public static function returnRoutes($prefix = null) { $dics_for_cache = ['projects', 'types']; foreach ($dics_for_cache as $dic_name) { ## Refresh dics cache #Cache::forget('dic_' . $dic_name); $dic_[$dic_name] = Cache::get('dic_' . $dic_name); if (!$dic_[$dic_name]) { Cache::forget('dic_' . $dic_name); $dic_[$dic_name] = Dic::valuesBySlug($dic_name, function ($query) { $query->orderBy('lft', 'ASC'); }, ['allfields', 'alltextfields'], true, true, true); #Helper::d($dic_name); Helper::ta($dic_{$dic_name}); #die; $dic_[$dic_name] = DicLib::loadImages($dic_[$dic_name], ['avatar', 'image', 'logo', 'photo', 'header_img']); #Helper::d($dic_name); Helper::ta($dic_{$dic_name}); #die; Cache::add('dic_' . $dic_name, $dic_[$dic_name], self::$global_cache_min); } View::share('dic_' . $dic_name, $dic_[$dic_name]); #Helper::d($dic_name); Helper::ta($dic_{$dic_name}); } #Helper::tad($dic_{'city'}); #die; Route::group(array('prefix' => '{lang}'), function () { Route::any('/project/{slug}', array('as' => 'app.project', 'uses' => __CLASS__ . '@appProject')); #Route::any('/ajax/send-message', array('as' => 'ajax.send-message', 'uses' => __CLASS__.'@postSendMessage')); #Route::any('/ajax/some-action', array('as' => 'ajax.some-action', 'uses' => __CLASS__.'@postSomeAction')); }); Route::group(array(), function () { #Route::any('/ajax/send-message', array('as' => 'ajax.send-message', 'uses' => __CLASS__.'@postSendMessage')); #Route::any('/ajax/some-action', array('as' => 'ajax.some-action', 'uses' => __CLASS__.'@postSomeAction')); }); }
/** * Search for movie title * * @param string $q The search query * * @return Response */ public function searchTitle($q) { // init result array $result = array(); // trim query $q = trim($q); // create slug from query $q_slug = str_slug('imdb-' . $q); // check if search is in cache if (\Cache::has($q_slug)) { // retrieve item from cache $item = \Cache::get($q_slug); // add data to array $result = array('fromcache' => true, 'data' => $item); } else { // url encode query $q = urlencode($q); // Use the Imdb Api to search for movie $imdbResult = json_decode(file_get_contents(sprintf(env('IMDB_SEARCH_TITLE_URL'), $q))); // only proceed if the most popular title array is filled and at least contains 1 movie if (isset($imdbResult->title_popular) && is_array($imdbResult->title_popular) && count($imdbResult->title_popular) > 0) { // extract year from title_description $year = intval(substr($imdbResult->title_popular[0]->title_description, 0, 4)); // create object for this movie $item = new ImdbMovie($imdbResult->title_popular[0]->id, $imdbResult->title_popular[0]->title, $year); // add item to cache for a year \Cache::add($q_slug, $item, 60 * 24 * 365); // add data to array $result = array('fromcache' => false, 'data' => $item); } } // return json formatted response return response()->json($result); }
public function get_exchange_rates() { // \Cache::forget('money_exchange_rates'); if (\Cache::has('money_exchange_rates')) { $data = \Cache::get('money_exchange_rates'); } elseif (is_connected("openexchangerates.org")) { $api_key = "bbc128aa6f3645d78b098f0eef3dd533"; $json = file_get_contents("http://openexchangerates.org/api/latest.json?app_id={$api_key}"); $json = json_decode($json, true); $data['rates'] = $json['rates']; $data['base'] = $json['base']; // $data['json_rates'] = json_encode($json['rates']); \Cache::add('money_exchange_rates', $data, 360); \Cache::add('money_exchange_rates_default', $data, 50000); } else { $data = \Cache::get('money_exchange_rates_default'); } $currency_list = \Lst::common('currency1'); $arr["site_name"] = "Ahmed-Badawy.com"; $arr["base"] = $data['base']; foreach ($currency_list as $key => $val) { $n = ['short' => $key, "name" => $val, "value" => $data['rates'][$key]]; $arr['rates'][$key] = $n; } return $arr; }
protected function _getDepartmentList() { if (Cache::has('departmentList')) { return Cache::get('departmentList'); } else { $list = DB::table('sectionmasters')->join('departmentmasters', 'departmentmasters.sectioncd', '=', 'sectionmasters.sectioncd')->select('departmentmasters.departmentcd as departmentcd', 'sectionmasters.sectionname as sectionname', 'departmentmasters.departmentname as departmentname')->get(); $expiresAt = Carbon::now()->addMinutes(10); Cache::add('departmentList', $list, $expiresAt); return $list; } }
public function institucion($categoria, $id = null) { $this->options['categoria'] = $categoria; $this->options['id'] = $id; Estructuras::setOptions($this->options); $encabezado = Estructuras::getEncabezado(); if ($encabezado) { $this->data = Estructuras::getEstructuraEncabezado($encabezado); } $response = ApiHelper::prepareResponse($this->data, 'institucion', $this->options, $this->total); Cache::add(Request::getRequestUri(), $response, Config::get('cache.time')); return $response; }
public function crear_key($datos, $results) { $datos = $this->sii->orderParamsToKeyCache($datos); $keyToService = md5(json_encode($datos)); $response['key'] = $keyToService; if (Cache::has($keyToService)) { $response['data'] = Cache::get($keyToService); } else { Cache::add($keyToService, $results, $this->minutesToCache); $response['data'] = $results; } return $response; }
public function fire($job, $data) { if (isset(app('veer')->cachedView) && config('veer.htmlcache_enable') == true && !auth_check_session()) { $cache_url = cache_current_url_value(); $expiresAt = now(24, 'hours'); \Cache::has($cache_url) ?: \Cache::add($cache_url, app('veer')->cachedView->render(), $expiresAt); } else { return $job->release(); } // leave it here if (isset($data['repeatJob']) && $data['repeatJob'] > 0) { $job->release($data['repeatJob'], 'minutes'); } }
public function store(Request $request) { $title = $request->input('title'); $content = $request->input('content'); $post = ['title' => trim($title), 'content' => trim($content)]; $posts = Cache::get('posts', []); if (!Cache::get('post_id')) { Cache::add('post_id', 1, 60); } else { Cache::increment('post_id', 1); } $posts[Cache::increment('post_id', 1)]; Cache::put('posts', $posts, 60); return redirect()->route('post.show', ['post' => Cache::get('post_id')]); }
public static function start() { $key = static::getKey(); $start = microtime(true); Cache::add($key, 0, static::$intervalSeconds); register_shutdown_function('Firewall::end'); while (Cache::increment($key) > static::$concurrency) { Cache::decrement($key); if (!static::$spinLockSeconds || microtime(true) - $start > static::$intervalSeconds) { http_response_code(429); die('429: Too Many Requests'); } usleep(static::$spinLockSeconds * 1000000); } }
public function manufacture($classname, $id, $row = null) { // Check that the id is valid if ((int) $id == 0) { throw new \Exception('Invalid id'); } // Set up the name for the factory array $factory_array_name = "_{$classname}s"; $item = null; // Set up the manufactured array if it doesn't exist if (!isset($this->{$factory_array_name})) { Logging::log("Setting up manufactured array for {$classname}"); $this->{$factory_array_name} = array(); } // If the current id doesn't exist in the manufactured array, manufacture it if (!array_key_exists($id, $this->{$factory_array_name})) { // Initialize a position for the item in the manufactured array $this->{$factory_array_name}[$id] = null; try { // Check if the class is cacheable as well $cacheable = in_array($classname, array('TBGProject', 'TBGStatus', 'TBGPriority', 'TBGCategory', 'TBGUserstate')); $item = null; // If the class is cacheable, check if it exists in the cache if ($cacheable) { if ($item = Cache::get("TBGFactory_cache{$factory_array_name}_{$id}")) { Logging::log("Using cached {$classname} with id {$id}"); } } // If we didn't get an item from the cache, manufacture it if (!$cacheable || !is_object($item)) { $item = new $classname($id, $row); Logging::log("Manufacturing {$classname} with id {$id}"); // Add the item to the cache if it's cacheable if ($cacheable) { Cache::add("TBGFactory_cache{$factory_array_name}_{$id}", $item); } } // Add the manufactured item to the manufactured array $this->{$factory_array_name}[$id] = $item; } catch (Exception $e) { throw $e; } } else { Logging::log("Using previously manufactured {$classname} with id {$id}"); } // Return the item at that id in the manufactured array return $this->{$factory_array_name}[$id]; }
/** * @param string $template The name of the template to use for events. These are JSON files and reside in * [library]/config/schema * * @throws InternalServerErrorException * @return bool|array The schema in array form, FALSE on failure. */ public static function initialize($template = self::SCRIPT_EVENT_SCHEMA) { if (false !== ($eventTemplate = \Cache::get('scripting.event_schema', false))) { return $eventTemplate; } // Not cached, get it... $path = Platform::getLibraryConfigPath('/schema') . '/' . trim($template, ' /'); if (is_file($path) && is_readable($path) && false !== ($eventTemplate = file_get_contents($path))) { if (false !== ($eventTemplate = json_decode($eventTemplate, true)) && JSON_ERROR_NONE == json_last_error()) { \Cache::add('scripting.event_schema', $eventTemplate, 86400); return $eventTemplate; } } \Log::notice('Scripting unavailable. Unable to load scripting event schema: ' . $path); return false; }
/** * Search for video * * @param string $q The search query * * @return Response */ public function searchVideo($q) { // init result array $result = array(); // create slug from query $q_slug = str_slug('youtube-' . $q); // check if search is in cache if (\Cache::has($q_slug)) { // retrieve item from cache $items = \Cache::get($q_slug); // add data to array $result = array('fromcache' => true, 'data' => $items); } else { // init Google objects $client = new \Google_Client(); $client->setDeveloperKey(env('YOUTUBE_API_KEY')); $youtube = new \Google_Service_YouTube($client); try { $items = array(); // use youtube search to retrieve video data $searchResponse = $youtube->search->listSearch('id,snippet', array('q' => $q, 'maxResults' => 3, 'type' => 'video')); // loop through search results foreach ($searchResponse['items'] as $video) { // create object for this video $item = new YoutubeVideo($video['id']['videoId'], $video['snippet']['title'], $video['snippet']['description'], $video['snippet']['thumbnails']['default']['url']); // add object to results $items[] = $item; } // add items to cache for a year \Cache::add($q_slug, $items, 60 * 24 * 365); // add data to array $result = array('fromcache' => false, 'data' => $items); } catch (\Google_Service_Exception $e) { // log Google_Service_Exception \Log::error('Google_Service_Exception: ' . $e->getMessage()); } catch (\Google_Exception $e) { // log Google_Exception \Log::error('Google_Exception: ' . $e->getMessage()); } } // return json formatted response return response()->json($result); }
/** * can we add several things to the cache and then return them all at once */ public function testFetchArrayOfKeys() { // to store all the keys and values we are testing with $stored_values = array(); // build and store 26 different values with different keys foreach (range('A', 'Z') as $letter) { $key = $this->key . '-key-' . $letter; $value = $this->key . '-value-' . $letter; // put them in the cache one at a time $this->assertTrue(Cache::add($key, $value, 10, false)); // so we can get them all at once below $stored_values[$key] = $value; } // get all the keys simultaneously $results = Cache::get(array_keys($stored_values)); // test all the records were returned as expected foreach ($stored_values as $key => $value) { $this->assertEquals($results[$key], $value); } }
/** param options [ processLink=>boolean, #whether to link lock to the process. Defaults to true timeLink=timeout in seconds #whether to timeout lock hold, and if so, how many seconds to hold lock for before timeout. Defaults to false ] */ function lock($name, $options = []) { //Don't use with forking. forking will cause response code 47 (temporarily unavailable) for some time after forks end $lockPackage = []; if (!isset($options['processLink']) || $options['processLink']) { $lockPackage['pid'] = getmypid(); } if ($options['timeLink']) { $lockPackage['time'] = time(); $lockPackage['timeout'] = $options['timeLink']; } $lockPackage = json_encode($lockPackage); $initial = Cache::add($name, $lockPackage); if (!$initial) { $existingLockPackage = json_decode(Cache::get($name), true); if (is_array($existingLockPackage)) { if ($existingLockPackage['pid']) { $processFile = '/proc/' . $existingLockPackage['pid']; clearstatcache(false, $processFile); //process is no longer running, attempt to get lock if (!file_exists($processFile)) { Cache::delete($name); $return = Cache::add($name, $lockPackage); return $return; } } if ($existingLockPackage['time']) { //timeout period has passed, unlock and attempt to gt lock if (time() - $existingLockPackage['time'] > $existingLockPackage['timeout']) { Cache::delete($name); return Cache::add($name, $lockPackage); } } } } else { return $initial; } }
/** * 获取上传token * @return bool * @throws \Exception */ public static function getUploadToken() { if (!config('l5-upload-client.enable')) { return ''; } $timestamp = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : 0; $version = config('l5-upload-client.version', '1.0'); $param = ['app_key' => config('l5-upload-client.app_key'), 'timestamp' => $timestamp, 'sign' => self::calcSign($timestamp), 'version' => $version]; // 计算缓存过期 $cacheKey = self::cacheName(__CLASS__, 'token'); $uploadToken = ''; if (\Cache::has($cacheKey)) { $cacheToken = \Cache::get($cacheKey); if (isset($cacheToken['token']) && $cacheToken['expire_timestamp'] > $timestamp) { // 存在 token 且不过期 $uploadToken = $cacheToken['token']; } else { \Cache::forget($cacheKey); } } if (!$uploadToken) { if (!config('l5-upload-client.token_url')) { throw new \Exception('Please set lemon picture server token url'); } else { $curl = new Curl(); $upload = $curl->get(config('l5-upload-client.token_url'), $param); $upload = json_decode(json_encode($upload), true); if ($upload['status'] == 'success') { $uploadToken = $upload['data']['upload_token']; $expired = (int) config('l5-upload-client.expires'); \Cache::add($cacheKey, ['token' => $uploadToken, 'expire_timestamp' => $timestamp + $expired * 60], config('l5-upload-client.expires')); } else { throw new \Exception($upload['msg']); } } } return $uploadToken; }
public function ValidateToken($token, $isValidating, $user) { $serviceResponse = new ServiceResponse(); Cache::forget($token); if ($isValidating) { if (Cache::has($token)) { // Constants->CacheExpirationTime //Cache::add($token, $this.GetSessionUser($token), 6000); Cache::add($token, $user, 525600); Cache::add($user->id, $token, 525600); $serviceResponse->IsSuccess = true; $this->Token = $token; } $serviceResponse->Message = trans('messages.TokenIsNotValid'); $serviceResponse->ErrorCode = "101"; } else { //Cache::add($token, $user, Constants->CacheExpirationTime); Cache::add($token, $user, 525600); $serviceResponse->Data = Cache::get($token); $serviceResponse->IsSuccess = true; $this->Token = $token; } return $serviceResponse; }
/** * save the values in the cache for faster retrieval next time (and to be kind to the database) * * @param string $localOnly * @return void * @author Craig Ulliott */ protected final function saveCache() { $this->requiresState(); // the key we use for this object $key = $this->buildCacheKey(); // prepare the data we are saving $data = array('primary_key' => $this->ID, 'values' => $this->values, 'cache_values' => $this->cache_values); // cache this data return Cache::add($key, $data); }
/** * This recursive method is called to generate the HTML representation of * the cached menu that is shown in the menu pane whenever anyone with the * associated role id logs in. In the generation of the menu controllers * to which the user has no permissions are ignored. * * @param $roleId string The id of the role for which the menu is being generated * @param $path string The path of the modules for which the menus is to be * generated. * * @return String */ private function generateMenus($roleId, $path = "app/modules") { $prefix = "app/modules"; //$d = dir($path); if (file_exists($path . "/package_redirect.php")) { include $path . "/package_redirect.php"; $originalPath = $path; $path = $redirect_path; $d = dir($path); $redirected = true; $redirects = Cache::get("permission_redirects"); if ($redirects == null) { $redirects = array(); } $redirects[] = array("from" => $originalPath, "to" => $path); Cache::add("permission_redirects", $redirects); } else { $redirects = Cache::get("permission_redirects"); if (is_array($redirects)) { foreach ($redirects as $redirect) { if (substr_count($path, $redirect["from"]) > 0) { $redirected = true; $originalPath = $path; $path = str_replace($redirect["from"], $redirect["to"], $path); break; } } } $d = dir($path); } $list = array(); // Go through every file in the module directory while (false !== ($entry = $d->read())) { // Ignore certain directories if ($entry != "." && $entry != ".." && is_dir("{$path}/{$entry}")) { if ($redirected) { $urlPath = substr("{$originalPath}/{$entry}", strlen($prefix)); $modulePath = substr("{$originalPath}/{$entry}", strlen($prefix)); $this->permissions->queryResolve = true; $value = $this->permissions->get(array("conditions" => "roles.role_id='{$roleId}' AND module = '{$modulePath}' AND value='1'")); $children = $this->generateMenus($roleId, "{$originalPath}/{$entry}"); } else { $urlPath = substr("{$path}/{$entry}", strlen($prefix)); $modulePath = substr("{$path}/{$entry}", strlen($prefix)); $this->permissions->queryResolve = true; $value = $this->permissions->get(array("conditions" => "roles.role_id='{$roleId}' AND module = '{$modulePath}' AND value='1'")); $children = $this->generateMenus($roleId, "{$path}/{$entry}"); } if (file_exists("app/modules/" . $modulePath . "/package.xml")) { $xml = simplexml_load_file("app/modules/" . $modulePath . "/package.xml"); $label = (string) reset($xml->xpath("/package:package/package:label")); $icon = (string) reset($xml->xpath("/package:package/package:icon")); } else { $label = ""; $icon = ""; } if (count($children) > 0 || count($value) > 0) { $list[] = array("title" => $label == '' ? ucwords(str_replace("_", " ", $entry)) : $label, "path" => $urlPath, "children" => $children, "icon" => $icon); } } } array_multisort($list, SORT_ASC); return $list; }
/** * Test add method. * * @return void */ public function testAdd() { Cache::set(array('duration' => 1), null, 'memcached'); Cache::delete('test_add_key', 'default'); $result = Cache::add('test_add_key', 'test data', 'default'); $this->assertTrue($result); $expected = 'test data'; $result = Cache::read('test_add_key', 'default'); $this->assertEquals($expected, $result); $result = Cache::add('test_add_key', 'test data 2', 'default'); $this->assertFalse($result); }
public function getOrderedChunk($X, $Z, $Yndex) { if (!isset($this->level)) { return false; } if (ADVANCED_CACHE == true and $Yndex == 0xff) { $identifier = "world:{$this->name}:{$X}:{$Z}"; if (($cache = Cache::get($identifier)) !== false) { return $cache; } } $raw = array(); for ($Y = 0; $Y < 8; ++$Y) { if (($Yndex & 1 << $Y) > 0) { $raw[$Y] = $this->level->getMiniChunk($X, $Z, $Y); } } $ordered = ""; $flag = chr($Yndex); for ($j = 0; $j < 256; ++$j) { $ordered .= $flag; foreach ($raw as $mini) { $ordered .= substr($mini, $j << 5, 24); //16 + 8 } } if (ADVANCED_CACHE == true and $Yndex == 0xff) { Cache::add($identifier, $ordered, 60); } return $ordered; }
/** * @param array $libraryPaths * * @throws ServiceUnavailableException */ protected static function initializeLibraryPaths($libraryPaths = null) { static::$libraryPaths = \Cache::get('scripting.library_paths', []); static::$libraries = \Cache::get('scripting.libraries', []); // Add ones from constructor $libraryPaths = ArrayUtils::clean($libraryPaths); // Application storage script path $libraryPaths[] = storage_path('scripting'); // Merge in config libraries... $libraryPaths = array_merge($libraryPaths, ArrayUtils::clean(\Config::get('df.scripting.paths', []))); // Add them to collection if valid if (is_array($libraryPaths)) { foreach ($libraryPaths as $path) { if (!in_array($path, static::$libraryPaths)) { if (!empty($path) || is_dir($path) || is_readable($path)) { static::$libraryPaths[] = $path; } else { Log::debug("Invalid scripting library path given {$path}."); } } } } \Cache::add('scripting.library_paths', static::$libraryPaths, static::DEFAULT_CACHE_TTL); if (empty(static::$libraryPaths)) { Log::debug('No scripting library paths found.'); } }
/** * deliver * * this is the reason all we did all this * * @return nothing */ protected function deliver() { $this->execute('preDeliver'); $buffer = ob_get_clean(); $config = array('indent' => true, 'input-xml' => true, 'wrap' => 200); $tidy = tidy_repair_string($buffer, $config, 'UTF8'); if (!$this->isAdmin && !$this->is_404() && ENABLE_CACHE && ENABLE_PAGE_CACHE && class_exists('Cache')) { Cache::add($this->cacheKey, (string) $tidy); } $this->fc->deliver($tidy); $this->execute('postDeliver'); $this->runHooks[] = 'deliver'; return; }
<?php /** * Created by PhpStorm. * User: kevin * Date: 14/10/11 * Time: 17:21 */ return array('appkey' => '', 'appsecret' => '', 'debounce' => 30, 'retry' => 3, 'logger' => function ($message, $context, $flag) { if (!is_array($context)) { $context = ['context' => $context]; } $context['flag'] = $flag; Log::debug($message, $context); return TRUE; }, 'set_cache' => function ($key, $value, $duration) { $expiresAt = \Carbon\Carbon::now()->addSeconds($duration); return Cache::add('laravel-sms-' . $key, $value, $expiresAt); }, 'get_cache' => function ($key) { return Cache::get('laravel-sms-' . $key, false); }, 'class_name' => '\\Sms\\Tui3');
?> <div data-lastcheck="" data-offset="{{\Config::get('post-per-page')}}" data-type="user-timeline" id="post-list"> {{Theme::extend('timeline-post')}} <?php $counter = 0; ?> @foreach($posts as $post) @if(Cache::has('post-'.$post->id)) {{Cache::get('post-'.$post->id)}} @else <?php $postContent = (string) Theme::section('post.media', ['post' => $post]); if (Config::get('enable-query-cache', 0)) { Cache::add('post-' . $post->id, $postContent, Config::get('post-cache-time-out', 3)); } ?> {{$postContent}} @endif {{Theme::extend('timeline-post-'.$counter)}} <?php $counter++; ?> @endforeach </div> @if(count($posts))
private function initialize($node) { $this->title = ''; $this->keywords = ''; $this->description = ''; $this->html = ''; $this->css = ''; $this->js = ''; $is_404 = null === $this->page; $this->page = SystemPage::get($node->getProperty('reference')); if (null === $this->page) { header("HTTP/1.0 404 Not Found"); $this->initialize(Router::$root->getById(Config::get('404_PAGE'))); return; } $this->title = $node->getProperty('title'); $this->keywords = $node->getProperty('keywords'); $this->description = $node->getProperty('description'); $this->render_page(); $this->render_view(); ob_start(); eval('?>' . $this->html); if (count(Router::$parts)) { ob_end_clean(); Router::$parts = array(); header("HTTP/1.0 404 Not Found"); $this->initialize(Router::$root->getById(Config::get('404_PAGE'))); return; } if (Config::get('CACHE_ENABLED')) { Cache::add(Router::$url, Router::export() . $this->html); $filename = 'cache/' . md5(Router::$url); file_put_contents($filename, php_strip_whitespace($filename)); } }
/** * Test add method. * * @return void */ public function testAdd() { Cache::delete('test_add_key', 'default'); $result = Cache::add('test_add_key', 'test data', 'default'); $this->assertTrue($result); $expected = 'test data'; $result = Cache::read('test_add_key', 'default'); $this->assertEquals($expected, $result); $result = Cache::add('test_add_key', 'test data 2', 'default'); $this->assertFalse($result); }
public static function getMulti($params, $mode = SQLDatabaseModel::MODE_ASSOC) { //Load all models $fields = array(); $field_infos = array(); $models = array(); $fieldDescriptions = array(); $headers = array(); $fixedConditions = array(); foreach ($params["fields"] as $field) { $fieldreferences = explode(", ", $field); if (count($fieldreferences) == 1) { $fields[] = (string) $field; $field_infos[] = Model::resolvePath((string) $field); } else { $fields[] = $fieldreferences; foreach ($fieldreferences as $ref) { $infos[] = Model::resolvePath((string) $ref); } $field_infos[] = $infos; } } foreach ($fields as $i => $field) { if (is_array($field)) { foreach ($field_infos[$i] as $info) { if (array_search($info["model"], array_keys($models)) === false) { $models[$info["model"]] = Model::load($info["model"]); } } } else { if (array_search($field_infos[$i]["model"], array_keys($models)) === false) { $models[$field_infos[$i]["model"]] = Model::load($field_infos[$i]["model"]); if ($models[$field_infos[$i]["model"]]->fixedConditions != "") { $fixedConditions[] = $models[$field_infos[$i]["model"]]->fixedConditions; } } } } // Replace any conditions with filters if (isset($params['filter'])) { $params['conditions'] = $params['filter']; } else { $params['conditions'] = ''; } if (count($fixedConditions) > 0) { $params["conditions"] = ($params["conditions"] == "" ? "" : "(" . $params["conditions"] . ") AND ") . "(" . implode(" AND ", $fixedConditions) . ")"; } //Buld the query $query = "SELECT "; $fieldList = array(); $rawFields = array(); $functions = $params["global_functions"]; foreach ($fields as $i => $field) { $field_info = $field_infos[$i]; if (is_array($field)) { $concatFieldList = array(); foreach ($field_info as $info) { $fieldData = $models[$info["model"]]->getFields(array($info["field"])); $concatFieldList[] = $models[$info["model"]]->datastore->formatField($fieldData[0], $models[$info["model"]]->getDatabase() . "." . $info["field"], true, null, true); $rawFields[] = $models[$info["model"]]->getDatabase() . "." . $info["field"]; } $fieldList[] = $models[$info["model"]]->datastore->applySqlFunctions($models[$info["model"]]->datastore->concatenate($concatFieldList), $functions); } else { $fieldData = $models[$field_infos[$i]["model"]]->getFields(array($field_info["field"])); $fieldDescriptions[] = $fieldData[0]; $headers[] = $fieldData[0]["label"]; $fieldList[] = $models[$field_info["model"]]->datastore->formatField($fieldData[0], $models[$field_info["model"]]->getDatabase() . "." . $field_info["field"], true, $functions, true); $rawFields[] = $models[$field_info["model"]]->getDatabase() . "." . $field_info["field"]; } } if ($params['moreInfoOnly'] === true) { return array("data" => $data, "fieldInfos" => $fieldDescriptions, "headers" => $headers, "rawFields" => $rawFields); } $tableList = array(); foreach ($models as $model) { $tableList[] = $model->getDatabase(); } $joinConditions = array(); $hasDontJoin = is_array($params['dont_join']); foreach ($models as $model) { foreach ($models as $other_model) { // skip if the models are the same if ($model->name == $other_model->name) { continue; } if ($model->hasField($other_model->getKeyField())) { if ($hasDontJoin) { $modelPair = "{$model->package},{$other_model->package}"; $fieldPair = "{$model->package}.{$other_model->getKeyField()},{$other_model->package}.{$other_model->getKeyField()}"; Application::log('GET_MULTI')->debug("Trying to skip a join", ['model_pair' => $modelPair, 'field_pair' => $fieldPair, 'dont_join' => $params['dont_join']]); if (array_search($modelPair, $params['dont_join']) !== false) { continue; } if (array_search($fieldPair, $params['dont_join']) !== false) { continue; } } $joinConditions[] = "{$model->getDatabase()}.{$other_model->getKeyField()}={$other_model->getDatabase()}.{$other_model->getKeyField()}"; } } } if ($params["distinct"] === true) { $query .= " DISTINCT "; } // Apply any special modifiers to the fields if ($params["count"] === true || $params["enumerate"] === true) { $query .= ' COUNT(*) as "count" FROM ' . implode(', ', array_unique($tableList)); } else { if ($params["sum"] === true) { $query .= "SUM(" . implode("), SUM(", $rawFields) . ") FROM " . implode(", ", array_unique($tableList)); } else { if ($params["max"] === true) { $query .= "MAX(" . implode("), MAX(", $rawFields) . ") FROM " . implode(", ", array_unique($tableList)); } else { $query .= ($params["resolve"] === false ? implode(",", $rawFields) : implode(",", $fieldList)) . " FROM " . implode(",", array_unique($tableList)); } } } if (count($joinConditions) > 0) { $query .= " WHERE (" . implode(" AND ", $joinConditions) . ") "; $query .= strlen($params["conditions"]) > 0 ? " AND (" . $params["conditions"] . ")" : ""; } else { $query .= strlen($params["conditions"]) > 0 ? " WHERE " . $params["conditions"] : ""; } if (is_array($params["sort_field"]) && $params["count"] !== true) { if (count($params["sort_field"]) > 0) { $query .= " ORDER BY "; $orderClauses = array(); foreach ($params["sort_field"] as $sortField) { if ($sortField["field"] == "") { continue; } $orderClauses[] = "{$sortField["field"]} {$sortField["type"]}"; } $query .= implode(", ", $orderClauses); } } else { if ($params["sort_field"] != "" && $params["count"] !== true) { $query .= " ORDER BY {$params["sort_field"]} {$params["sort_type"]}"; } } if ($params["group_field"] != "") { $query .= " GROUP BY {$params["group_field"]}"; foreach ($rawFields as $field) { if ($field != $params["group_field"]) { $query .= "," . $field; } } } if (isset($params["limit"])) { $query .= " LIMIT ?"; $params['bind'][] = $params['limit']; } if (isset($params['offset'])) { $query .= " OFFSET ?"; $params['bind'][] = $params['offset']; } Application::log()->info($params['cache_key']); $data = $other_model->datastore->query($query, $mode, $params['bind'], $params['cache_key']); if (isset($params['cache_key'])) { Cache::add($params['cache_key'], $query); } if ($params["moreInfo"] === true) { if (isset($params['cache_key'])) { Cache::add("{$params['cache_key']}_meta", ['fieldInfos' => $fieldDescriptions, 'headers' => $headers, 'rawFields' => $rawFields]); } return array("data" => $data, "fieldInfos" => $fieldDescriptions, "headers" => $headers, "rawFields" => $rawFields); } else { return $data; } }
/** * call the WIB API and convert urls into trackable urls * * @param mixed $urls * @return void * @author Craig Ulliott */ function track_urls($urls, $additional_params = null) { // to make the code easier, and accept one or an array of urls if (!is_array($urls)) { $urls = array($urls); $return_single = true; } else { $return_single = false; } // save on bandwidth $unique_urls = array_unique($urls); // here we add any new params we want to the url if ($additional_params) { foreach ($unique_urls as $k => $url) { // we cant add params to some urls if (!stristr($url, 'ad.doubleclick.net')) { $unique_urls[$k] = http_add_params($url, $additional_params); } } } // build an assoc array to return the new urls $new_urls = array(); // build cache keys $cache_keys = array(); foreach ($unique_urls as $url) { $cache_keys[] = 'track_urls_' . $url; } // try the cache first foreach (Cache::get($cache_keys) as $cache_key => $lilurl) { $url = substr($cache_key, 11); // add to the new url list $new_urls[$url] = $lilurl; // remove from the $unique_urls queue $k = array_search($url, $unique_urls); if ($k !== false) { unset($unique_urls[$k]); } } // we want to get all the remaining lilurls in one call WIB::getClient()->start_batch(); // loop through each foreach ($unique_urls as $url) { // if we didnt get it from the cache if (!array_key_exists($url, $new_urls)) { $response = WIB::getClient()->call_method('lilurl.create', array('url' => $url)); } } // get the results $results = WIB::getClient()->run_batch(); // get only the parts we want from each URL foreach ($results as $result) { //the url we passed to the wib api $tracked_url = array_val($result, array('results', 0, 'url')); // we now go back to the very original $urls array, as we dont want to pass back the "additional params" $k = array_search($tracked_url, $unique_urls); $original_url = $urls[$k]; $tracking_url = array_val($result, array('results', 0, 'lilurl')); if ($original_url && $tracking_url) { // add it to the result $new_urls[$original_url] = $tracking_url; // cache it for next time $from_cache = Cache::add('track_urls_' . $original_url, $tracking_url); } } if ($return_single) { return reset($new_urls); } return $new_urls; }
function getProductPopupData($lang = 'id') { $result = Cache::get('product_popup_data_' . $lang, function () use($lang) { $promo = App\Models\Product::Active()->Promo()->first(); if ($promo) { $data['photo'] = $promo->thumbnail; $data['slug'] = $promo->slug; if ($lang == 'en') { $data['product'] = $promo->name_en; $data['label'] = $promo->promo_label_en; } else { $data['product'] = $promo->name_id; $data['label'] = $promo->promo_label_id; } Cache::add('product_popup_data_' . $lang, $data, 1); return $data; } return false; }); return $result; }
private static function _load($model, $path) { global $packageSchema; global $redirectedPackage; $model = (substr($model, 0, 1) == "." ? $redirectedPackage : "") . $model; $model_path = SOFTWARE_HOME . ($path == null ? Application::$packagesPath : $path) . "app/modules/" . str_replace(".", "/", $model) . "/"; $modelClassName = Application::camelize($model) . "Model"; add_include_path($model_path, false); $array = explode(".", $model); $model_name = array_pop($array); if (file_exists("{$model_path}/model.xml")) { if (CACHE_MODELS) { Cache::add("model_path_{$model}", $model_path); } $instance = XMLDefinedSQLDatabaseModel::create($model_path, $model_name, $model, $path); $instance->postInitHook(); } else { if (file_exists("{$model_path}/{$modelClassName}.php")) { if (CACHE_MODELS) { Cache::add("model_path_{$model}", $model_path); } $instance = new $modelClassName($model, $model_name); $instance->postInitHook(); } else { $modelPathArray = explode(".", $model); $baseModelPath = SOFTWARE_HOME . ($path == null ? Application::$packagesPath : $path) . "app/modules/"; foreach ($modelPathArray as $index => $path) { $baseModelPath = $baseModelPath . "{$path}/"; if (file_exists($baseModelPath . "package_redirect.php")) { include $baseModelPath . "package_redirect.php"; $modelPathArray = array_slice($modelPathArray, $index + 1); $modelClassName = $package_name . Application::camelize(implode(".", $modelPathArray)) . "Model"; $modelIncludePath = SOFTWARE_HOME . $redirect_path . "/" . implode("/", $modelPathArray); $packageSchema = $package_schema; $redirectedPackage = $redirectedPackage == "" ? $package_path : $redirectedPackage; add_include_path($modelIncludePath, false); $instance = new $modelClassName($model, $model_name); $instance->redirectedPackage = $redirectedPackage; $instance->packageSchema = $packageSchema; $instance->postInitHook(); if (CACHE_MODELS) { Cache::add("model_path_{$model}", $modelIncludePath); } } } if ($instance == null) { throw new ModelException("Failed to load Model [{$model}] with [{$modelClassName}]"); } } } return $instance; }