sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function cpf($num){ $num = preg_replace('/[^0-9]/', '', $num); if($num == "11111111111" || $num == "22222222222" || $num == "33333333333" || $num == "44444444444" || $num == "55555555555" || $num == "66666666666" || $num == "77777777777" || $num == "88888888888" || $num == "99999999999" || $num == "00000000000"){ return false; } return strlen($num) == 11 && self::_cpf_cnpj($num, 9) && self::_cpf_cnpj($num, 10); }
verifica CPF
entailment
public static function WhatBrowser($browser=''){ $ua = strtolower($_SERVER['HTTP_USER_AGENT']); if($browser=="ie"){ if(strpos($ua, 'msie') == true ){ return true;}else{return false;} }else if($browser=="ie7"){ if(strpos($ua, 'msie 7.0') == true ){ return true;}else{return false;} }else if($browser=="ie8"){ if(strpos($ua, 'msie 8.0') == true ){ return true;}else{return false;} }else if($browser=="chrome"){ if(strpos($ua, 'chrome') == true ){ return true;}else{return false;} }else if($browser=="firefox"){ if(strpos($ua, 'firefox') == true ){ return true;}else{return false;} }else if($browser=="safari"){ if(strpos($ua, 'safari') == true ){ return true;}else{return false;} }else if($browser=="iphone"){ if(strpos($ua, 'iphone') == true ){ return true;}else{return false;} }else if($browser=="ipad"){ if(strpos($ua, 'ipad') == true ){ return true;}else{return false;} }else if($browser=="android"){ if(strpos($ua, 'android') == true ){ return true;}else{return false;} }else if($browser=="webos"){ if(strpos($ua, 'webos') == true ){ return true;}else{return false;} }else if($browser=="mobile"){ if(stripos($ua,'android') !== false || stripos($ua,'iPad') !== false || stripos($ua,'iPhone') !== false || stripos($ua,'iPod') !== false || stripos($ua,'webOS') !== false ) { return true;} }else{ return false; } }
responde Browser
entailment
public static function Compactar($b,$bolean) { if($bolean==false){return $b;} ob_start("compactar"); $b = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $b); $b = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $b); return $b; }
compacta codigo HTML
entailment
public static function dt2br($var,$separa="/"){ if(preg_match('/([012][0-9]|3[01]|[0-9])\/([0-9]|[0-9]{2})\/([0-9]{4})/', $var, $array)) return self::checkDtbr($array[1], $array[2], $array[3],$separa); else if(preg_match('/([0-9]{4})\-([0-9]|[0-9]{2})\-([012][0-9]|3[01]|[0-9])/', $var, $array)) return self::checkDtbr($array[3], $array[2], $array[1],$separa); }
transforma data 1992-08-14 para 14/08/1992
entailment
public static function dttm2br($var,$separador="/"){ if(preg_match('/([0-9]{4})\-([0-9]{2})\-([012][0-9]|3[01])[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})/', $var, $array)){ $dt = self::checkDtbr($array[3], $array[2], $array[1],$separador); if($dt && ($array[4] != '00' || $array[5] != '00')) $dt .= ' '.$array[4].':'.$array[5]; return $dt; } }
transforma datetime do servidor US para data e hora BR
entailment
public static function checkDtbr($dia, $mes, $ano,$separa){ if(checkdate($mes, $dia, $ano)) return $dia.$separa.$mes.$separa.$ano; }
function auxiliar
entailment
public function getImageType() { $this->imageType = ($this->imageType === 'jpg') ? 'jpeg' : $this->imageType; $this->imageType = ( in_array($this->imageType, $this->imageTypes) ) ? $this->imageType : 'png'; return $this->imageType; }
Get image type @return string
entailment
public function create($width = null, $height = null) { $this->width = ($width) ? $width : $this->width; $this->height = ($height) ? $height : $this->height; $imageType = $this->getImageType(); $createFunc = ($imageType === 'gif') ? 'imagecreate' : 'imagecreatetruecolor'; $this->image = $createFunc($this->width, $this->height); $bgColor = $this->backgroundColor; $backgroundColor = imagecolorallocate($this->image, $bgColor[0], $bgColor[1], $bgColor[2]); imagefilledrectangle($this->image, 0, 0, $this->width, $this->height, $backgroundColor); $this->drawText(); if ($this->drawBorder) { $this->drawBorder(); } if ($this->drawLine) { $this->drawLine(); } if ($this->drawPixel) { $this->drawPixel(); } return $this; }
Captcha image creator @param int $width null @param int $height null @return $this
entailment
protected function randomLetters() { for ($i = 0; $i < $this->length; $i++) { $letters = $this->letters[mt_rand(0, count($this->letters) - 1)]; $this->code .= $letters[mt_rand(0, strlen($letters) - 1)]; } }
Random generation English & Numbers letters @return void
entailment
protected function randomChinese() { if ( function_exists('mb_substr') ) { $len = mb_strlen($this->chineseCharacters, 'utf-8'); for ($i = 0; $i < $this->length; $i++) { $this->code .= mb_substr($this->chineseCharacters, mt_rand(0, $len - 1), 1, 'utf-8'); } } }
Random generation chinese characters @return void
entailment
protected function randomMixed() { $characters = implode('', $this->letters) . $this->chineseCharacters; if (function_exists('mb_substr')) { $len = mb_strlen($characters, 'utf-8'); for ($i = 0; $i < $this->length; $i++) { $this->code .= mb_substr($characters, mt_rand(0, $len - 1), 1, 'utf-8'); } } }
Random generation mixed characters @return void
entailment
protected function drawText() { /** * 0 Numbers * 1 Pure English letters * 2 English letters & Numbers mixed * 3 chinese characters * 4 All mixed */ switch($this->randomType) { case 0: $this->randomNumbers(); break; case 1: $this->randomPureLetters(); break; case 3: $this->randomChinese(); break; case 4: $this->randomMixed(); break; case 2: default: $this->randomLetters(); break; } if (!$this->fontFile) { $this->fontFile = __DIR__ . '../../Fonts/verdana.ttf'; } if (!file_exists($this->fontFile)) { throw new \InvalidArgumentException('Font file ' . $this->fontFile . ' not found.'); } $textColor = imagecolorallocate($this->image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); $x = ($this->width - ($this->fontSize * $this->length)) / 2; $y = $this->fontSize + ($this->height - $this->fontSize) / 2; $fontFile = (is_array($this->fontFile)) ? $this->fontFile[array_rand($this->fontFile)] : $this->fontFile; imagettftext($this->image, $this->fontSize , mt_rand(-8, 8), $x, $y, $textColor, $fontFile, $this->code); }
Draw text characters to image @return void
entailment
protected function drawBorder() { $borderColor = imagecolorallocate($this->image, 0, 0, mt_rand(50, 255)); imagerectangle($this->image, 0, 0, $this->width - $this->borderWidth, $this->height - $this->borderWidth, $borderColor); }
Draw border @return void
entailment
protected function drawLine() { $lineColor = imagecolorallocate($this->image, mt_rand(50, 255), mt_rand(100, 255), mt_rand(0, 255)); for($i = 0; $i < $this->lines; $i++) { imageline($this->image, 0, mt_rand() % $this->height, $this->width, mt_rand() % $this->height, $lineColor); } }
Draw lines @return void
entailment
protected function drawPixel() { $pixelColor = imagecolorallocate($this->image, mt_rand(0, 255), mt_rand(100, 255), mt_rand(50, 255)); for($i = 0; $i< mt_rand(1000, 1800); $i++) { imagesetpixel($this->image, mt_rand() % $this->width, mt_rand() % $this->height, $pixelColor); } }
Draw pixel points @return void
entailment
public function display() { $imageType = $this->getImageType(); header('Content-type: image/' . $imageType); $imageFunc = 'image' . $imageType; $imageFunc($this->image); $this->destroy($this->image); return $this; }
Display captcha image in page @return $this
entailment
public function save($filename) { $type = pathinfo($filename, PATHINFO_EXTENSION); $type = ($type === 'jpg') ? 'jpeg' : $type; $type = (in_array($type, $this->imageTypes)) ? $type : 'png'; header('Content-type: image/' . $type); $imageFunc = 'image' . $type; $imageFunc($this->image, $filename); $this->destroy($this->image); return $this; }
Save captcha image file @param string $filename @return $this
entailment
public function gotoURL($url, $base = true) { if ($base) { $url = $this->app->baseURL . $url; } $this->js('location.href="'.$url.'";'); }
Using javascript location.href go to url @param string $url @param bool $base true @return string
entailment
protected function redirect($path) { $path = str_replace('//', '/', $this->app->baseURL . $path); $this->app->redirect($path); }
Redirect controller @param string $path @return void
entailment
protected function render($tpl, array $data = []) { $suffix = $this->app->config('template.suffix'); $suffix = (empty($suffix)) ? $this->viewSuffix : $suffix; $tpl .= $suffix; $this->app->render($tpl, $data); }
Override \Slim\Slim::render method on controller @param string $tpl @param array $data [] @param string $suffix @return void
entailment
protected function getFilePath() { $path = $this->cachePath . DIRECTORY_SEPARATOR . $this->cacheDirectory . DIRECTORY_SEPARATOR; $path = str_replace(['\\\\', '//'], [DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], $path); return $path; }
Get cache file path @return string
entailment
protected function getFileName($key) { $file = $this->getFilePath() . $this->encrypt($key) . $this->fileExtension; return $file; }
Get cache filename @param string $key @return string
entailment
public function set($key, $value, $expireTime = null) { if ( $expireTime && !is_int($expireTime) ) { throw new \InvalidArgumentException('cache expire time must be integer.'); } $this->expireTime = ($expireTime) ? $expireTime : $this->expireTime; return $this->write($key, $value); }
Set cache key and write to cache file @param string $key @param string $value @param int $expireTime null @return bool @throws InvalidArgumentException @throws FileCacheException
entailment
protected function write($file, $value) { $key = $file; $path = $this->getFilePath(); if ( !file_exists($dir) ) { mkdir($path, 0777, true); } $file = $this->getFileName($key); $value = serialize($value); $value = ($this->base64Encode) ? base64_encode($value) : $value; if ( !file_put_contents($file, $value) ) { throw new FileCacheException('File write failure.'); } if ( !chmod($file, 0777) ) { throw new FileCacheException('Failed to set file permissions.'); } if ( !touch($file, time() + $this->expireTime) ) { throw new FileCacheException('Failed to change file time.'); } static::$keys[$key] = true; return true; }
Write to cache file @param string $file @param string $value @return bool @throws FileCacheException
entailment
protected function read($file) { $data = null; $key = $file; $file = $this->getFileName($file); if ( file_exists($file)) { // if cache file not expire if (filemtime($file) >= time()) { echo "read cache<br/>"; $data = file_get_contents($file); $data = ($this->base64Encode) ? base64_decode($data) : $data; $data = unserialize($data); static::$keys[$key] = true; } else { unset(static::$keys[$key]); unlink($file); } } return $data; }
Read cache file @param string $file @return mixed|null
entailment
public function has($key) { $file = $this->getFileName($key); if ( !file_exists($file) ) { return false; } // if cache file expire if ( filemtime($file) >= time() ) { static::$keys[$key] = true; return true; } else { unset(static::$keys[$key]); unlink($file); return false; } }
Check has cache key @param string $key @return bool
entailment
public function remove($key) { $file = $this->getFileName($key); if ( !file_exists($file) ) { return false; } unset(static::$keys[$key]); return (unlink($file))? true : false; }
Remove cache key @param string $key @return bool
entailment
public function clear() { echo $path = $this->getFilePath(); $files = glob($path . '*' . $this->fileExtension); foreach ($files as $file) { // if cache file expire, delete cache file if ( time() > filemtime($file) ) { @unlink($file); } } }
Clear expire cache file @return void
entailment
public function clearAll() { $path = $this->getFilePath(); $files = glob($path . '*' . $this->fileExtension); foreach ($files as $file) { @unlink($file); } static::$keys = []; }
Delete all cache files @return void
entailment
public function setDefaultOptions() { curl_setopt_array($this->curl, [ CURLOPT_TIMEOUT => $this->timeout, CURLOPT_NOSIGNAL => $this->nosignal, CURLOPT_FILETIME => $this->fileTime, CURLOPT_USERAGENT => $this->userAgent, CURLOPT_HEADER => $this->header, CURLOPT_HTTPHEADER => $this->headers, CURLOPT_RETURNTRANSFER => $this->returnTransfer, CURLOPT_SSL_VERIFYPEER => $this->sslVerifyPeer, CURLOPT_SSL_VERIFYHOST => $this->sslVerifyHost, CURLOPT_FRESH_CONNECT => $this->freshConnect ]); }
Default cURL options @return void
entailment
public function method($method) { $this->headers = array_merge($this->headers, array('X-HTTP-Method-Override: ' . $method)); $this->setOption(CURLOPT_CUSTOMREQUEST, $method); $this->setOption(CURLOPT_HTTPHEADER, $this->headers); }
Set cURL method @param string $method @return void
entailment
public function error() { $this->errors = [ 'code' => curl_errno($this->curl), 'message' => curl_error($this->curl) ]; return $this->error(); }
Get cURL errors @return mixed
entailment
public function send($url, $method = 'GET', $data = null, callable $callback = null) { $this->curl($url); $this->setDefaultOptions(); if (is_array($this->options)) { if (count($this->options) > 0) { foreach ($this->options as $key => $value) { $this->setOption($key, $value); } } } if ($method !== self::GET) { $this->method($method); } if ($method === self::POST || $method === self::PUT || $method === self::DELETE) { $this->setOption(CURLOPT_POSTFIELDS, $data); } $response = $this->execute(); if (!$response) { $this->error(); } $this->getInfo(); $this->close(); if ( is_callable($callback) ) { $callback($this->response, $this->info, $this->errors); } return $response; }
Send Http query @param string $url @param string $method GET @param string|array $data null @param callable $callback null @return mixed
entailment
public function head($url, $fields = null, callable $callback = null) { $this->send($url, self::HEAD, $fields, $callback); }
HTTP HEAD method @param $url @param string $fields null @param callable $callback null
entailment
public function get($url, $queries = null, callable $callback = null) { if ( is_array($queries) ) { $queries = '?' . http_build_query($queries); } return $this->send($url . $queries, self::GET, [], $callback); }
HTTP GET method @param string $url @param array|string $queries null @param callable $callback null @return mixed
entailment
public function post($url, array $fields = [], callable $callback = null) { return $this->send($url, self::POST, $fields, $callback); }
HTTP POST method @param string $url @param array $fields [] @param callable $callback null @return mixed
entailment
public function put($url, $fields = null, callable $callback = null) { $fields = (is_array($fields)) ? http_build_query($fields) : $fields; return $this->send($url, self::PUT, $fields, $callback); }
HTTP PUT method @param string $url @param string|array $fields null @param callable $callback null @return mixed
entailment
public function delete($url, $fields = null, callable $callback = null) { $fields = ( is_array($fields) ) ? http_build_query($fields) : $fields; return $this->send($url, self::DELETE, $fields, $callback); }
HTTP DELETE method @param string $url @param string|array $fields null @param callable $callback null @return mixed
entailment
public function patch($url, $fields = null, callable $callback = null) { $this->send($url, self::PATCH, $fields, $callback); }
HTTP PATCH method @param $url @param string $fields null @param callable $callback null
entailment
public function options($url, $fields = null, callable $callback = null) { $this->send($url, self::OPTIONS, $fields, $callback); }
HTTP OPTIONS method @param $url @param null $fields null @param callable $callback null
entailment
public function trace($url, $fields = null, callable $callback = null) { $this->send($url, self::TRACE, $fields, $callback); }
HTTP TRACE method @param $url @param null $fields null @param callable $callback null
entailment
public function boot() { parent::boot(); if (Request::is('*/gallery/gallery/*')) { Route::bind('gallery', function ($gallery) { $galleryrepo = $this->app->make('Litecms\Gallery\Interfaces\GalleryRepositoryInterface'); return $galleryrepo->findorNew($gallery); }); } }
Define your route model bindings, pattern filters, etc. @param \Illuminate\Routing\Router $router @return void
entailment
protected function mapWebRoutes() { if (request()->segment(1) == 'api' || request()->segment(2) == 'api') { return; } Route::group([ 'middleware' => 'web', 'namespace' => $this->namespace, 'prefix' => trans_setlocale(), ], function ($router) { require (__DIR__ . '/../../routes/web.php'); }); }
Define the "web" routes for the package. These routes all receive session state, CSRF protection, etc. @return void
entailment
public function make() { $this->pageTotal = ceil($this->total / $this->num); $this->page = ($this->page > $this->pageTotal) ? $this->pageTotal : $this->page; $this->offset = ($this->page == 1) ? 0 : (($this->page - 1) * $this->num); $this->prev = ($this->page == 1) ? 1 : $this->page - 1; $this->next = ($this->page == $this->pageTotal) ? $this->pageTotal : $this->page + 1; $this->last = $this->pageTotal; $this->range(); }
Make paginator params @return void
entailment
public function range() { $start = $this->page - $this->range; $start = ($start < 1) ? 1 : $start; $end = $this->page + $this->range; $end = ($end > $this->pageTotal) ? $this->pageTotal : $end; $this->ranges = [ 'start' => $start, 'end' => $end ]; return $this->ranges; }
Set/Get paginator ranges @return array
entailment
public function query() { $model = $this->model; $this->query = $model->select($this->select) ->where($this->where) ->orderBy($this->orderBy, $this->sortBy) ->take($this->num) ->offset($this->offset); $this->sql = $this->query->getQuery()->toSql(); $this->data = $this->query->get()->toArray(); return $this->data; }
Sql query @param bool $toJson @return array
entailment
public static function mask($txt='', $mascara='') { if(empty($txt) || empty($mascara)){ return false; }else if($mascara == Mask::TELEFONE){ $mascara = (strlen($txt) == 10 ? '(##)####-####' : '(##)#####-####'); }else if($mascara == Mask::DOCUMENTO){ $mascara = (strlen($txt) == 14 ? Mask::CNPJ : (strlen($txt) == 11? Mask::CPF : '')); } return Mask::MaskFactory($txt , $mascara); }
Adiciona máscara em um texto @param string $txt Texto @param Mask $mascara @return string (Texto com mascara)
entailment
public static function maskFactory($txt='', $mascara='') { $txt = Mask::unmask($txt); if(empty($txt) || empty($mascara)){ return false; } $qtd = substr_count($mascara, '#'); if($qtd != strlen($txt) && strlen($txt)!=0) { return false; }else{ $string = str_replace(" ", "", $txt); for ($i = 0; $i < strlen($string); $i++) { $pos = strpos($mascara, "#"); $mascara[$pos] = $string[$i]; } return $mascara; } }
Adiciona máscara @param string $texto @return string (Texto com a mascara)
entailment
public static function isNumericArray($array){ if (!is_array($array)) { return false; } $current = 0; foreach (array_keys($array) as $key) { if ($key !== $current) { return false; } $current++; } return true; }
Retorna booleano se uma função é uma matriz numérica plana / seqüencial @param array $array An array to test @return boolean
entailment
public static function arrayFlatten(array $array, $preserve_keys = true){ $flattened = array(); array_walk_recursive($array, function ($value, $key) use (&$flattened, $preserve_keys) { if ($preserve_keys && !is_int($key)) { $flattened[$key] = $value; } else { $flattened[] = $value; } }); return $flattened; }
Aplique uma matriz multidimensional em uma matriz unidimensional. * @param array $array The array to flatten @param boolean $preserve_keys Whether or not to preserve array keys. Keys from deeply nested arrays will overwrite keys from shallowy nested arrays @return array
entailment
public static function arrayPluck(array $array, $field, $preserve_keys = true, $remove_nomatches = true){ $new_list = array(); foreach ($array as $key => $value) { if (is_object($value)) { if (isset($value->{$field})) { if ($preserve_keys) { $new_list[$key] = $value->{$field}; } else { $new_list[] = $value->{$field}; } } elseif (!$remove_nomatches) { $new_list[$key] = $value; } } else { if (isset($value[$field])) { if ($preserve_keys) { $new_list[$key] = $value[$field]; } else { $new_list[] = $value[$field]; } } elseif (!$remove_nomatches) { $new_list[$key] = $value; } } } return $new_list; }
Aceita uma matriz e retorna uma matriz de valores da matriz conforme especificado pelo $field. Por exemplo, se a matriz estiver cheia de objetos e você chamar util::array_pluck ($array, 'name'), a função será retornar uma matriz de valores de $array[]->name. @param array $array An array @param string $field The field to get values from @param boolean $preserve_keys Whether or not to preserve the array keys @param boolean $remove_nomatches If the field doesn't appear to be set, remove it from the array @return array
entailment
public function isInScope(UriInterface $source, UriInterface $comparator): bool { $source = $this->removeIgnoredComponents($source); $comparator = $this->removeIgnoredComponents($comparator); $sourceString = (string) $source; $comparatorString = (string) $comparator; if ($sourceString === $comparatorString) { return true; } if ($this->isSourceUrlSubstringOfComparatorUrl($sourceString, $comparatorString)) { return true; } if (!$this->areSchemesEquivalent($source->getScheme(), $comparator->getScheme())) { return false; } if (!$this->areHostsEquivalent($source->getHost(), $comparator->getHost())) { return false; } return $this->isSourcePathSubstringOfComparatorPath($source->getPath(), $comparator->getPath()); }
Is the given comparator url in the scope of the source url? Comparator is in the same scope as the source if: - scheme is the same or equivalent (e.g. http and https are equivalent) - hostname is the same or equivalent (equivalency looks at subdomain equivalence e.g. example.com and www.example.com) - path is the same or greater (e.g. sourcepath = /one/two, comparatorpath = /one/two or /one/two/* Comparison ignores: - port - user - pass - query - fragment @param UriInterface $source @param UriInterface $comparator @return bool
entailment
public function set() { $args = func_get_args(); $count = func_num_args(); if ( is_array($args[0]) ) { foreach ($args[0] as $key => $value) { if ($key === 'path') { $this->setPath($value); continue; } if (property_exists($this, $key)) { $this->$key = $value; } } } elseif ($count === 2) { if ($args[0] === 'path') { $this->setPath($args[1]); return ; } if (property_exists($this, $args[0])) { $this[$args[0]] = $args[1]; } } }
Settings @param string|array $key null @param string $value null @return void
entailment
public function setPath($path) { if (!file_exists($path)) { mkdir($path, 0777, true); } $this->path = $path; }
Setting logs path @param string $path @return void
entailment
protected function defaultMessageFormatReplaces() { $this->messageFormatReplaces = [ $this->label, str_repeat(' ', 9 - strlen($this->label)), date('Y-m-d H:i:s e O'), $this->message ]; }
Default log message format replaces @return void
entailment
protected function messageFormatParser() { $this->label = $this->levels[$this->level]; $this->messageOutput = str_replace( $this->getMessageFormatSearchs(), $this->getMessageFormatReplaces(), $this->getMessageFormat() ); }
Log message format parser @return void
entailment
public function write($content, $level) { $this->message = (string) $content; $this->level = $level; if ( is_callable($this->writeBeforeHandle) ) { $this->writeBefore($this->writeBeforeHandle); if (!$this->customMessageFormatParser) { $this->defaultMessageFormatReplaces(); } } else { $this->defaultMessageFormatReplaces(); } $this->messageFormatParser(); if ( !$this->resource ) { $this->filename = date($this->dateFormat); if ( !empty($this->extension) ) { $this->filename .= '.' . $this->extension; } $this->resource = fopen($this->path . DIRECTORY_SEPARATOR . $this->filename, 'a'); } fwrite($this->resource, $this->messageOutput . PHP_EOL); }
Write to log file @param mixed $content @param int $level @return void
entailment
public static function numberToWords($number, $measurement='') { if(strpos($number, ',')!== false) { $number = str_replace(',', '.', $number); } if (!is_numeric($number)) { return false; } if ($number > PHP_INT_MAX) { // overflow return false; } if ($number < 0) { return 'menos ' . HumanizeBR::numberToWords(abs($number)); } $string = $fraction = null; if(strpos($number, '.')!== false) { list($number, $fraction) = explode('.', $number); } switch (true) { case $number < 21: $string = HumanizeBR::DICTIONARY[$number]; break; case $number < 100: $tens = ((int) ($number / 10)) * 10; $units = $number % 10; $string = HumanizeBR::DICTIONARY[$tens]; if ($units) { $string .= ' e ' . HumanizeBR::DICTIONARY[$units]; } break; case $number < 1000: $hundreds = floor($number / 100)*100; $remainder = $number % 100; if($number==100){ $string = HumanizeBR::DICTIONARY[$hundreds][0]; }else if($number<200){ $string = HumanizeBR::DICTIONARY[$hundreds][1]; }else{ $string = HumanizeBR::DICTIONARY[$hundreds]; } if($remainder){ $string .= ' e ' . HumanizeBR::numberToWords($remainder); } break; default: $baseUnit = pow(1000, floor(log($number, 1000))); $numBaseUnits = (int) ($number / $baseUnit); $remainder = $number % $baseUnit; if($baseUnit == 1000) { $string = HumanizeBR::numberToWords($numBaseUnits) . ' ' . HumanizeBR::DICTIONARY[1000]; }elseif($numBaseUnits == 1) { $string = HumanizeBR::numberToWords($numBaseUnits) . ' ' . HumanizeBR::DICTIONARY[$baseUnit][0]; }else{ $string = HumanizeBR::numberToWords($numBaseUnits) . ' ' . HumanizeBR::DICTIONARY[$baseUnit][1]; } if($remainder){ $string .= $remainder < 100 ? ' e ' : ', '; $string .= HumanizeBR::numberToWords($remainder); } break; } if (null !== $fraction && is_numeric($fraction)) { $string .= ' ponto '; $string .= HumanizeBR::numberToWords($fraction); } return $string.($measurement!=''?' '. $measurement : '' ); }
Converts a unix timestamp to a relative time string, such as "3 days ago" or "2 weeks ago". @param int number @return string
entailment
public static function humanTimeDiff($from, $to = '', $as_text = false, $suffix = ' atrás'){ if ($to == '') { $to = time(); } $from = new \DateTime(date('Y-m-d H:i:s', $from)); $to = new \DateTime(date('Y-m-d H:i:s', $to)); $diff = $from->diff($to); if ($diff->y > 1) { $text = $diff->y . ' anos'; } elseif ($diff->y == 1) { $text = '1 ano'; } elseif ($diff->m > 1) { $text = $diff->m . ' meses'; } elseif ($diff->m == 1) { $text = '1 mês'; } elseif ($diff->d > 7) { $text = ceil($diff->d / 7) . ' semanas'; } elseif ($diff->d == 7) { $text = '1 semana'; } elseif ($diff->d > 1) { $text = $diff->d . ' dias'; } elseif ($diff->d == 1) { $text = '1 dia'; } elseif ($diff->h > 1) { $text = $diff->h . ' horas'; } elseif ($diff->h == 1) { $text = ' 1 hora'; } elseif ($diff->i > 1) { $text = $diff->i . ' minutos'; } elseif ($diff->i == 1) { $text = '1 minuto'; } elseif ($diff->s > 1) { $text = $diff->s . ' segundos'; } else { $text = '1 segundo'; } if ($as_text) { $text = explode(' ', $text, 2); $text = HumanizeBR::numberToWords($text[0]) . ' ' . $text[1]; } return trim($text) . $suffix; }
Converts a unix timestamp to a relative time string, such as "3 days ago" or "2 weeks ago". @param int $from The date to use as a starting point @param int $to The date to compare to, defaults to now @param string $suffix The string to add to the end, defaults to " ago" @return string
entailment
public function isPubliclyRoutable(): bool { try { $ip = IpUtilsFactory::getAddress($this->host); if ($ip->isPrivate()) { return false; } if ($ip->isLoopback()) { return false; } if ($ip instanceof IPv4 && $this->isIpv4InUnroutableRange($ip)) { return false; } return true; } catch (\UnexpectedValueException $unexpectedValueException) { return true; } }
@return bool @throws InvalidExpressionException
entailment
private function isIpv4InUnroutableRange(IPv4 $ip): bool { foreach ($this->unrouteableRanges as $ipRange) { if ($ip->matches(new Subnet($ipRange))) { return true; } } return false; }
@param IPv4 $ip @return bool @throws InvalidExpressionException
entailment
public function config(array $configs) { foreach($configs as $key => $value) { if (property_exists($this, $key)) { $this->$key = $value; } } }
Set configs @access public @param array $configs @return void
entailment
public function upload($name) { // When $_FILES[$name]['name'] empty if ( empty($_FILES[$name]['name']) ) { $this->error($this->errors['empty'], 0, true); return false; } $this->files = $_FILES[$name]; // When the directory is not exist. if( !file_exists($this->savePath) ) { $this->error($this->errors['not_exist'], 0, true); return false; } // When the directory is not written if( !is_writable($this->savePath) ) { $this->error($this->errors['unwritable'], 0, true); return false; } return $this->moveFile(); }
Execute upload @access public @param string $name fileInput's name @return bool
entailment
private function moveFile() { $this->setSeveName(); $files = $this->files; if ($this->formats != "" && !in_array($this->fileExt, $this->formats)) { $formats = implode(',', $this->formats); $message = "Your upload file " . $files["name"] . " is " . $this->fileExt; $message .= " format, The system is not allowed to upload, you can only upload " . $formats . " format's file."; $this->error($message, 0, true); return false; } if ($files["size"] / 1024 > $this->maxSize) { $message = "Your upload file " . $files["name"] . " The file size exceeds of the system limit size " . $this->maxSize . " KB."; $this->error($message, 0, true); return false; } // When can't covered if (!$this->cover) { // The same file already exists if (file_exists($this->savePath . $this->saveName)) { $this->error($this->saveName . $this->errors['same_file'], 0, true); return false; } } if ( !@move_uploaded_file( $files["tmp_name"], iconv("utf-8", "gbk", $this->savePath . $this->saveName) ) ) { switch ($files["error"]) { case '0': $message = "File upload successfully."; break; case '1': $message = "The uploaded file exceeds the value of the upload_max_filesize option in php.ini."; break; case '2': $message = "The size of the upload file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form."; break; case '3': $message = "Only part of the file is uploaded."; break; case '4': $message = "No file is uploaded."; break; case '6': $message = "Can't find upload temp directory."; break; case '7': $message = "Error writing file to hard drive"; break; case '8': $message = "An extension has stopped the upload of the file."; break; case '999': default: $message = "Unknown error, please check the file is damaged, whether the oversized and other reasons."; break; } $this->error($message, 0, true); return false; } @unlink($files["tmp_name"]); // Delete temporary file return true; }
Check and move the upload file @access private @return bool
entailment
private function randomFileName() { $fileName = ''; // Generate the datetime format file name if ($this->randomNameType == 1) { date_default_timezone_set($this->timezone); $date = date($this->randomLength); echo $dir = $this->savePath . $date; if ( !file_exists($dir) ) { mkdir($dir, $this->mode, true); } $fileName = $date . '/' . time(); } elseif ($this->randomNameType == 2) // Generate random character file name { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; $max = strlen($chars) - 1; mt_srand( (double) microtime() * 1000000); for ($i = 0; $i < $this->randomLength; $i++) { $fileName .= $chars[mt_rand(0, $max)]; } } else { } $this->fileExt = $this->getFileExt($this->files["name"]); $fileName = $fileName . '.' . $this->fileExt; return $fileName; }
Generate random file name @access private @return string $fileName
entailment
private function setSeveName() { $this->saveName = $this->randomFileName(); if ($this->saveName == '') { $this->saveName = $this->files['name']; } }
Set Saved filename for database @access private @return void
entailment
public function message($message, $success = 0, $return = false) { $array = array( 'success' => $success, 'message' => $message ); $url = $this->saveURL . $this->saveName; // Cross-domain redirect to callback url if ($this->redirect) { $this->redirectURL .= '&success=' . $success . '&message=' . $message; if ($success == 1) { $this->redirectURL .= '&url=' . $url; } $this->redirect(); } else { echo "success =>" . $success; if ($success == 1) { $array['url'] = $url; } $this->message = $array = json_encode($array); if ($return) { return $array; } else { echo $array; } } }
Errors message handle @access public @param string $message @param int $success @param bool $return false @return array|string
entailment
public function index(GalleryRequest $request) { $view = $this->response->theme->listView(); if ($this->response->typeIs('json')) { $function = camel_case('get-' . $view); return $this->repository ->setPresenter(\Litecms\Gallery\Repositories\Presenter\GalleryPresenter::class) ->$function(); } $galleries = $this->repository->paginate(); return $this->response->title(trans('gallery::gallery.names')) ->view('gallery::gallery.index', true) ->data(compact('galleries')) ->output(); }
Display a list of gallery. @return Response
entailment
public function show(GalleryRequest $request, Gallery $gallery) { if ($gallery->exists) { $view = 'gallery::gallery.show'; } else { $view = 'gallery::gallery.new'; } return $this->response->title(trans('app.view') . ' ' . trans('gallery::gallery.name')) ->data(compact('gallery')) ->view($view, true) ->output(); }
Display gallery. @param Request $request @param Model $gallery @return Response
entailment
public function edit(GalleryRequest $request, Gallery $gallery) { return $this->response->title(trans('app.edit') . ' ' . trans('gallery::gallery.name')) ->view('gallery::gallery.edit', true) ->data(compact('gallery')) ->output(); }
Show gallery for editing. @param Request $request @param Model $gallery @return Response
entailment
public function update(GalleryRequest $request, Gallery $gallery) { try { $attributes = $request->all(); $gallery->update($attributes); return $this->response->message(trans('messages.success.updated', ['Module' => trans('gallery::gallery.name')])) ->code(204) ->status('success') ->url(guard_url('gallery/gallery/' . $gallery->getRouteKey())) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('gallery/gallery/' . $gallery->getRouteKey())) ->redirect(); } }
Update the gallery. @param Request $request @param Model $gallery @return Response
entailment
public function destroy(GalleryRequest $request, Gallery $gallery) { try { $gallery->delete(); return $this->response->message(trans('messages.success.deleted', ['Module' => trans('gallery::gallery.name')])) ->code(202) ->status('success') ->url(guard_url('gallery/gallery/0')) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('gallery/gallery/' . $gallery->getRouteKey())) ->redirect(); } }
Remove the gallery. @param Model $gallery @return Response
entailment
public function executeSQL($sql){ //verifica se o banco de dados está conectado if(!isset($GLOBALS['CONN'])){ $this->setError('Não há conexão com o banco de dados <i><b>$</b>GLOBALS["CONN"]</i>'); } //se for teste, exibe SQL e não executa; if($this->getError()!=''){ echo "Em:".$sql.'<br/><br/>'.utf8_decode($this->getError()); exit; } //salva última SQL realizada $this->setlastQuery($sql); //se for teste, exibe SQL e não executa; if($this->getTest()==true){ echo $this->getlastQuery(); exit; } //Executa SQL usando ADODB if($this->getDebugger()==true){ $GLOBALS['CONN']->debug = true; } $s=$GLOBALS['CONN']->Execute($sql); if($s===false){ $erro=$GLOBALS['CONN']->ErrorMsg(); $GLOBALS['f']->writeErrorSQL("[".date('d/m/Y H:m:i')."] - ".$erro); //armazenda erro em $lastQuery $this->setLastError($erro); //armazenda erro na lista de erro $allError do tipo ARRAY $this->setAllError($erro); if($this->getDebugger()==true){ //exit(); } }else{ //Armazenda a quantidade de resultados $this->setRecords($s->RecordCount()); //salva na variavel query o objeto retornado do ADODB $this->setQuery($s); return $s; } }
EXECUTA
entailment
public function Select($executar=true){ $q='SELECT '; $q.=($this->getFields()!=''?$this->getFields():'*'); $q.=' FROM '; if($this->getTable()!=''){ $q.=$this->getTable(); }else{ $this->setError('É necessário atribuir um valor ao método <i><b>getTable</b></i>'); } //insere WHERE if($this->getWhere()!=''){ $q.=' WHERE '.$this->getWhere(); } //insere WHERE if($this->getGroupBy()!=''){ $q.=' GROUP BY '.$this->getGroupBy(); } //insere ORDER BY if($this->getOrderBy()!=''){ $q.=' ORDER BY '.$this->getOrderBy(); } //insere LIMIT if($this->getLimit()!=''){ $q.=' LIMIT '.$this->getLimit(); } if($executar==false){ return $q; }else{ $this->executeSQL($q); } }
SELECT
entailment
public function Insert(){ $q='INSERT INTO '; if($this->getTable()!=''){ $q.=$this->getTable(); }else{ $this->setError('É necessário atribuir um valor ao método <i><b>getTable</b></i>'); } //insere SET if($this->getSet()!=''){ $q.=' SET '; $q.=$this->getSet(); }else{ $this->setError('É necessário atribuir um valor ao método <i><b>getSet</b></i>'); } //insere WHERE if($this->getWhere()!=''){ $q.=' WHERE '.$this->getWhere(); } $insert=$this->executeSQL($q); //armazena ultimo id inserido no banco if($this->getLastError()==''){ $inserted=$GLOBALS['CONN']->Insert_ID(); $this->setInsertId($inserted); } }
INSERIR
entailment
public function Update($executar=true){ $q='UPDATE '; if($this->getTable()!=''){ $q.=$this->getTable(); }else{ $this->setError('É necessário atribuir um valor ao método <i><b>getTable</b></i>'); } $q.=' SET '; //insere SET if($this->getSet()!=''){ $q.=$this->getSet(); }else{ $this->setError('É necessário atribuir um valor ao método <i><b>getSet</b></i>'); } //insere WHERE if($this->getWhere()!=''){ $q.=' WHERE '.$this->getWhere(); }else{ $this->setError('É necessário atribuir um valor ao <i><b>getWhere</b></i>'); } //insere LIMIT if($this->getLimit()!=''){ $q.=' LIMIT '.$this->getLimit(); } $q=str_replace(array('"NULL"',"'NULL'"), 'NULL', $q); if($executar==false){ return $q; }else{ return $this->executeSQL($q); } }
INSERIR
entailment
public function Delete(){ $q='DELETE FROM '; if($this->getTable()!=''){ $q.=$this->getTable(); }else{ $this->setError('É necessário atribuir um valor ao método <i><b>getTable</b></i>'); } //insere WHERE if($this->getWhere()!=''){ $q.=' WHERE '.$this->getWhere(); } //insere LIMIT if($this->getLimit()!=''){ $q.=' LIMIT '.$this->getLimit(); } return $this->executeSQL($q); }
INSERIR
entailment
public function clear(){ $this->setFields(''); $this->setSet(''); $this->setLimit(''); $this->setWhere(''); $this->setOrderBy(''); $this->setGroupBy(''); $this->setRecords(''); $this->setQuery(''); }
Limpa variaveis para novas consultas
entailment
public function getRow(){ if($GLOBALS['CONN']->_connectionID==false){ return false; } $s=$this->getQuery(); return $s->FetchRow(); }
CONTROLE DE TABLE
entailment
public function setSet($v=''){ if(is_array($v)){ $q=''; if(count($v)>0){ foreach($v as $key=>$value){ $q.= "`{$key}` = '{$value}', "; } $q=substr($q, 0, -2); } $this->set=$q; }else{ $this->set=$v; } }
CONTROLE DE SET
entailment
public function setWhere($v=''){ if(is_array($v)){ $q=''; if(count($v)>0){ foreach($v as $key=>$value){ $q.= " {$key}= '{$value}' AND"; } $q=substr($q, 0, -3); } $this->where=$q; }else{ $this->where=$v; } }
CONTROLE DE WHERE
entailment
public function setError($v=''){ $tmp=array(); $tmp=$this->getError('array'); $tmp[]=$v; $this->error=$tmp; }
CONTROLE DE ALL ERROR
entailment
public function setAllError($v=''){ $tmp=array(); $tmp=$this->getAllError('array'); $tmp[]=$v; $this->allError=$tmp; }
CONTROLE DE ALL ERROR
entailment
public function getAllError($t='text'){ $tmp=''; if(count($this->allError)>0){ $tmp='<table>'; for ($i=0; $i < count($this->allError); $i++) { $tmp.='<tr>'; $tmp.=' <td width="100">#ERRO N&deg; '.($i+1).'</td>'; $tmp.=' <td>SQL: '.strip_tags($this->getLastQuery()).'</td>'; $tmp.='</tr>'; $tmp.='<tr> <td></td><td><i>'.$this->allError[$i].'</i></td></tr>'; $tmp.='<tr> <td colspan="2" height="15"></td></tr>'; } $tmp.='</table>'; } if($t=='array'){ return $this->allError; }else{ return $tmp; } }
parametro('array') - Retorna tabela HTML de erros
entailment
public function run(ApplicationInterface $app) { $config = $app->getConfig(); $servicesFactory = $app->getServicesFactory(); $this->injectInitialServices($app); foreach ($config->get(Service::class, []) as $serviceSpec) { $servicesFactory->registerService($serviceSpec); } }
@param ApplicationInterface $app @throws \ObjectivePHP\ServicesFactory\Exception\Exception
entailment
protected function injectInitialServices(ApplicationInterface $app) { $app->getServicesFactory()->registerService( ['id' => 'application', 'instance' => $app], // all those are here for convenience only since 'application' gives access to all of them ['id' => 'config', 'instance' => $app->getConfig()], ['id' => 'events-handler', 'instance' => $app->getEventsHandler()] ) ; }
@param ApplicationInterface $app @throws \ObjectivePHP\ServicesFactory\Exception\Exception @internal param ApplicationInterface $application
entailment
public function set($reference, $value) { $reference = $this->computeKeyFQN($reference); self::$data[$reference] = $value; return $this; }
@param $key @param $value @return $this @throws \ObjectivePHP\Primitives\Exception
entailment
public function get($reference, $default = null) { $reference = $this->computeKeyFQN($reference); // first look for exact match if (isset(self::$data[$reference])) { return self::$data[$reference]; } // otherwise use a matcher to return a // collection of matching entries $matcher = $this->getMatcher(); $matches = new Collection(); Collection::cast(self::$data)->each(function (&$value, $key) use ($matcher, $reference, $matches) { if ($matcher->match($reference, $key)) { $matches[$key] = $value; } }); if (!$matches->isEmpty()) return $matches; return $default; }
@param $reference @param null $default @return mixed|null @throws \ObjectivePHP\Primitives\Exception
entailment
public function remove($reference) { $reference = $this->computeKeyFQN($reference); $matcher = $this->getMatcher(); Collection::cast(self::$data)->each(function (&$value, $key) use ($matcher, $reference) { if ($matcher->match($reference, $key)) { unset(self::$data[$key]); } }); return $this; }
@param $key @return $this
entailment
public function getImportCurrentDataApplication(){ $app_config = $this->getAppConfigYaml(); foreach ($app_config[$this->getApplicationName()] as $key => $value) { if(isset($value['address_uri'])){ $addresUri = explode('/', $value['address_uri']); if(!empty($addresUri[0]) && strpos($_SERVER['HTTP_HOST'] , $addresUri[0]) !== false ){ $this->setEnvironmentStatus($key); if($this->getEnvironmentStatus()=='production' || $this->getEnvironmentStatus()=='staging'){ $dir_path = 'prod'; }else if($this->getEnvironmentStatus()=='testing' || $this->getEnvironmentStatus()=='development'){ $dir_path = 'dev'; if(file_exists(PATH_ROOT.'/app/dev/') && file_exists(PATH_ROOT.'/app/prod/')){ unlink(file_exists(PATH_ROOT.'/app/dev/')); } } if(!file_exists(PATH_ROOT.'/app/'.$dir_path)){ if($this->getEnvironmentStatus()!='development' && $this->getEnvironmentStatus()!='testing' && file_exists(PATH_ROOT.'/app/dev/')){ rename(PATH_ROOT.'/app/dev/', PATH_ROOT.'/app/'.$dir_path ); }else if($this->getEnvironmentStatus()!='production' && $this->getEnvironmentStatus()!='staging' && file_exists(PATH_ROOT.'/app/prod/')){ rename(PATH_ROOT.'/app/prod/', PATH_ROOT.'/app/'.$dir_path ); } } $this->setApplicationPath('/app/'.$dir_path.'/'.$this->getApplicationName()); break; } } } //Get address_uri of file app_config.yml if($this->getEnvironmentStatus()=='production'){ if(isset($app_config[$this->getNameApplication()]['production'])){ $c=$app_config[$this->getNameApplication()]['production']; $this->setAddressUri($c['address_uri']); $this->setUseHttps($c['use_https']); $this->setUseWww($c['use_www']); } }else if($this->getEnvironmentStatus()=='staging'){ if(isset($app_config[$this->getNameApplication()]['staging'])){ $c=$app_config[$this->getNameApplication()]['staging']; $this->setAddressUri($c['address_uri']); $this->setUseHttps($c['use_https']); $this->setUseWww($c['use_www']); } }else if($this->getEnvironmentStatus()=='testing'){ if(isset($app_config[$this->getNameApplication()]['testing'])){ $c=$app_config[$this->getNameApplication()]['testing']; $this->setAddressUri($c['address_uri']); $this->setUseHttps($c['use_https']); $this->setUseWww($c['use_www']); } }else if($this->getEnvironmentStatus()=='development'){ if(isset($app_config[$this->getNameApplication()]['development'])){ $c=$app_config[$this->getNameApplication()]['development']; $this->setAddressUri($c['address_uri']); $this->setUseHttps($c['use_https']); $this->setUseWww($c['use_www']); } } //Get address_uri of file app_config.yml if($this->getEnvironmentStatus()=='production'){ if(isset($app_config['address_uri_production'])){ $this->setAddressUri($app_config['address_uri_production']); } }else if($this->getEnvironmentStatus()=='staging'){ if(isset($app_config['address_uri_staging'])){ $this->setAddressUri($app_config['address_uri_staging']); } }else if($this->getEnvironmentStatus()=='testing'){ if(isset($app_config['address_uri_testing'])){ $this->setAddressUri($app_config['address_uri_testing']); } }else if($this->getEnvironmentStatus()=='development'){ if(isset($app_config['address_uri_development'])){ $this->setAddressUri($app_config['address_uri_development']); } } if($this->getAddressUri()==''){ throw new \Exception("Você deve definir uma url em address_uri_".$this->getEnvironmentStatus().' no arquivo de configuração do app_config.yml'); } $this->setConnectionDb($app_config); }
configura applications
entailment
private function setSystemConfigs(){ /* Set limiter cache, default: private */ if($this->getCacheLimiter() != 'nochace' && $this->getCacheLimiter() != 'private' && $this->getCacheLimiter() != 'private_no_expire' && $this->getCacheLimiter() != 'public'){ $this->getCacheLimiter('private'); } session_cache_limiter($this->getCacheLimiter()); //Update path to save sessions if(!file_exists(PATH_ROOT.$this->getSessionSavePath()) || $this->getSessionSavePath()==''){ mkdir(PATH_ROOT.$this->getSessionSavePath(), 0777, true); } /* Set time in seconds for expite sessions */ session_cache_expire((empty($this->getCacheExpire())?1000:$this->getCacheExpire())); session_save_path(PATH_ROOT.$this->getSessionSavePath()); session_start(); ob_start(); $dir_session = session_save_path(); if ($handle = opendir($dir_session)) { foreach (glob($dir_session."sess_*") as $filename) { if (filemtime($filename) + $this->getCacheExpire() < time()) { @unlink($filename); } } } /*Set time zone for system */ if($this->getChaceNavegation()==false){ header('Expires: Sun, 01 Jan 2017 00:00:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-Control: post-checkcheck=0, pre-check=0', FALSE); header('Pragma: no-cache'); } /*Set time zone for system */ if($this->getDateTimezone()!=''){ ini_set('date.timezone', $this->getDateTimezone()); } if($this->getUploadMaxFilesize()!=''){ ini_set("upload_max_filesize", $this->getUploadMaxFilesize()); } if($this->getPostMaxSize()!=''){ ini_set('post_max_size',$this->getPostMaxSize()); } //Set path for errors if(!file_exists(PATH_ROOT.$this->getErrorLog()) || $this->getErrorLog()==''){ $difLog = explode('/',PATH_ROOT.$this->getErrorLog()); array_pop($difLog); $difLog = implode('/', $difLog).'/'; if(!file_exists($difLog) || $difLog==''){ mkdir($difLog, 0777); }else{ chmod($difLog, 0777); } $file = fopen(PATH_ROOT.$this->getErrorLog(), "w+") or die("Arquivo de log não pode ser aberto!"); chmod(PATH_ROOT.$this->getErrorLog(), 0777); $txt = "Created: ".date('d-m-Y H:m:i')."\n"; fwrite($file, $txt); fclose($file); } ini_set('error_log' , PATH_ROOT.$this->getErrorLog()); // error log if($this->getDisplayErrors()!='On' && $this->getDisplayErrors()!='Off' && $this->getDisplayErrors()!=''){ throw new \Exception("setSystemConfigs() Valor de display_errors deve ser 'On', 'Off' ou ''."); }else if($this->getDisplayErrors()!=''){ ini_set('display_errors' , $this->getDisplayErrors()); } //Set if have log errors if($this->getLogErrors()!='On' && $this->getLogErrors()!='Off' && $this->getLogErrors()!=''){ throw new \Exception("setSystemConfigs() Valor de log_errors deve ser 'On', 'Off' ou ''."); }else if($this->getLogErrors()!=''){ ini_set('log_errors' , $this->getLogErrors()); } //Set o tipo de erro if($this->getErrorReporting()!='' && array_search($this->getErrorReporting(), array("E_ERROR","E_WARNING","E_PARSE","E_NOTICE","E_CORE_ERROR","E_CORE_WARNING","E_COMPILE_ERROR","E_COMPILE_WARNING","E_USER_ERROR","E_USER_WARNING","E_USER_NOTICE","E_ALL","E_STRICT","E_RECOVERABLE_ERROR","0"))==''){ $this->setErrorReporting('E_ALL'); } if($this->getErrorReporting()!=''){ switch ($this->getErrorReporting()) { case "E_ERROR" : error_reporting(E_ERROR); break; case "E_WARNING" : error_reporting(E_WARNING); break; case "E_PARSE" : error_reporting(E_PARSE); break; case "E_NOTICE" : error_reporting(E_NOTICE); break; case "E_CORE_ERROR" : error_reporting(E_CORE_ERROR); break; case "E_CORE_WARNING" : error_reporting(E_CORE_WARNING); break; case "E_COMPILE_ERROR" : error_reporting(E_COMPILE_ERROR); break; case "E_COMPILE_WARNING" : error_reporting(E_COMPILE_WARNING); break; case "E_USER_ERROR" : error_reporting(E_USER_ERROR); break; case "E_USER_WARNING" : error_reporting(E_USER_WARNING); break; case "E_USER_NOTICE" : error_reporting(E_USER_NOTICE); break; case "E_ALL" : error_reporting(E_ALL); break; case "E_STRICT" : error_reporting(E_STRICT); break; case "E_RECOVERABLE_ERROR" : error_reporting(E_RECOVERABLE_ERROR); break; default: error_reporting(0); break; } } /* Define o limitador de cache para 'private' */ if($this->getLocale()==''){ $this->setLocale('pt_BR'); } setlocale(LC_CTYPE, $this->getLocale()); }
realiza as configurações do sistema
entailment
private function setSystemConfigsCurrentApplication(){ //verifica use_https if($this->getUseHttps()!='On' && $this->getUseHttps()!='Off'){ $this->setUseHttps('Off'); } //verifica use_www if($this->getUseWww()!='On' && $this->getUseWww()!='Off'){ $this->setUseWww('Off'); } //verifica address_uri if($this->getAddressUri()=='' || preg_match('/^http/', $this->getAddressUri()) || preg_match('/^www/', $this->getAddressUri())){ throw new \Exception("setSystemConfigsCurrentApplication() Valor de address_uri deve conter a url da aplicação sem http e sem www. ex: google.com"); } //define url padrão da aplicação $this->setPathBaseHref(($this->getUseHttps()=='On'?'https://':'http://').($this->getUseWww()=='On'?'www.':'').$this->getAddressUri()); $tmp=explode('/', preg_replace('/^[\/]*(.*?)[\/]*$/', '\\1', $_SERVER['REQUEST_URI'])); $k=array_search('public', $tmp); if($k!=''){ unset($tmp[$k]); } if($this->getUseHttps()=='On' || (preg_match('/^www/', $this->getAddressUri()) && $this->getUseWww()=='Off') || (!preg_match('/^www/', $this->getAddressUri()) && $this->getUseWww()=='On') || $k!=''){ if( (!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on") || (preg_match('/^www/', $_SERVER["HTTP_HOST"])===1 && $this->getUseWww()=='Off') || (preg_match('/^www/', $_SERVER["HTTP_HOST"])===0 && $this->getUseWww()=='On') ){ header('Location: '.($this->getUseHttps()=='On'?'https://':'http://').($this->getUseWww()=='On'?'www.':'').$this->getAddressUri()); exit; } } }
realiza as configurações da atual aplicação
entailment
public function setApplication($a='',$l=''){ if(is_string($a)){ // adicona novas applications // 'default' => /app/default/ é padrão $this->application[$a] = $l; }else if(is_array($a)){ foreach ($a as $key => &$value) { $this->application[$key] = $value; } } }
Set applications of system
entailment
public function getApplicationUseNow(){ $tmp=explode('/', preg_replace('/^[\/]*(.*?)[\/]*$/', '\\1', $_SERVER['REQUEST_URI'])); foreach ($tmp as $key => $value) { if(isset($tmp[$key]) && is_array($this->getApplication()) && array_key_exists($tmp[$key],$this->getApplication())){ for ($i=0; $i < $key; $i++) { array_shift($tmp); } $app_path = $this->getApplication(); $app_public = $app_path[$tmp[0]]['path_public']; $app_path = $app_path[$tmp[0]]['path_app']; $this->setNameApplication($tmp[0]); } } for ($i=0; $i < count($key); $i++) { array_shift($tmp); } if(!isset($app_path)){ $app_path = $this->getApplication(); $app_public=$app_path['default']['path_public']; $app_path=$app_path['default']['path_app']; $this->setNameApplication('default'); } $this->setApplicationName($app_path); if(!file_exists(PATH_ROOT.$app_public)){ throw new \Exception("app_public não foi encontrado em: ".PATH_ROOT.$app_public); }else{ $this->setPublicPath($app_public); } }
Capture path of application, using url or subdomin
entailment
private function getApplicationPathFiles(){ $this->setPathURI(explode('/', preg_replace('/^[\/]*(.*?)[\/]*$/', '\\1', $_SERVER['REQUEST_URI']))); $a=$this->getPathURI(); if($this->getEnvironmentStatus()=='development'){ $nun_level=explode("/", $this->getAddressUri()); for ($i=0; $i < count($nun_level)-2; $i++) { array_shift($a); } $this->setPathURI($a); } foreach ($a as $key => $value) { if($this->getNameApplication()==$value){ unset($a[$key]); } } if(reset($a)=='helpers'){ array_shift($a); $helpers=true; }else{ $helpers=false; } $this->setPathURI($a); foreach ($a as $key => $value) { $this->posURL[]=$value; } $url_array=$this->getPathURI(); $directory_action=$directory_ctrl=$directory_view=''; if($helpers==true){ $directory_action = $this->getPathApplication().'helpers'; do{ if( in_array(current($url_array), scandir($directory_action))){ $directory_action.='/'.current($url_array); next($url_array); $dir = false; if(isset($url_array[key($url_array)+1])){ $this->setMethodsURI($url_array[key($url_array)+1]); } }else if( in_array(current($url_array).'.php', scandir($directory_action))){ $directory_action.='/'.current($url_array).'.php'; next($url_array); $dir = true; }else{ $directory_action.='/index.php'; $dir = true; } }while(!$dir); }else{ $directory_ctrl = $this->getPathApplication().'controllers'; $directory_view = $this->getPathApplication().'views/pages'; $this->urlCompletePath = substr($this->getPathBaseHref(),0,-1); do{ if( (file_exists($directory_view) && in_array(current($url_array), scandir($directory_view))) || (file_exists($directory_ctrl) && in_array(current($url_array), scandir($directory_ctrl))) ){ $directory_ctrl.='/'.current($url_array); $directory_view.='/'.current($url_array); $this->urlCompletePath.='/'.(current($url_array)!='index'?current($url_array):''); next($url_array); $dir = false; if(isset($url_array[key($url_array)])){ $this->setMethodsURI($url_array[key($url_array)]); } }else if( (file_exists($directory_view) && in_array(current($url_array).'.php', scandir($directory_view))) || (file_exists($directory_ctrl) && in_array(current($url_array).'.php', scandir($directory_ctrl))) ){ $directory_ctrl.='/'.current($url_array).'.php'; $directory_view.='/'.current($url_array).'.php'; $this->urlCompletePath.='/'.(current($url_array)!='index'?current($url_array):''); next($url_array); if(isset($url_array[key($url_array)])){ $this->setMethodsURI($url_array[key($url_array)]); } $dir = true; }else{ if(isset($url_array[key($url_array)])){ $this->setMethodsURI($url_array[key($url_array)]); } if((count($url_array)==0 || is_int(key($url_array)) == false) || (isset($url_array) && $url_array[0]=='')){ $directory_ctrl.='/index.php'; $directory_view.='/index.php'; $this->urlCompletePath.='/'; } $dir = true; } }while(!$dir); } //verifica se existe a view if($helpers==true && file_exists($directory_action) && is_file($directory_action) ){ // inicia actoin $this->setPageAction($directory_action); $this->instanceTemplate($this->getPageAction()); if (strpos($_SERVER['HTTP_ACCEPT'], 'htm') === false) { }else{ $helpers=false; $this->setPageView($this->getPathApplication('views/error/','404.php')); } }else if((file_exists($directory_ctrl) && is_file($directory_ctrl)) || (file_exists($directory_view) && is_file($directory_view))){ // inicia controller $this->setPageCtrl($directory_ctrl); $this->setPageView($directory_view); } if(!file_exists($directory_ctrl) || !is_file($directory_ctrl)){ $this->setPageCtrl($this->getPathApplication('controllers/error/','404.php')); } if(!file_exists($directory_view) || !is_file($directory_view)){ $this->setPageView($this->getPathApplication('views/error/','404.php')); } if($helpers==false){ $this->instanceTemplate($this->getPathApplication('views/layout/','template.php')); } }
retur folder about aplicatoins
entailment
public function insertLoadPageLog($timer= '', $page=''){ if($this->getLimitDataLoadPage()!=0){ $text=''; $addLine=true; if(file_exists(PATH_ROOT."/dwphp/storage/log/loadpage.log")){ $f=fopen(PATH_ROOT."/dwphp/storage/log/loadpage.log","r+"); while (!feof($f)) { //pega conteudo da linha $line=fgets($f); if($line!=''){ $lines=explode('|',$line); if(isset($lines[0]) && $lines[0]==$page){ //define que o arquivo será reescrito $addLine=false; $text=substr($text, 0,-1); //$text.=$timer.";\n"; $lines[1] = explode(';',$lines[1]); array_pop($lines[1]); if(count($lines[1])>$this->getLimitDataLoadPage()-1){ while ( count($lines[1])>(int)$this->getLimitDataLoadPage()-1) { array_shift($lines[1]); } } $t=implode($lines[1], ";"); if(strlen($text)!=0){ $text.= "\n"; } $text.= $page."|".$t.';'.$timer.";\n"; //echo $page."|".$t.$timer.";\n"; }else{ $text.=$line; } } } fclose($f); } $f2=fopen(PATH_ROOT."/storage/log/loadpage.log","w+"); if($addLine==true){ $text.=$page.'|'.$timer.";\n"; } fwrite($f2, $text); fclose($f2); } }
/* GET PATH
entailment
private function instanceTemplate($pathFile){ if(file_exists($pathFile)){ require_once $pathFile; if(class_exists('App\\template', true)){ $n='App\template'; $this->template = new $n($this); if(file_exists($this->getpageCtrl())){ require_once $this->getpageCtrl(); if(class_exists('\App\Framework\controller', false)){ $this->controller = new \App\Framework\controller($this); if($this->getMethodsURI()!=''){ if(method_exists($this->controller,$this->getMethodsURI())){ $methods_action=$this->getMethodsURI(); $this->controller->$methods_action(); } } if(method_exists($this->controller,'show')){ $this->controller->show(); } if(isset($this->ctrlFunction) && !empty($this->ctrlFunction)){ try{ $methods = get_class_methods($this->controller); $function = $this->ctrlFunction; if(in_array($function, $methods)){ $this->controller->$function(); }else{ throw new \Exception(utf8_decode("Não foi encontrada a função " . $function . " no controller " . $this->getPageCtrl())); } }catch(\Exception $e){ $this->notificationErrors('Funcção não encontrada:' ,$e->getMessage()); exit; } } } if($this->getPageView() == ''){ exit; } } try { if(isset($this->controller)){ $this->controller->constructPage(); }else if(isset($this->template)){ $this->template->constructPage(); } } catch (Exception $e) { $this->notificationErrors('Não inciado constructPage', $e->getMessage()); exit; } }else if(class_exists('App\\action', true)){ $n='App\action'; $this->action = new $n($this); } } }
/* GET PATH
entailment
public function requireModels($file=''){ //$d = PATH_ROOT.$this->getApplicationPath().'/'.$this->getEnvironmentStatus().'/models'.($file!=''?'/'.$file:''); $d = PATH_ROOT.'/app/'.$this->getEnvironmentStatus().'/models'.($file!=''?'/'.$file:''); if(file_exists($d) && is_file($d)){ require_once $d; } }
GETTERS AND SETTERES
entailment
public function make($file, $content, $recursive = false) { if ($this->exists($this->getPath($file))) { throw new FileAlreadyExists; } $this->put($file, $content, 0, $recursive); }
Create file with provided content if not exists. @param $file @param $content @param bool $recursive @throws FileAlreadyExists
entailment
public function get($file) { $path = $this->getPath($file); if (! file_exists($path)) { throw new FileDoesNotExists; } return file_get_contents($path); }
Get file contents. @param $file @return string @throws FileDoesNotExists
entailment