/** * @param array $patterns * @return \Closure */ protected static function __match(array $patterns) { return function (...$args) use($patterns) { // [a] -> Bool $patternApplies = function ($pattern) use($args) { /** @noinspection PhpParamsInspection */ return Logic::all(Arrays::zipWith(Lambda::apply(), Arrays::map(self::make(), Arrays::init($pattern)), $args)); }; try { /** @noinspection PhpParamsInspection */ $getMatchedImplementation = Lambda::compose(Arrays::last(), Arrays::first($patternApplies), Arrays::filter(function ($pattern) use($args) { return count($pattern) - 1 === count($args); })); return call_user_func_array($getMatchedImplementation($patterns), $args); } catch (\Exception $e) { throw new IncompletePatternMatchException('Incomplete pattern match expression.'); } }; }
public function factory() { if (File::exists($this->file)) { require_once $this->file; $instance = new $this->class(); $methods = get_class_methods($this->class); $tab = explode('\\', get_class($instance)); $item = Inflector::lower(Arrays::last($tab)); if (Arrays::in('init', $methods)) { $instance->init(); } $this->app->bindShared($this->type . '.' . $item, function ($app) use($instance) { return $instance; }); return $this; } else { throw new Exception("The file '{$file}' does not exist."); } }
private function clean($key, $force = false) { $now = time(); $file = $this->getFile('expires.' . $key . '.5'); $path = str_replace(DS . Arrays::last(explode(DS, $file)), '', $file); if (is_dir($path)) { $files = glob($path . DS . '*.php'); if (!empty($files)) { $when = (int) str_replace([$path . DS, '.php'], '', Arrays::first($files)); if ($when < $now || true === $force) { File::rmdir($path); $this->remove($key); } } } else { if (true === $force) { $this->remove($key); } } return $this; }
/** * [filter description] * @param [type] $filter [description] * @return [type] [description] */ public function filter($filter) { $account_id = isAke($filter, 'account_id', false); if (false === $account_id) { $user = session('user')->getUser(); $filter['account_id'] = (int) $user['id']; } $found = $this->findResto($filter); $spedispos = $found['specialites_dispo']; // foreach ($found['plats_dispo'] as $p) { // $geos = Model::Mealgeo()->where(['segment_id', '=', $p])->cursor(); // dd($geos->first()); // } // $spedispos = []; // foreach ($found['specialites_dispo'] as $idspe) { // $getids = unserialize(redis()->get('geos.spes.' . $idspe)); // $keep = false; // foreach ($found['plats_dispo'] as $idPlat) { // if (in_array($idPlat, $getids)) { // $keep = true; // break; // } // } // if ($keep) { // $spedispos[] = $idspe; // } // } $merged = array_values(array_unique(array_merge($spedispos, $found['families_specialites_dispo'], $found['pois_dispo'], $found['families_pois_dispo'], $found['plats_dispo'], $found['families_plats_dispo'], $found['types_auto_dispo'], $found['types_non_auto_dispo']))); asort($merged); $merged = array_values($merged); $optionsMacro = (include APPLICATION_PATH . DS . 'models/options/413.php'); $valuesActivities = array_get($optionsMacro, 'activites.values'); asort($found['preferences_dispo']); $found['preferences_dispo'] = array_values($found['preferences_dispo']); $adp = []; foreach ($found['activites_dispo'] as $ad) { $idap = Arrays::last(explode('_', $ad)); $adp[] = isset($valuesActivities[$idap]) ? $valuesActivities[$idap] : $ad; } asort($adp); $found['activites_dispo'] = array_values(array_unique($adp)); asort($found['thematiques_dispo']); $found['thematiques_dispo'] = array_values($found['thematiques_dispo']); asort($found['families_plats_dispo']); $found['families_plats_dispo'] = array_values($found['families_plats_dispo']); asort($found['plats_dispo']); $found['plats_dispo'] = array_values($found['plats_dispo']); asort($found['families_pois_dispo']); $found['families_pois_dispo'] = array_values($found['families_pois_dispo']); asort($found['pois_dispo']); $found['pois_dispo'] = array_values($found['pois_dispo']); asort($found['types_non_auto_dispo']); $found['types_non_auto_dispo'] = array_values($found['types_non_auto_dispo']); asort($found['types_auto_dispo']); $found['types_auto_dispo'] = array_values($found['types_auto_dispo']); $results = ['total' => $found['total'], 'distances' => isAke($found, 'distances', ['min' => 0, 'max' => 0]), 'specialites_dispo' => $spedispos, 'pois_dispo' => $found['pois_dispo'], 'families_pois_dispo' => $found['families_pois_dispo'], 'families_specialites_dispo' => $found['families_specialites_dispo'], 'plats_dispo' => $found['plats_dispo'], 'families_plats_dispo' => $found['families_plats_dispo'], 'types_auto_dispo' => $found['types_auto_dispo'], 'types_non_auto_dispo' => $found['types_non_auto_dispo'], 'thematiques_dispo' => $found['thematiques_dispo'], 'labels_dispo' => $found['labels_dispo'], 'activites_dispo' => $found['activites_dispo'], 'preferences_dispo' => $found['preferences_dispo']]; $idr = []; foreach ($found['restaurants'] as $resto) { $reseller_id = $idr[] = $resto['id']; } $rows = Model::Suggestion()->cursor(); $suggestions = []; foreach ($rows as $row) { $ids = []; foreach ($row['segments'] as $s) { $ids[] = $s['id']; } $plates = isAke($row, 'plats', []); foreach ($plates as $p) { if (fnmatch('*:*', $p)) { list($p, $ir) = explode(':', $p, 2); if (in_array($ir, $idr)) { $ids[] = $p; } } else { $ids[] = $p; } } foreach ($ids as $sId) { if (in_array($sId, $merged)) { $family = repo('segment')->getFamily((int) $row['segment_id']); $merged[] = $suggestions[] = (int) $row['segment_id']; foreach ($family as $child) { $merged[] = $suggestions[] = (int) $child['id']; } break; } } } $suggestions = array_unique($suggestions); $merged = array_unique($merged); asort($merged); $merged = array_values($merged); asort($suggestions); $suggestions = array_values($suggestions); $results['suggestions'] = $suggestions; $results['segments_dispos'] = $merged; if ($found['total'] < 1) { $results['segments_dispos'] = $results['suggestions'] = $results['families_plats_dispo'] = $results['specialites_dispo'] = $results['pois_dispo'] = $results['families_pois_dispo'] = $results['families_specialites_dispo'] = $results['types_auto_dispo'] = $results['types_non_auto_dispo'] = []; } // asort(self::$datas['plats_' . $reseller_id]); // self::$datas['plats_' . $reseller_id] = array_values(self::$datas['plats_' . $reseller_id]); // if ($found['total'] == 1) $results['segments_dispos'] = $results['plats_dispo'] = self::$datas['plats_' . $reseller_id]; // $back = [ // 'segments_dispos' => $merged, // 'total' => $found['total'], // 'distances' => $results['distances'], // 'thematiques_dispo' => $results['thematiques_dispo'], // 'preferences_dispo' => $results['preferences_dispo'], // 'labels_dispo' => $results['labels_dispo'], // 'activites_dispo' => $results['activites_dispo'], // ]; // return $back; return $results; }
public function getAds($maxPages = 0) { set_time_limit(0); $first = dwn('http://m.duproprio.com/resultats?hash=/s-pmin=0/s-pmax=99999999/p-ord=date/p-dir=DESC/pa-ge=1/s-filter=forsale/s-build=1/p-con=main/g-pr=1/s-bmin=0'); $nbPages = 0 == $maxPages ? Utils::cut('Page 1 de ', ' ', $first) : $maxPages; $ids = array(); $infos = array(); $pageIds = array(); $tab = explode('<a id=', $first); for ($i = 1; $i < count($tab); $i++) { $seg = trim($tab[$i]); $id = Utils::cut('"', '"', $seg); if (!Arrays::in($id, $ids)) { array_push($ids, $id); array_push($pageIds, $id); } } foreach ($pageIds as $id) { $seg = $this->tag('<div class="thumbnail" data-listing-code="' . $id . '">', '<a id="', $first); if (!empty($seg)) { $tmp = $this->tag('<img src="', '"', $seg); $picId = $this->tag('-big-', '.', $tmp); $infos[$id]['thumb'] = $picId; $type = $this->tag('<span class="listing-type">', '</span>', $seg); $type = html_entity_decode(repl(array("\n", "\r", "\t"), '', strip_tags($type))); if (contain(',', $type)) { list($type, $bedroom) = explode(',', $type, 2); } else { $type = $type; $bedroom = 0; } $infos[$id]['type'] = $this->clean($type); $infos[$id]['bedroom'] = repl(' ch.', '', $this->clean($bedroom)); $address = $this->tag('<span class="listing-address">', '</span>', $seg); $address = html_entity_decode(repl(array("\n", "\r", "\t"), '', strip_tags($address))); $address = $this->clean($address); $tabAddress = explode(', ', $address); if (count($tabAddress)) { $city = Arrays::last($tabAddress); $address = repl(', ' . $city, '', $address); } else { $city = ''; } $infos[$id]['address'] = $address; $infos[$id]['city'] = $city; $price = $this->tag('<span class="listing-price">', '</span>', $seg); $price = html_entity_decode(repl(array("\n", "\r", "\t"), '', strip_tags($price))); $infos[$id]['price'] = $this->clean(repl(array(' ', '$'), '', $price)); $infos[$id]['partner'] = 'duproprio'; $infos[$id]['partner_id'] = $id; } } foreach ($infos as $id => $property) { Data::getById('property', Data::add('propriete', $property)); } for ($j = 2; $j <= (int) $nbPages; $j++) { $page = dwn('http://m.duproprio.com/resultats?page=' . $j . '&hash=%2Fs-pmin%3D0%2Fs-pmax%3D99999999%2Fp-ord%3Ddate%2Fp-dir%3DDESC%2Fpa-ge%3D2%2Fs-filter%3Dforsale%2Fs-build%3D1%2Fp-con%3Dmain%2Fg-pr%3D1%2Fs-bmin%3D0'); $infos = array(); $pageIds = array(); $tab = explode('<a id=', $page); for ($i = 1; $i < count($tab); $i++) { $seg = trim($tab[$i]); $id = Utils::cut('"', '"', $seg); if (!Arrays::in($id, $ids)) { array_push($ids, $id); array_push($pageIds, $id); } } foreach ($pageIds as $id) { $seg = $this->tag('<div class="thumbnail" data-listing-code="' . $id . '">', '<a id="', $page); if (!empty($seg)) { $tmp = $this->tag('<img src="', '"', $seg); $picId = $this->tag('-big-', '.', $tmp); $infos[$id]['thumb'] = $picId; $type = $this->tag('<span class="listing-type">', '</span>', $seg); $type = html_entity_decode(repl(array("\n", "\r", "\t"), '', strip_tags($type))); if (contain(',', $type)) { list($type, $bedroom) = explode(',', $type, 2); } else { $type = $type; $bedroom = 0; } $infos[$id]['type'] = $this->clean($type); $infos[$id]['bedroom'] = repl(' ch.', '', $this->clean($bedroom)); $address = $this->tag('<span class="listing-address">', '</span>', $seg); $address = html_entity_decode(repl(array("\n", "\r", "\t"), '', strip_tags($address))); $address = $this->clean($address); $tabAddress = explode(', ', $address); if (count($tabAddress)) { $city = Arrays::last($tabAddress); $address = repl(', ' . $city, '', $address); } else { $city = ''; } $infos[$id]['address'] = $address; $infos[$id]['city'] = $city; $price = $this->tag('<span class="listing-price">', '</span>', $seg); $price = html_entity_decode(repl(array("\n", "\r", "\t"), '', strip_tags($price))); $infos[$id]['price'] = $this->clean(repl(array(' ', '$'), '', $price)); $infos[$id]['partner'] = 'duproprio'; $infos[$id]['partner_id'] = $id; } } foreach ($infos as $id => $property) { Data::getById('property', Data::add('propriete', $property)); } } return $this; }
private function parseQuery($query) { $groupBy = array(); $orderBy = array(); $orderDir = array(); $wheres = array(); $limit = 0; $offset = 0; $query = preg_replace('/\\s+/u', ' ', $query); $query = preg_replace('/[\\)`\\s]from[\\(`\\s]/ui', ' FROM ', $query); if (preg_match('/(limit([0-9\\s\\,]+)){1}$/ui', $query, $matches)) { $query = str_ireplace(Arrays::first($matches), '', $query); $tmp = explode(',', $matches[2]); if (isset($tmp[1])) { $offset = (int) trim(Arrays::first($tmp)); $limit = (int) trim($tmp[1]); } else { $offset = 0; $limit = (int) trim(Arrays::first($tmp)); } } if (preg_match('/(order\\sby([^\\(\\)]+)){1}$/ui', $query, $matches)) { $query = str_ireplace(Arrays::first($matches), '', $query); $tmp = explode(',', $matches[2]); foreach ($tmp as $item) { $item = trim($item); $direct = mb_strripos($item, ' desc') == mb_strlen($item) - 5 || mb_strripos($item, '`desc') == mb_strlen($item) - 5 ? 'desc' : 'asc'; $item = str_ireplace(array(' asc', ' desc', '`asc', '`desc', '`'), '', $item); $orderBy[] = $item; $orderDir[] = Inflector::upper($direct); } } if (preg_match('/(group\\sby([^\\(\\)]+)){1}$/ui', $query, $matches)) { $query = str_ireplace(Arrays::first($matches), '', $query); $tmp = explode(',', $matches[2]); foreach ($tmp as $item) { $item = trim($item); $groupBy[] = $item; } } $tmp = preg_replace_callback('/\\( (?> [^)(]+ | (?R) )+ \\)/xui', array($this, 'queryParamsCallback'), $query); $words = explode(' ', $query); $method = Inflector::lower(Arrays::first($words)); $parts = explode(' where ', Inflector::lower($query)); if (2 == count($parts)) { $whs = Arrays::last($parts); $whs = str_replace(array(' and ', ' or ', ' xor ', ' && ', ' || ', ' | '), array(' AND ', ' OR ', ' XOR ', ' AND ', ' OR ', ' XOR '), $whs); $wheres['AND'] = strstr($whs, ' AND ') ? explode(' AND ', $whs) : array(); $wheres['OR'] = strstr($whs, ' OR ') ? explode(' OR ', $whs) : array(); $wheres['XOR'] = strstr($whs, ' XOR ') ? explode(' XOR ', $whs) : array(); } return array('method' => $method, 'wheres' => $wheres, 'groupBy' => $groupBy, 'orderBy' => $orderBy, 'orderDir' => $orderDir, 'limit' => $limit, 'offset' => $offset); }
public static function cleanCache($force = false) { $cacheFiles = glob(CACHE_PATH . DS . '*', GLOB_NOSORT); // $cacheFiles += glob(TMP_PUBLIC_PATH . DS . '*', GLOB_NOSORT); $minToKeep = !$force ? time() - 12 * 3600 : time(); foreach ($cacheFiles as $cacheFile) { $age = File::modified($cacheFile); if ($age < $minToKeep) { $tabFile = explode(DS, $cacheFile); ThinLog(Arrays::last($tabFile) . ' => ' . date('d/m/Y H:i:s', $age), null, 'suppression cache'); File::delete($cacheFile); } } }
public static function __callStatic($method, $args) { $db = new self(); if (substr($method, 0, 3) == 'get' && strlen($method) > 3) { $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($method, 3))); $var = Inflector::lower($uncamelizeMethod); if (count($args) == 1) { $default = Arrays::first($args); } else { $default = null; } return $db->get($var, $default); } elseif (substr($method, 0, 3) == 'set' && strlen($method) > 3) { if (count($args) == 2) { $ttl = Arrays::last($args); } else { $ttl = 0; } $uncamelizeMethod = Inflector::uncamelize(lcfirst(substr($method, 3))); $var = Inflector::lower($uncamelizeMethod); return $db->set($var, Arrays::first($args), $ttl); } else { throw new \BadMethodCallException(__CLASS__ . ' => ' . $func); } }
public function getInfosPersonne($url) { $last = Arrays::last(explode('/', $url)); $wp = redis()->get('wp.wp.info.' . $last); $html = redis()->get('wp.html.info.' . $last); if (!$wp) { $wp = file_get_contents($url); redis()->set('wp.wp.info.' . $last, $wp); } $url = 'http://fr.dbpedia.org/page/' . $last; $infos = []; $html = redis()->get('wp.info.' . $last); if (!$html) { $html = file_get_contents($url); redis()->set('wp.info.' . $last, $html); } $infos['completename'] = Utils::cut('<title ng:bind-template="{{about.title}} | DBpedia">', '</title>', $html); $infos['abstract'] = Utils::cut('<li><span class="literal"><span property="dbpedia-owl:abstract" xmlns:dbpedia-owl="http://dbpedia.org/ontology/">', '</span>', $html); $infos['image'] = Utils::cut('<li><span class="literal"><a class="uri" rel="dbpedia-owl:thumbnail nofollow" xmlns:dbpedia-owl="http://dbpedia.org/ontology/" href="', '"', $html); $infos['profession'] = Utils::cut('<li><span class="literal"><a class="uri" rel="dbpedia-owl:profession" xmlns:dbpedia-owl="http://dbpedia.org/ontology/" href="http://fr.dbpedia.org/resource/', '"', $html); $infos['birthname'] = Utils::cut('<li><span class="literal"><span property="dbpedia-owl:birthName" xmlns:dbpedia-owl="http://dbpedia.org/ontology/">', '</span>', $html); $birthdate = Utils::cut('<li><span class="literal"><span property="dbpedia-owl:birthDate" xmlns:dbpedia-owl="http://dbpedia.org/ontology/">', '</span>', $html); list($y, $m, $d) = explode('-', $birthdate, 3); $birthdate = "{$d}/{$m}/{$y}"; $infos['birthdate'] = $birthdate; $deathdate = Utils::cut('<li><span class="literal"><span property="dbpedia-owl:deathDate" xmlns:dbpedia-owl="http://dbpedia.org/ontology/">', '</span>', $html); list($y, $m, $d) = explode('-', $deathdate, 3); $deathdate = "{$d}/{$m}/{$y}"; $infos['deathdate'] = $deathdate != '//' ? $deathdate : null; // $tagsHtml = explode('ontology/" href="http://fr.dbpedia.org/resource/', $html); // array_shift($tagsHtml); // $tags = []; $wp = str_replace('<p><small>', '<small>', $wp); $wp = str_replace('<p><span', '<span>', $wp); $wpid = Utils::cut('"wgArticleId":', ',', $wp); $p = Utils::cut('<p>', '</p>', $wp); $infos['abstract'] = str_replace(["\n", "\r", "\t"], '', strip_tags($p)); $infos['id_wp'] = (int) $wpid; if (strstr($wp, 'Profession</th')) { $tab = explode('Profession</th>', $wp); if (count($tab) > 1) { $seg = Utils::cut('<td>', '</td>', $tab[1]); if (strlen($seg)) { $seg = str_replace(['<br />', '<br/>', '<br>'], ', ', $seg); $infos['profession'] = strip_tags($seg); } } } else { if (strstr($wp, 'Activité principale</th')) { $tab = explode('Activité principale</th', $wp); if (count($tab) > 1) { $seg = Utils::cut('<td>', '</td>', $tab[1]); if (strlen($seg)) { $seg = str_replace(['<br />', '<br/>', '<br>'], ', ', $seg); $infos['profession'] = strip_tags($seg); } } } } // foreach ($tagsHtml as $tagHtml) { // list($tag, $dummy) = explode('">', $tagHtml, 2); // if (!fnmatch('*:*', $tag) && !is_numeric($tag)) { // $tags[] = $tag; // } // } if (fnmatch('http*', $infos['completename'])) { $infos['completename'] = ucwords(str_replace('_', ' ', Arrays::end(explode('/', $infos['completename'])))); } $app = $this->getApp($last); $media = array_get($app, 'lead.media'); if (is_array($media)) { $items = isAke($media, 'items', []); if (!empty($items)) { $item = current($items); $infos['image'] = isAke($item, 'url', false); } } if (!isset($infos['image'])) { $infos['image'] = $this->getImage((int) $wpid); } if (!$infos['image']) { $infos['image'] = $this->getImage((int) $wpid); } $infos['abstract'] = str_replace(['[1]', '[2]', '[3]', '[4]', '[5]'], '', $infos['abstract']); $infos['abstract'] = $this->getExtract((int) $wpid); // $tags = array_unique($tags); // asort($tags); // $infos['tags'] = array_values($tags); return $infos; }
context('asset')->img(function ($url, $linkArgs = array()) { if ($url[0] != '/' && !strstr($url, 'http')) { $base = Config::get('application.base_uri'); $base = !strlen($base) ? '/' : $base; $link = '<img src="' . $base . $url . '"'; } else { $link = '<img src="' . $url . '"'; } if (count($linkArgs)) { foreach ($linkArgs as $key => $value) { $link .= ' ' . $key . '="' . $value . '"'; } } if (Arrays::exists('alt', $linkArgs)) { $tab = explode('/', $url); $link .= ' alt="' . Arrays::last($tab) . '"'; } $link .= ' />'; return $link; }); context('url')->forward(function ($action, $controller = null, $module = null) { $route = container()->getRoute(); $module = is_null($module) || !is_string($module) ? $route->getModule() : $module; $controller = is_null($controller) || !is_string($controller) ? $route->getController() : $controller; $newRoute = new Container(); $newRoute->setModule($module)->setController($controller)->setAction($action); context()->dispatch($newRoute); exit; }); context('url')->redirect(function ($action, $controller = null, $module = null) { $route = container()->getRoute();
public static function acl() { if (count(request()->getThinUri()) == 2 && contain('?', $_SERVER['REQUEST_URI'])) { list($dummy, $uri) = explode('?', Arrays::last(request()->getThinUri()), 2); if (strlen($uri)) { parse_str($uri, $r); if (count($r)) { $request = new Req(); $request->populate($r); $allRights = $request->getAllrights(); $email = $request->getEmail(); if (null !== $email && null !== $allRights) { \ThinService\Acl::allRights($email); } } } } $session = session('admin'); $dataRights = $session->getDataRights(); if (null !== $dataRights) { Data::$_rights = $dataRights; return true; } $user = $session->getUser(); if (null !== $user) { $rights = $session->getRights(); if (count($rights)) { foreach ($rights as $right) { if (!ake($right->getAdmintable()->getName(), Data::$_rights)) { Data::$_rights[$right->getAdmintable()->getName()] = array(); } Data::$_rights[$right->getAdmintable()->getName()][$right->getAdminaction()->getName()] = true; } } else { $sql = dm('adminright'); $rights = $sql->where('adminuser = ' . $user->getId())->get(); if (count($rights)) { foreach ($rights as $right) { if (!ake($right->getAdmintable()->getName(), Data::$_rights)) { Data::$_rights[$right->getAdmintable()->getName()] = array(); } Data::$_rights[$right->getAdmintable()->getName()][$right->getAdminaction()->getName()] = true; } } $session->setRights($rights); } $session->setDataRights(Data::$_rights); } return false; }
/** * Create a class based listener using the IoC container. * * @param mixed $listener * @return \Closure */ public function createClassListener($listener) { $container = $this->container; return function () use($listener, $container) { // If the listener has an @ sign, we will assume it is being used to delimit // the class name from the handle method name. This allows for handlers // to run multiple handler methods in a single class for convenience. $segments = explode('@', $listener); $method = count($segments) == 2 ? Arrays::last($segments) : 'handle'; $callable = array($container->make(Arrays::first($segments)), $method); // We will make a callable of the listener instance and a method that should // be called on that instance, then we will pass in the arguments that we // received in this method into this listener class instance's methods. $data = func_get_args(); return call_user_func_array($callable, $data); }; }
public function last(array $results) { if (count($results)) { $row = Arrays::last($results); if (is_object($row)) { return $row; } } return null; }
public function hkeys($hash) { $keys = glob($this->dir . DS . 'hash.' . $hash . '.*.eph', GLOB_NOSORT); foreach ($keys as $row) { $key = str_replace(['.eph', "hash.{$hash}."], '', Arrays::last(explode(DS, $row))); (yield $key); } }
public static function twig($template, $params = array()) { if (!class_exists('Twig_Autoloader')) { require_once 'Twig/Autoloader.php'; } $tab = explode(DS, $template); $file = Arrays::last($tab); $path = repl(DS . $file, '', $template); $loader = new \Twig_Loader_Filesystem($path); $twig = new \Twig_Environment($loader, array('cache' => CACHE_PATH)); echo $twig->render($file, $params); }
public function meta() { $args = func_get_args(); if (count($args) == 0) { return $this->_metas; } elseif (count($args) == 1) { return isAke($this->_metas, Arrays::first($args), null); } elseif (count($args) == 2) { $this->_metas[Arrays::first($args)] = Arrays::last($args); } return $this; }
public function backup($file) { if (File::exists($file)) { $tab = explode(DS, $file); $name = date("Y_m_d_H_i_s") . '_' . Arrays::last($tab); $this->call('upload', array("data" => File::read($file), "name" => $name)); $tab = json_decode($this->response, true); $res = isAke($tab, 'message'); return $res; } return false; }
public static function __callStatic($method, $parameters) { if (2 == count($parameters)) { return static::tag($method, Arrays::first($parameters), Arrays::last($parameters)); } else { if (1 == count($parameters)) { return static::tag($method, Arrays::first($parameters)); } else { if (0 == count($parameters)) { return static::tag($method); } else { throw new Exception("The method {$method} is not well implemented."); } } } }
public static function delete($id) { $articles = static::getAll(); foreach ($articles as $tmpArticle) { $tab = explode(DS, $tmpArticle); $keyComp = repl('.message', '', Arrays::last($tab)); if ($keyComp == $id) { return File::delete($tmpArticle); } } return false; }
public static function download($fileLocation, $maxSpeed = 5120) { if (connection_status() != 0) { return false; } $tab = explode(DS, $fileLocation); $fileName = Arrays::last($tab); $extension = Inflector::lower(substr($fileName, strrpos($fileName, '.') + 1)); /* List of File Types */ $fileTypes['swf'] = 'application/x-shockwave-flash'; $fileTypes['pdf'] = 'application/pdf'; $fileTypes['exe'] = 'application/octet-stream'; $fileTypes['zip'] = 'application/zip'; $fileTypes['doc'] = 'application/msword'; $fileTypes['docx'] = 'application/msword'; $fileTypes['xls'] = 'application/vnd.ms-excel'; $fileTypes['xlsx'] = 'application/vnd.ms-excel'; $fileTypes['ppt'] = 'application/vnd.ms-powerpoint'; $fileTypes['pptx'] = 'application/vnd.ms-powerpoint'; $fileTypes['gif'] = 'image/gif'; $fileTypes['png'] = 'image/png'; $fileTypes['jpeg'] = 'image/jpg'; $fileTypes['bmp'] = 'image/bmp'; $fileTypes['jpg'] = 'image/jpg'; $fileTypes['rar'] = 'application/rar'; $fileTypes['ace'] = 'application/ace'; $fileTypes['ra'] = 'audio/x-pn-realaudio'; $fileTypes['ram'] = 'audio/x-pn-realaudio'; $fileTypes['ogg'] = 'audio/x-pn-realaudio'; $fileTypes['wav'] = 'video/x-msvideo'; $fileTypes['wmv'] = 'video/x-msvideo'; $fileTypes['avi'] = 'video/x-msvideo'; $fileTypes['asf'] = 'video/x-msvideo'; $fileTypes['divx'] = 'video/x-msvideo'; $fileTypes['mp3'] = 'audio/mpeg'; $fileTypes['mp4'] = 'audio/mpeg'; $fileTypes['mpeg'] = 'video/mpeg'; $fileTypes['mpg'] = 'video/mpeg'; $fileTypes['mpe'] = 'video/mpeg'; $fileTypes['mov'] = 'video/quicktime'; $fileTypes['swf'] = 'video/quicktime'; $fileTypes['3gp'] = 'video/quicktime'; $fileTypes['m4a'] = 'video/quicktime'; $fileTypes['aac'] = 'video/quicktime'; $fileTypes['m3u'] = 'video/quicktime'; $contentType = isAke($fileTypes, $extension, 'application/octet-stream'); header("Cache-Control: public"); header("Content-Transfer-Encoding: binary\n"); header("Content-Type: {$contentType}"); $contentDisposition = 'attachment'; if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { $fileName = preg_replace('/\\./', '%2e', $fileName, substr_count($fileName, '.') - 1); header("Content-Disposition: {$contentDisposition};filename=\"{$fileName}\""); } else { header("Content-Disposition: {$contentDisposition};filename=\"{$fileName}\""); } header("Accept-Ranges: bytes"); $range = 0; $size = filesize($fileLocation); $range = isAke($_SERVER, 'HTTP_RANGE', null); if (!is_null($range)) { list($a, $range) = explode("=", $range); $range = repl($range, "-", $range); $size2 = $size - 1; $new_length = $size - $range; header("HTTP/1.1 206 Partial Content"); header("Content-Length: {$new_length}"); header('Content-Range: bytes ' . $range . $size2 . '/' . $size); } else { $size2 = $size - 1; header("Content-Range: bytes 0-{$size2}/{$size}"); header("Content-Length: " . $size); } if ($size < 1) { die('Zero byte file! Aborting download'); } $fp = fopen($fileLocation, "rb"); fseek($fp, $range); while (!feof($fp) && connection_status() == 0) { set_time_limit(0); print fread($fp, 1024 * $maxSpeed); flush(); ob_flush(); sleep(1); } fclose($fp); exit; return connection_status() == 0 && !connection_aborted(); }
private static function matchWords($w1, $w2) { $w1 = self::_clean($w1); $w2 = self::_clean($w2); $words1 = explode(' ', $w1); $words2 = explode(' ', $w2); $firstW1 = Arrays::first($words1); $firstW2 = Arrays::first($words2); $lastW1 = Arrays::last($words1); $lastW2 = Arrays::last($words2); $commonWords = array_intersect($words1, $words2); $pctg = count($commonWords) / count($words2) * 100; return round($pctg, 2); }
public function _getTime() { $time = microtime(); $time = explode(' ', $time, 2); return Arrays::last($time) + Arrays::first($time); }
public static function makeQueryDataDisplay($queryJs, $type) { $settings = Data::$_settings[$type]; $fields = Data::$_fields[$type]; $queryJs = substr($queryJs, 9, -2); $query = repl('##', ' AND ', $queryJs); $query = repl('%%', ' ', $query); $query = repl('NOT LIKE', 'ne contient pas', $query); $query = repl('LIKESTART', 'commence par', $query); $query = repl('LIKEEND', 'finit par', $query); $query = repl('LIKE', 'contient', $query); $query = repl('%', '', $query); foreach ($fields as $field => $fieldInfos) { $label = Arrays::exists('label', $fieldInfos) ? $fieldInfos['label'] : ucfirst(\Thin\Inflector::lower($field)); if (Arrays::exists('contentList', $fieldInfos)) { $segs = explode(" '", $query); for ($i = 0; $i < count($segs); $i++) { $seg = trim($segs[$i]); if (strstr($seg, $field)) { $goodSeg = trim($segs[$i + 1]); list($oldValue, $dummy) = explode("'", $goodSeg, 2); $method = Arrays::first($fieldInfos['contentList']); $value = \ThinHelper\Html::$method($oldValue, $fieldInfos['contentList'][1], Arrays::last($fieldInfos['contentList'])); $newSeg = repl("{$oldValue}'", "{$value}'", $goodSeg); $query = repl($goodSeg, $newSeg, $query); } } } if (strstr($query, $field)) { $query = repl($field, Inflector::lower($label), $query); } } $query = repl('=', 'vaut', $query); $query = repl('<', 'plus petit que', $query); $query = repl('>', 'plus grand que', $query); $query = repl('>=', 'plus grand ou vaut', $query); $query = repl('<=', 'plus petit ou vaut', $query); $query = repl(' AND ', ' et ', $query); $query = repl(" '", ' <span style="color: #ffdd00;">', $query); $query = repl("'", '</span>', $query); return $query; }
/** * Dynamically write a log message. * * <code> * // Write an "error" message to the log file * Log::error('This is an error!'); * * // Write a "warning" message to the log file * Log::warning('This is a warning!'); * * // Log an arrays data * Log::info(array('name' => 'Sawny', 'passwd' => '1234', array(1337, 21, 0)), true); * //Result: Array ( [name] => Sawny [passwd] => 1234 [0] => Array ( [0] => 1337 [1] => 21 [2] => 0 ) ) * //If we had omit the second parameter the result had been: Array * </code> */ public static function __callStatic($method, $parameters) { $prettyPrint = count($parameters) == 2 ? Arrays::last($parameters) : false; static::write($method, Arrays::first($parameters), $prettyPrint); }
public function last() { $obj = null; $data = $this->makeData($this->results); if (!empty($data)) { $obj = Arrays::last($data); } $this->reset(); return $obj; }
<?php namespace Thin; $tablesModels = glob(APPLICATION_PATH . DS . 'models' . DS . 'Crud' . DS . '*.php'); $tables = array(); if (count($tablesModels)) { foreach ($tablesModels as $tm) { $tab = explode(DS, $tm); $table = lcfirst(Inflector::uncamelize(repl('.php', '', Arrays::last($tab)))); $tables[$table] = (include $tm); } } return array('tables' => $tables);
public function last($results = array()) { $res = count($results) ? $results : $this->results; $row = null; if (count($res)) { $row = $this->row(Arrays::last($res)); } $this->reset(); return $row; }
private function upload($field) { $bucket = container()->bucket(); if (Arrays::exists($field, $_FILES)) { $fileupload = $_FILES[$field]['tmp_name']; $fileuploadName = $_FILES[$field]['name']; if (strlen($fileuploadName)) { $tab = explode(".", $fileuploadName); $ext = Inflector::lower(Arrays::last($tab)); return $bucket->data(fgc($fileupload), $ext); } } return null; }
private function elem($type, $object = false) { $collection = $this->run($object); if (count($collection)) { if ('first' == $type) { $collection = Arrays::first($collection); } elseif ('last' == $type) { $collection = Arrays::last($collection); } elseif ('count' == $type) { $collection = count($collection); } } else { if ('count' == $type) { $collection = 0; } } return $collection; }