Example #1
0
 public function getCached(ImportEvent $event)
 {
     $data = $this->cache->get('admin-panels-cached', function () use($event) {
         $fresh = new ImportEvent($event->getViewEvent());
         $this->dispatcher->fire(AdminEvent::IMPORT_ADMIN_DASHBOARD_PANELS, $fresh);
         return $fresh->getContent();
     }, 300);
     $event->setContent($data);
 }
Example #2
0
 public function getData(SeoEvent $event)
 {
     $url = $event->getUrl();
     $result = $this->cache->get('seo-titles', function () {
         return $this->config->get('seo');
     }, 3600);
     if ($data = $result['titles'][$url] ?? null) {
         if (!empty($data['title'])) {
             $event->setTitle($data['title']);
         }
         if (!empty($data['description'])) {
             $event->setMeta([['name' => 'description', 'content' => $data['description']]]);
         }
     }
 }
Example #3
0
 /**
  * @param string $viewFile
  * @param bool $withLayout
  * @param bool $useCache
  *
  * @return ViewParser
  * @throws ViewError
  */
 public function loadViewFile(string $viewFile, bool $withLayout = true, bool $useCache = true)
 {
     $compiler = function () use($viewFile, $withLayout) {
         if ($files[] = $path = $this->resolver->getView($viewFile)) {
             if ($withLayout === true) {
                 for ($i = 0, $layout = dirname($viewFile); $i <= 10 && $layout !== '.'; $layout = dirname($layout), $i++) {
                     $includes[] = $layout;
                 }
                 $includes = array_merge($includes ?? [], ['Global']);
             }
             if ($additionalLayouts = $this->getAdditionalLayoutFiles()) {
                 $includes = array_merge($includes ?? [], $additionalLayouts);
             }
             if (!empty($includes)) {
                 $files = array_merge($files, array_filter(array_map(function ($l) {
                     return $this->resolver->getView("Layout\\{$l}");
                 }, $includes)));
             }
             $compiled = $this->compiler->compile($files);
             return $compiled;
         } else {
             throw new ViewError("Unable to find view file: {$viewFile}");
         }
     };
     $this->content = $useCache ? $this->cache->get("compiled:{$viewFile}", $compiler, self::CACHE_TIMEOUT) : $compiler();
     return $this;
 }
Example #4
0
 /**
  * Bind listeners defined in plugins, app and Database
  */
 public function bind()
 {
     $listeners = $this->cache->get('app-listeners', function () {
         foreach ($this->resolver->getListeners() as $file) {
             try {
                 $binding = $this;
                 require_once $file;
             } catch (\Throwable $e) {
                 $this->logger->warn("Unable to include {$file}: " . $e->getMessage());
             }
         }
         $listeners = $this->getListeners();
         if ($this->database->isConnected()) {
             /** @var ModelEx $eventModel */
             if ($eventModel = $this->resolver->getModel('Event', true)) {
                 try {
                     foreach ($eventModel::all() as $item) {
                         $attrs = $item->attributesToArray();
                         list($class, $func) = @explode('@', $attrs['handler']);
                         $event = array_merge($attrs, ['event' => $attrs['name'], 'handler' => [sprintf('\\%s', ltrim($class, '\\')), $func ?? 'index']]);
                         $listeners[] = $event;
                     }
                 } catch (\Exception $e) {
                 }
             }
         }
         return $listeners;
     }, 300);
     foreach ($listeners as $listener) {
         $this->dispatcher->listen($listener['event'], $listener['handler'], $listener['priority'] ?? 99, $listener['data'] ?? '');
     }
 }
Example #5
0
 /**
  * Save site configuration using keys like /public/host, /private/api_keys/google/token, etc
  *
  * @param string $key
  * @param $value
  * @param bool $create - create this key if it does not exists when true, fails if false and key isn't already present
  *
  * @return bool
  */
 public function set(string $key, $value, bool $create = false)
 {
     list($type, $path) = explode('/', ltrim($key, '/'), 2);
     if ($create || $this->get($key) !== false) {
         $data = $this->get($type, []);
         $this->update($data, $path, $value);
         if ($model = $this->getConfigModel()) {
             $model::unguard();
             if ($model::updateOrCreate(['type' => $type], ['data_json' => json_encode($data)])) {
                 $this->cache->remove("config-{$type}");
                 return true;
             }
         }
     }
     return false;
 }
Example #6
0
 public function getEventIdByEventName(string $eventName)
 {
     return $this->cache->get("event-name-{$eventName}", function () use($eventName) {
         if (!($event = MEventName::where('event_name', '=', $eventName)->first())) {
             MEventName::unguard(true);
             $event = MEventName::create(['event_name' => $eventName]);
         }
         return !empty($event) ? $event->event_name_id : 0;
     }, 86400);
 }
