File: //home/artinside/sites.artinside.com.br/paliar/source/Boot/Helpers.php
<?php
/**
* ####################
* ### VALIDATE ###
* ####################
*/
/**
* @param string $email
* @return bool
*/
function is_email(string $email): bool
{
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
/**
* @param string $password
* @return bool
*/
function is_passwd(string $password): bool
{
if (password_get_info($password)['algo'] || (mb_strlen($password) >= CONF_PASSWD_MIN_LEN && mb_strlen($password) <= CONF_PASSWD_MAX_LEN)) {
return true;
}
return false;
}
function sum_cart(?array $cartSession): int
{
if (isset($cartSession)) {
$count = 0;
foreach ($cartSession as $c):
$count += $c['qtd'];
endforeach;
return $count;
}
return 0;
}
function is_cpf($cpf) : bool
{
// Extrai somente os números
$cpf = preg_replace( '/[^0-9]/is', '', $cpf );
// Verifica se foi informado todos os digitos corretamente
if (strlen($cpf) != 11) {
return false;
}
// Verifica se foi informada uma sequência de digitos repetidos. Ex: 111.111.111-11
if (preg_match('/(\d)\1{10}/', $cpf)) {
return false;
}
// Faz o calculo para validar o CPF
for ($t = 9; $t < 11; $t++) {
for ($d = 0, $c = 0; $c < $t; $c++) {
$d += $cpf($c) * (($t + 1) - $c);
}
$d = ((10 * $d) % 11) % 10;
if ($cpf($c) != $d) {
return false;
}
}
return true;
}
function is_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
// Valida tamanho
if (strlen($cnpj) != 14)
return false;
// Verifica se todos os digitos são iguais
if (preg_match('/(\d)\1{13}/', $cnpj))
return false;
// Valida primeiro dígito verificador
for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
{
$soma += $cnpj[$i] * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
if ($cnpj[12] != ($resto < 2 ? 0 : 11 - $resto))
return false;
// Valida segundo dígito verificador
for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++)
{
$soma += $cnpj[$i] * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
return $cnpj[13] == ($resto < 2 ? 0 : 11 - $resto);
}
function is_date($date, $format = 'Y-m-d H:i:s') : bool
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
function coupon_validate(string $code) : ?\Source\Models\Ecommerce\Coupon
{
$date = date("Y-m-d h:i:s");
$c = (new \Source\Models\Ecommerce\Coupon())->find("code = :code", "code={$code}");
if($c->count()){
$n = $c->fetch();
if($date <= $n->valid_at AND $n->uses < $n->quantity){
return $n;
}
return null;
}
return null;
}
/**
* ##################
* ### MENU ###
* ##################
*/
/**
* @param string $string
* @return string
*/
function menuCategories(string $type = "product")
{
$categories = new \Source\Models\Category();
$res = $categories->findByType($type)->order("title ASC");
return $res->fetch(true);
}
function menuCollections()
{
$collections = new \Source\Models\Ecommerce\Collection();
$res = $collections->find();
return $res->fetch(true);
}
function maintenance()
{
$maintenance = (new \Source\Models\Config())->findById(1);
return $maintenance->maintenance;
}
function scripts(string $column)
{
$maintenance = (new \Source\Models\Scripts())->findById(1);
return $maintenance->$column;
}
/**
* ##################
* ### STRING ###
* ##################
*/
/**
* @param string $string
* @return string
*/
function str_slug(string $string): string
{
$string = filter_var(mb_strtolower($string), FILTER_SANITIZE_STRIPPED);
$formats = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜüÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿRr"!@#$%&*()_-+={[}]/?;:.,\\\'<>°ºª';
$replace = 'aaaaaaaceeeeiiiidnoooooouuuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr ';
$slug = str_replace(["-----", "----", "---", "--"], "-",
str_replace(" ", "-",
trim(strtr(utf8_decode($string), utf8_decode($formats), $replace))
)
);
return $slug;
}
/**
* @param string $string
* @return string
*/
function str_studly_case(string $string): string
{
$string = str_slug($string);
$studlyCase = str_replace(" ", "",
mb_convert_case(str_replace("-", " ", $string), MB_CASE_TITLE)
);
return $studlyCase;
}
/**
* @param string $string
* @return string
*/
function str_camel_case(string $string): string
{
return lcfirst(str_studly_case($string));
}
/**
* @param string $string
* @return string
*/
function str_title(string $string): string
{
return mb_convert_case(filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS), MB_CASE_TITLE);
}
/**
* @param string $text
* @return string
*/
function str_textarea(string $text): string
{
$text = filter_var($text, FILTER_SANITIZE_STRIPPED);
$arrayReplace = [" ", " ", " ", " ", " "];
return "<p>" . str_replace($arrayReplace, "</p><p>", $text) . "</p>";
}
/**
* @param string $string
* @param int $limit
* @param string $pointer
* @return string
*/
function str_limit_words(string $string, int $limit, string $pointer = "..."): string
{
$string = trim(filter_var($string, FILTER_DEFAULT));
$arrWords = explode(" ", $string);
$numWords = count($arrWords);
if ($numWords < $limit) {
return $string;
}
$words = implode(" ", array_slice($arrWords, 0, $limit));
return "{$words}{$pointer}";
}
/**
* @param string $string
* @param int $limit
* @param string $pointer
* @return string
*/
function str_limit_chars(string $string, int $limit, string $pointer = "..."): string
{
$string = trim(filter_var($string, FILTER_DEFAULT));
if (mb_strlen($string) <= $limit) {
return $string;
}
$chars = mb_substr($string, 0, mb_strrpos(mb_substr($string, 0, $limit), " "));
return "{$chars}{$pointer}";
}
/**
* @param string $price
* @return string
*/
function str_price(?string $price): string
{
return number_format((!empty($price) ? $price : 0), 2, ",", ".");
}
/**
* @param string|null $search
* @return string
*/
function str_search(?string $search): string
{
if (!$search) {
return "all";
}
// $search = preg_replace("/[^a-z0-9A-Z\@\ ]/", "", $search);
return (!empty($search) ? $search : "all");
}
function card_first_digits(string $cardNumber):string
{
$n = str_replace([" ", " ", " "], "", trim($cardNumber));
$first = substr($n, 0, 6);
return $first;
}
function card_last_digits(string $cardNumber):string
{
$n = str_replace([" ", " ", " "], "", trim($cardNumber));
$last = substr($n, -4, 4);
return $last;
}
/**
* ###############
* ### URL ###
* ###############
*/
/**
* @param string $path
* @return string
*/
function url(string $path = null): string
{
if (strpos($_SERVER['HTTP_HOST'], "localhost")) {
if ($path) {
return CONF_URL_TEST . "/" . ($path[0] == "/" ? mb_substr($path, 1) : $path);
}
return CONF_URL_TEST;
}
if ($path) {
return CONF_URL_BASE . "/" . ($path[0] == "/" ? mb_substr($path, 1) : $path);
}
return CONF_URL_BASE;
}
function get_url(int $level = 0): ?string
{
$url = explode("/", $_GET['route']);
return $url[$level];
}
/**
* @param string $path
* @return string
*/
function url_images(string $path = null): string
{
return url()."/".CONF_UPLOAD_DIR."/".$path;
}
/**
* @return string
*/
function url_back(): string
{
return ($_SERVER['HTTP_REFERER'] ?? url());
}
/**
* @param string $url
*/
function redirect(string $url): void
{
header("HTTP/1.1 302 Redirect");
if (filter_var($url, FILTER_VALIDATE_URL)) {
header("Location: {$url}");
exit;
}
if (filter_input(INPUT_GET, "route", FILTER_DEFAULT) != $url) {
$location = url($url);
header("Location: {$location}");
exit;
}
}
/**
* ##################
* ### ASSETS ###
* ##################
*/
/**
* @return \Source\Models\User|null
*/
function user(): ?\Source\Models\User
{
return \Source\Models\Auth::user();
}
/**
* @return \Source\Core\Session
*/
function session(): \Source\Core\Session
{
return new \Source\Core\Session();
}
/**
* @param string|null $path
* @param string $theme
* @return string
*/
function theme(string $path = null, string $theme = CONF_VIEW_THEME): string
{
if (strpos($_SERVER['HTTP_HOST'], "localhost")) {
if ($path) {
return CONF_URL_TEST . "/themes/{$theme}/" . ($path[0] == "/" ? mb_substr($path, 1) : $path);
}
return CONF_URL_TEST . "/themes/{$theme}";
}
if ($path) {
return CONF_URL_BASE . "/themes/{$theme}/" . ($path[0] == "/" ? mb_substr($path, 1) : $path);
}
return CONF_URL_BASE . "/themes/{$theme}";
}
/**
* @param string $image
* @param int $width
* @param int|null $height
* @return string
*/
function image(?string $image, int $width, int $height = null): ?string
{
if ($image) {
return url() . "/" . (new \Source\Support\Thumb())->make($image, $width, $height);
} else{
return url() . "/" . (new \Source\Support\Thumb())->make(NO_IMAGE, $width, $height);
}
}
/**
* ################
* ### DATE ###
* ################
*/
/**
* @param string $date
* @param string $format
* @return string
* @throws Exception
*/
function date_fmt(?string $date, string $format = "d/m/Y H\hi"): string
{
$date = (empty($date) ? "now" : $date);
return (new DateTime($date))->format($format);
}
/**
* @param string $date
* @return string
* @throws Exception
*/
function date_fmt_br(?string $date): string
{
$date = (empty($date) ? "now" : $date);
return (new DateTime($date))->format(CONF_DATE_BR);
}
/**
* @param string $date
* @return string
* @throws Exception
*/
function date_fmt_app(?string $date): string
{
$date = (empty($date) ? "now" : $date);
return (new DateTime($date))->format(CONF_DATE_APP);
}
function month_dif(string $date1, string $date2): string
{
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
return (($year2 - $year1) * 12) + ($month2 - $month1);
}
/**
* @param string|null $date
* @return string|null
*/
function date_fmt_back(?string $date): ?string
{
if (!$date) {
return null;
}
if (strpos($date, " ")) {
$date = explode(" ", $date);
return implode("-", array_reverse(explode("/", $date[0]))) . " " . $date[1];
}
return implode("-", array_reverse(explode("/", $date)));
}
function order_id(int $id, int $digits = 6) : string
{
return sprintf("%0{$digits}d", $id);
}
/**
* ####################
* ### PASSWORD ###
* ####################
*/
/**
* @param string $password
* @return string
*/
function passwd(string $password): string
{
if (!empty(password_get_info($password)['algo'])) {
return $password;
}
return password_hash($password, CONF_PASSWD_ALGO, CONF_PASSWD_OPTION);
}
/**
* @param string $password
* @param string $hash
* @return bool
*/
function passwd_verify(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
/**
* @param string $hash
* @return bool
*/
function passwd_rehash(string $hash): bool
{
return password_needs_rehash($hash, CONF_PASSWD_ALGO, CONF_PASSWD_OPTION);
}
/**
* #####################
* ### ECOMMERCE ###
* #####################
*/
function preco_real(?string $preco) : ?string
{
return number_format($preco, 2, ",", ".");
}
function discountPercent(float $propotionaPrice, float $price) : ?int
{
return ceil(-(($propotionaPrice/$price*100)-100));
}
function shippingBox():?stdClass
{
$cart = new \Anam\Phpcart\Cart(CARRINHO);
$result = new stdClass();
if($cart->count() >= 1){
$cubagem = 0;
$weight = 0;
foreach ($cart->getItems() as $item) {
$cubagem += ($item->weight * $item->width * $item->depth * $item->quantity) * 100;
$weight += $item->weight * $item->quantity;
}
if($cubagem < 2500){
$result->lenght = 16;$result->width = 16;$result->height = 9;$result->weight = $weight;
return $result;
}
if($cubagem < 4300){
$result->lenght = 27;$result->width = 18;$result->height = 9;$result->weight = $weight;
return $result;
}
if($cubagem < 17000){
$result->lenght = 27;$result->width = 36;$result->height = 18;$result->weight = $weight;
return $result;
}
if($cubagem < 45000){
$result->lenght = 50;$result->width = 30;$result->height = 30;$result->weight = $weight;
return $result;
}
if($cubagem < 64000){
$result->lenght = 40;$result->width = 40;$result->height = 40;$result->weight = $weight;
return $result;
}
if($cubagem < 125000){
$result->lenght = 50;$result->width = 50;$result->height = 50;$result->weight = $weight;
return $result;
}
if($cubagem < 274000){
$result->lenght = 65;$result->width = 65;$result->height = 65;$result->weight = $weight;
return $result;
}
}
return null;
}
function max_installments(float $value) : int
{
$installments = $value / CONF_MIN_INSTALLMENTS_VALUE;
if((int)$installments >= CONF_MAX_INSTALLMENTS){
return CONF_MAX_INSTALLMENTS;
}
if((int)$installments == 0){
return 1;
}
return (int)$installments;
}
/**
* @return int
*/
function searchArrayFrenet($service, $array, $search = "service_description", $result = "shipping_price" )
{
foreach ($array as $key => $val) {
if ($val[$search] === $service) {
return $array[$key][$result];
}
}
return "erro";
}
/**
* ###################
* ### REQUEST ###
* ###################
*/
/**
* @return string
*/
function csrf_input(): string
{
$session = new \Source\Core\Session();
$session->csrf();
return "<input type='hidden' name='csrf' value='" . ($session->csrf_token ?? "") . "'/>";
}
function csrf_input_alt(): string
{
$session = new \Source\Core\Session();
$session->csrfAlt();
return "<input type='hidden' name='csrf_alt' value='" . ($session->csrf_token_alt ?? "") . "'/>";
}
function status(string $status) : object
{
$st = new stdClass();
if($status == "paid"){
$st->icon = "fa-dollar-sign";
$st->class = "border-green";
$st->text = "Pagamento Concluído";
$st->content = "Seu pagamento foi aprovado, em breve estaremos postando seus produtos!";
$st->color = "#61A563";
return $st;
}
if($status == "authorized"){
$st->icon = "fa-dollar-sign";
$st->class = "border-green";
$st->text = "Pagamento Autorizado";
$st->content = "Seu pagamento foi autorizado, em breve estaremos postando seus produtos!";
$st->color = "#61A563";
return $st;
}
if($status == "shipped"){
$st->icon = "fa-dollar-sign";
$st->class = "border-green";
$st->text = "Enviado para Transportadora";
$st->content = "Você pode acompanhar a entrega nos correios com o código de rastreamento abaixo!";
$st->color = "#61A563";
return $st;
}
if($status == "processing"){
$st->icon = "fa-hourglass-half";
$st->class = "border-blue";
$st->text = "Em processamento";
$st->content = "Seu pagamento está em processamento, assim que alterar o status informamos.";
$st->color = "#009EBF";
return $st;
}
if($status == "waiting_payment"){
$st->icon = "fa-hourglass-half";
$st->class = "border-blue";
$st->text = "Aguardando Pagamento";
$st->content = "Seu pagamento está aguardando pagamento, efetue o pagamento do seu boleto dentro da data de vencimento para que possamos garantir a entrega de suas peças.";
$st->color = "#009EBF";
return $st;
}
if($status == "refused"){
$st->icon = "fa-times-circle";
$st->class = "border-red";
$st->text = "Pagamento Recusado";
$st->content = "Seu pagamento infelizmente foi recusado, favor tentar outra forma de pagamento.";
$st->color = "#EF4355";
return $st;
}
if($status == "canceled"){
$st->icon = "fa-times-circle";
$st->class = "border-red";
$st->text = "Pedido cancelado";
$st->content = "Seu pedido foi cancelado, caso tenha interesse favor refazer a compra!";
$st->color = "#EF4355";
return $st;
}
if($status == "refunded"){
$st->icon = "fa-times-circle";
$st->class = "border-violet";
$st->text = "Pagamento Devolvido";
$st->content = "Seu pagamento já foi devolvido, em caso de cartão de crédito ele será devolvido na própria fatura,
esse processo pode levar até 30 dias de acordo com a operadora de seu cartão!";
$st->color = "#8F6CAF";
return $st;
}
if($status == "pending_refund"){
$st->icon = "fa-times-circle";
$st->class = "border-violet";
$st->text = "Aguardando Devolução";
$st->content = "A devolução de seu pagamento já foi solicitado pela nossa equipe, em breve confirmaremos a conclusão!";
$st->color = "#8F6CAF";
return $st;
}
}
function verifyAddress($full = false)
{
$session = new \Source\Core\Session();
if ($session->has("cep") AND $full == false){
return $session->cep->cep;
}
if ($session->has("cep") AND $full == true){
return $session->cep;
}
return null;
}
/**
* @param $request
* @return bool
*/
function csrf_verify($request): bool
{
$session = new \Source\Core\Session();
if (empty($session->csrf_token) || empty($request['csrf']) || $request['csrf'] != $session->csrf_token) {
return false;
}
return true;
}
function csrf_verify_alt($request): bool
{
$session = new \Source\Core\Session();
if (empty($session->csrf_token_alt) || empty($request['csrf_alt']) || $request['csrf_alt'] != $session->csrf_token_alt) {
return false;
}
return true;
}
/**
* @return null|string
*/
function flash(): ?string
{
$session = new \Source\Core\Session();
if ($flash = $session->flash()) {
return $flash;
}
return null;
}
/**
* @param string $key
* @param int $limit
* @param int $seconds
* @return bool
*/
function request_limit(string $key, int $limit = 5, int $seconds = 60): bool
{
$session = new \Source\Core\Session();
if ($session->has($key) && $session->$key->time >= time() && $session->$key->requests < $limit) {
$session->set($key, [
"time" => time() + $seconds,
"requests" => $session->$key->requests + 1
]);
return false;
}
if ($session->has($key) && $session->$key->time >= time() && $session->$key->requests >= $limit) {
return true;
}
$session->set($key, [
"time" => time() + $seconds,
"requests" => 1
]);
return false;
}
/**
* @param string $field
* @param string $value
* @return bool
*/
function request_repeat(string $field, string $value): bool
{
$session = new \Source\Core\Session();
if ($session->has($field) && $session->$field == $value) {
return true;
}
$session->set($field, $value);
return false;
}
function gallery_id(int $size = 12): string
{
return substr(md5(time()), 0, $size);
}
function _mime_content_type($filename='')
{
$filename = escapeshellcmd($filename);
$command = "file -b --mime-type -m /usr/share/misc/magic {$filename}";
$mimeType = shell_exec($command);
return trim($mimeType);
}
/**
* ###################
* ### SESSION ###
* ###################
*/
function unsetSession(string $key) : bool
{
$destroy = new \Source\Core\Session();
if($destroy->unset($key)){
return true;
}
return false;
}