Example #7
0
 public function getTargetUserIds(int $ar_list_id) : array
 {
     return $this->qCache->get("ar-list-id-{$ar_list_id}", function () use($ar_list_id) {
         $results = ['positive' => [], 'negative' => []];
         if ($list = MArList::find($ar_list_id)) {
             $sqls = MArListSql::where('ar_list_id', '=', $ar_list_id)->get();
             foreach ($sqls as $sql) {
                 $users = $this->qCache->get(md5($sql->sql), function () use($sql) {
                     foreach ($this->db->getPdo()->query($sql->sql) as $row) {
                         $results[] = $row[0];
                     }
                     return $results ?? [];
                 });
                 $results[$sql->type] = array_merge($results[$sql->type], $users);
             }
         }
         return array_diff($results['positive'], $results['negative']) ?: [];
     }, 3600);
 }
Example #8
0
 public function compile(ImportEvent $event)
 {
     $plugins = [];
     $basedir = realpath(sprintf('%s/../../../..', __DIR__));
     $results = $this->cache->get('plugin-list', function () {
         return $this->client->getPackages();
     }, 300);
     foreach ($results ?? [] as $package) {
         $plugin = $package['name'];
         if ($plugin !== 'minutephp/minutephp' && $plugin !== 'minutephp/framework') {
             $name = join(' ', array_slice(preg_split('/\\W+/', $plugin), 1));
             $vendor = dirname($plugin);
             $official = $vendor === 'minutephp';
             $type = $official ? 'official' : 'thirdparty';
             $required = ['admin', 'framework'];
             $plugins[$type][] = ['plugin' => $plugin, 'name' => $name, 'description' => $package['description'], 'installed' => is_dir("{$basedir}/{$plugin}"), 'required' => $official && in_array($name, $required), 'src' => $package['src']];
         }
     }
     $event->setContent($plugins);
 }
Example #9
0
 public function minify(ResponseEvent $event)
 {
     if ($event->isSimpleHtmlResponse()) {
         /** @var HttpResponseEx $response */
         $response = $event->getResponse();
         try {
             if ($content = $response->getContent()) {
                 $settings = $this->cache->get('minify-settings', function () {
                     return $this->config->get(self::MINIFY_KEY);
                 }, 3600);
                 $version = $settings['version'] ?? 0 ?: 0.01;
                 if (!empty($settings['css']['files'])) {
                     $content = $this->compress('#<lin' . 'k (?:.+)?href="(/static/(?!cache/)[^"]+\\.css)"(?:.*)/?>#', $content, 'css', $version, $settings['css']['excludes'] ?? null);
                 }
                 if (!empty($settings['js']['files'])) {
                     $content = $this->compress('#<scrip' . 't (?:.+)?src="(/static/(?!cache/)[^"]+\\.js)"(?:.*)>\\s*</script>#', $content, 'js', $version, $settings['js']['excludes'] ?? null);
                 }
                 $response->setContent($content);
             }
         } catch (\Exception $e) {
             echo '';
         }
     }
 }
Example #10
0
 public function getCachedSessionData($reload)
 {
     $key = sprintf("session-user-%d", $this->session->getLoggedInUserId());
     $userData = function () {
         $user_id = $this->session->getLoggedInUserId();
         /** @var User $user_info */
         if ($user_info = User::find($user_id)) {
             $user_data = array_diff_key($user_info->getAttributes(), ['password' => 1, 'verified' => 1, 'ident' => 1]);
             $user_data['groups'] = $this->userInfo->getUserGroups($user_id, true) ?: [];
         } else {
             $user_data = null;
         }
         if (!empty($user_data) && empty($user_data['full_name'])) {
             $user_data['full_name'] = trim(sprintf('%s %s', $user_data['first_name'], $user_data['last_name'])) ?: 'Anonymous';
         }
         foreach ($this->providers->getEnabled() as $provider) {
             unset($provider['key'], $provider['secret']);
             $providers[] = $provider;
         }
         return ['site' => $this->config->getPublicVars(), 'user' => $user_data, 'providers' => $providers ?? []];
     };
     $data = $reload ? $userData() : $this->cache->get($key, $userData, 300);
     return $data;
 }
Example #11
0
 public function clearCache($userId)
 {
     foreach ([true, false] as $extended) {
         $this->cache->remove("user-groups-{$userId}-{$extended}");
     }
 }
Example #12
0
 /**
  * @param string $table
  *
  * @return array
  */
 public function getColumns($table)
 {
     return $this->cache->get("columns-{$table}", function () use($table) {
         return $this->capsule->schema()->getColumnListing($table);
     });
 }
Example #13
0
 public function flushCache()
 {
     printf('Cache cleared!');
     $this->cache->flush();
 }