Esempio n. 1
0
 public function setLocale($lang)
 {
     switch ($lang) {
         case 'en':
             setlocale(LC_ALL, 'en_EN.UTF8', 'en_EN.UTF-8', 'en_EN	');
             break;
         case 'cs':
         default:
             setlocale(LC_ALL, 'cs_CZ.UTF8', 'cs_CZ.UTF-8', 'cs_CZ');
     }
     $this->lang = $lang;
     $cache = Environment::getCache();
     $cacheName = 'getText-' . $this->lang;
     if (isset($cache[$cacheName])) {
         $this->dictionary = unserialize($cache[$cacheName]);
     } else {
         $dict = new Model\Dictionary('utils/translate');
         try {
             $this->dictionary = $dict->getPairs($this->lang);
             $cache->save($cacheName, serialize((array) $this->dictionary), array('expire' => time() + 60 * 30, 'refresh' => TRUE, 'tags' => array('dictionary')));
         } catch (DibiException $e) {
             echo $e;
         }
     }
 }
function log_write($data, FileDownload $file, IDownloader $downloader)
{
    $cache = Environment::getCache("FileDownloader/log");
    $log = array();
    $tid = (string) $file->getTransferId();
    if (!isset($cache["registry"])) {
        $cache["registry"] = array();
    }
    $reg = $cache["registry"];
    $reg[$tid] = true;
    $cache["registry"] = $reg;
    if (isset($cache[$tid])) {
        $log = $cache[$tid];
    }
    Debugger::fireLog("Data: " . $data . "; " . $downloader->end);
    $data = $data . ": " . Helpers::bytes($file->transferredBytes) . " <->; ";
    if ($downloader instanceof AdvancedDownloader and $downloader->isInitialized()) {
        $data .= "position: " . Helpers::bytes($downloader->position) . "; ";
        //$data .= "length: ".Helpers::bytes($downloader->length)."; ";
        $data .= "http-range: " . Helpers::bytes($downloader->start) . "-" . Helpers::bytes($downloader->end) . "; ";
        $data .= "progress (con: " . round($file->transferredBytes / $downloader->end * 100) . "% X ";
        $data .= "file: " . round($downloader->position / $file->sourceFileSize * 100) . "%)";
    }
    $log[] = $data;
    $cache[$tid] = $log;
}
Esempio n. 3
0
 public static function createValidator()
 {
     $loader = new Validator\Mapping\Loader\AnnotationLoader();
     $cache = Environment::isProduction() ? new ValidatorCache(Environment::getCache("SymfonyValidator")) : null;
     $metadataFactory = new Validator\Mapping\ClassMetadataFactory($loader, $cache);
     $validatorFactory = new Validator\ConstraintValidatorFactory();
     $validator = new Validator\Validator($metadataFactory, $validatorFactory);
     return $validator;
 }
Esempio n. 4
0
 /**
  * Get table config
  * @return Config
  */
 public function getConfig()
 {
     if (empty($this->config)) {
         $cacheKey = get_class($this) . "-" . $this->table . "-" . $this->rowClass;
         $cache = Environment::getCache("Ormion");
         if (isset($cache[$cacheKey])) {
             $this->config = $cache[$cacheKey];
         } else {
             $tableInfo = $this->getDb()->getDatabaseInfo()->getTable($this->table);
             $this->config = Config::fromTableInfo($tableInfo);
             $cache[$cacheKey] = $this->config;
         }
     }
     return $this->config;
 }
Esempio n. 5
0
 public function onFlush(Event\OnFlushEventArgs $args)
 {
     $em = $args->getEntityManager();
     $uow = $em->getUnitOfWork();
     $tags = array();
     foreach ($uow->getScheduledEntityDeletions() as $entity) {
         $tags[] = get_class($entity);
         $tags[] = $entity->getCacheKey();
     }
     foreach ($uow->getScheduledEntityUpdates() as $entity) {
         $tags[] = get_class($entity);
         $tags[] = $entity->getCacheKey();
     }
     Environment::getCache()->clean(array(Cache::TAGS => array_unique($tags)));
 }
Esempio n. 6
0
 /**
  * Tries to find out the mimetype for file specified in param.
  * The query is based on file extension. If system contains mime_content_type
  * function it takes precedence. If no match is found the application/octet-stream
  * is returned.
  * 
  * @param string path to file
  * @param string|null fiele extension, if null it will be taken as last .part in filepath
  */
 static function getMimeType($filepath, $extension = null)
 {
     if (function_exists("mime_content_type")) {
         $mime = mime_content_type($filepath);
         if (self::isValidMimeType($mime)) {
             return $mime;
         }
     }
     $cache = Nette\Environment::getCache("vBuilder.Download");
     if (!isset($cache["mime-types"])) {
         $m = parse_ini_file(__DIR__ . '/' . self::MIME_INI_FILEPATH);
         if ($m != false) {
             $cache["mime-types"] = $m;
         }
     }
     if ($extension == null) {
         $extension = pathinfo($filepath, PATHINFO_EXTENSION);
     }
     if (array_key_exists($extension, $cache["mime-types"])) {
         $mime = $cache["mime-types"][$extension];
     }
     return self::isValidMimeType($mime) ? $mime : "application/octet-stream";
 }
Esempio n. 7
0
 public function handleTrashDeleteOne($id)
 {
     if ($id > 0) {
         $item = $this->items->fetch($id);
         if (!$item) {
             $this->flashMessage('There is no file to delete', 'info');
             $this->redirect('default');
         } else {
             try {
                 if (file_exists(FILESTORAGE_DIR . '/' . $item['filename'])) {
                     unlink(FILESTORAGE_DIR . '/' . $item['filename']);
                 }
                 if (file_exists(TEMP_DIR . '/imagecache/' . $id)) {
                     $this->deltree(TEMP_DIR . '/imagecache/' . $id);
                 }
             } catch (Exception $e) {
                 $this->flashMessage('Brutal error on the disk!', 'err');
             }
             $this->items->delete($id);
             $this->flashMessage('The file has been completely deleted.', 'ok');
         }
     } else {
         $this->flashMessage('Missing ID of file!', 'err');
     }
     $cache = Environment::getCache();
     $cache->clean(array('tags' => array('photogallery', 'files', 'filesystem')));
 }
Esempio n. 8
0
 public function getRolesToSelect()
 {
     $cache = Environment::getCache('application/acl');
     $cacheName = 'roles_to_select';
     if (isset($cache[$cacheName])) {
         return unserialize($cache[$cacheName]);
     } else {
         $roles = dibi::query("\n\t          SELECT [r.name] AS [role_name], if(!ISNULL([r.note]),CONCAT([r.name],' - ',[r.note]),[r.name])  AS [ident]\n\t          FROM [users_roles] AS [r] LEFT JOIN [users_roles] AS [rp] ON [r.parent_id] = [rp.id]\n\t          ORDER BY [r.id] ASC;");
         $roles = $roles->fetchPairs('role_name', 'ident');
         $cache->save($cacheName, serialize((array) $roles), array('expire' => time() + 60 * 60 * 30, 'refresh' => TRUE, 'tags' => array('system', 'acl')));
         return $roles;
     }
 }
 /**
  * Renders HTML code for custom panel.
  * @return string
  * @see IDebugPanel::getPanel()
  */
 public function getPanel()
 {
     if ($this->response instanceof \Nette\Application\Responses\ForwardResponse || $this->response instanceof \Nette\Application\Responses\RedirectResponse) {
         return '';
     }
     /** @var Template */
     $template = new FileTemplate();
     $template->setFile(dirname(__FILE__) . "/bar.latte");
     $template->registerFilter(new Engine());
     $template->presenter = $template->control = $template->rootComponent = Environment::getApplication()->getPresenter();
     if ($template->presenter === NULL) {
         return NULL;
     }
     $template->wrap = static::$wrap;
     $template->cache = static::$cache ? Environment::getCache('Debugger.Panels.ComponentTree') : NULL;
     $template->dumps = static::$dumps;
     $template->parametersOpen = static::$parametersOpen;
     $template->presenterOpen = static::$presenterOpen;
     $template->showSources = static::$showSources;
     $template->omittedVariables = static::$omittedTemplateVariables;
     $template->registerHelper('parametersInfo', callback($this, 'getParametersInfo'));
     $template->registerHelper('editlink', callback($this, 'buildEditorLink'));
     $template->registerHelper('highlight', callback($this, 'highlight'));
     $template->registerHelper('filterMethods', callback($this, 'filterMethods'));
     $template->registerHelper('renderedTemplates', callback($this, 'getRenderedTemplates'));
     $template->registerHelper('isPersistent', callback($this, 'isPersistent'));
     $template->registerHelperLoader('Nette\\Templating\\Helpers::loader');
     ob_start();
     $template->render();
     return ob_get_clean();
 }
Esempio n. 10
0
 /**
  * Remove cached html from cache
  * @param IRecord record
  */
 public function clearCache(IRecord $record)
 {
     $cache = Environment::getCache(__NAMESPACE__ . "-" . __CLASS__ . "-" . get_class($record) . "-" . $this->name);
     $key = $record->getPrimary();
     unset($cache[$key]);
 }
Esempio n. 11
0
 /**
  * Get cache
  *
  * @param string $namespace nella namespace suffix
  * @return Nette\Caching\Cache
  */
 public static function getCache($namespace = NULL)
 {
     return \Nette\Environment::getCache($namespace ? "ActiveMapper." . $namespace : "ActiveMapper");
 }
Esempio n. 12
0
 /**
  * @return Nette\Caching\Cache
  */
 protected static function getCache()
 {
     return Nette\Environment::getCache('Nette.Annotations');
 }
Esempio n. 13
0
 public function getGlobalCategoriesArray($type, $hidden = false, $zero = false)
 {
     $cache = Environment::getCache('application/system');
     $cacheName = 'category_to_select/' . $type . '/' . $hidden;
     if (isset($cache[$cacheName])) {
         return unserialize($cache[$cacheName]);
     } else {
         $res = dibi::select('[id], [name]')->from('[category] [c]')->where($type . ' = 1')->orderBy('name');
         if (!$hidden) {
             $res->where('visible', '=', '1');
         }
         $res = $res->fetchPairs('id', 'name');
         if ($zero) {
             $a = array(0 => '---');
             $res = $a + $res;
         }
         $cache->save($cacheName, serialize((array) $res), array('expire' => time() + 60 * 60 * 30, 'refresh' => TRUE, 'tags' => array('system', 'category', $type)));
         return $res;
     }
 }
Esempio n. 14
0
 public function __construct()
 {
     $this->data = Environment::getCache('Doctrine');
 }
<?php

use Nette\Environment;
Environment::getHttpResponse()->setHeader("refresh", "1");
$cache = Environment::getCache("FileDownloader/log");
echo "<html><body>";
echo "<h1>Log console (called events)</h1>";
echo "<p>Clear log = delete temp files</p>";
echo "<style>p{font-size: 11px;font-family: monospace;}</style>";
$reg = $cache["registry"];
$y = 0;
if (count($reg) > 0) {
    krsort($reg);
    foreach ($reg as $tid => $none) {
        $y++;
        $tid = (string) $tid;
        $log = $cache[$tid];
        $i = 0;
        if (count($log) > 0) {
            krsort($log);
            foreach ($log as $key => $val) {
                if ($i == 0) {
                    echo "<h2>Con. #" . $tid;
                    if (strstr($val, "Abort")) {
                        echo " <span style=\"color: orange;\">(Aborted)</span>";
                    } elseif (strstr($val, "Lost")) {
                        echo " <span style=\"color: red;\">(Connection losted)</span>";
                    } elseif (strstr($val, "Complete")) {
                        echo " <span style=\"color: green;\">(Completed)</span>";
                    } else {
                        echo " (Running)";
Esempio n. 16
0
 public function fetchAllNear($lat, $lon, $distance = 100000, $limit = 10)
 {
     $cache = Environment::getCache('application/subjects');
     $cacheName = 'near-' . $lat . '-' . $lon . '-' . $distance . '-' . $limit;
     if (isset($cache[$cacheName])) {
         return unserialize($cache[$cacheName]);
     } else {
         /* Vytáhnu si všechny koordináty */
         $res = dibi::select('id, lat, lon')->from('subject')->where('deleted = 0')->and('map_coords !=""')->fetchAll();
         /* Zjistím vzdálenost jednotlivých ID od středu */
         $locs = array();
         foreach ($res as $r => $n) {
             $dist = Geolocation::getDistance($lat, $lon, $n['lat'], $n['lon']);
             if ($dist <= $distance && $dist > 1) {
                 $locs[] = array('id' => $n['id'], 'dist' => $dist);
             }
         }
         /* Nestliže nic nenajdu, tak vyhodím chybu. */
         if (count($locs) == 0) {
             return array('fake');
         }
         foreach ($locs as $key => $row) {
             $ids[$key] = $row['id'];
             $distances[$key] = $row['dist'];
         }
         foreach ($locs as $key => $row) {
             $aa[$row['id']] = $row['dist'];
         }
         array_multisort($distances, SORT_ASC, $ids, SORT_ASC, $locs);
         $res = dibi::select('distinct s.*, [sl.name] as [locality], [ss.name] as [shire]')->from('subject')->as('s')->leftJoin('[locality] as [sl]')->on('s.locality_id', '=', 'sl.id')->leftJoin('[shire] as [ss]')->on('sl.shire_id', '=', 'ss.id')->where('s.id IN %l', array_slice($ids, 0, $limit))->groupBy('s.id')->limit($limit);
         $items = $res->fetchAll();
         foreach ($items as $k => $n) {
             $this->getFlags($n);
             $res = dibi::select('[c].*')->from('[categories] as [c]')->leftJoin('[subject_x_category] as [sc]')->on('sc.category_id', '=', 'c.id')->where('sc.subject_id', '=', $n->id);
             $items[$k]['categories'] = $res->fetchAll();
             $items[$k]['distance'] = str_pad(round($aa[$n->id]), 10, "0", STR_PAD_LEFT);
         }
         //$items = \Utils\MyArray::array_msort($items, array('distance'=>SORT_ASC));
         \soundake\MyArray::array_sort($items, 'distance');
         //$items = \Utils\MyArray::array_orderby($items, 'distance', SORT_ASC);
         //\dump($items);
         $cache->save($cacheName, serialize((array) $items), array('expire' => time() + 60 * 60 * 30, 'refresh' => TRUE, 'tags' => array('subjects', 'near')));
         return $items;
     }
 }
Esempio n. 17
0
 /** Catch submitted newItem
  * 
  * @param \Nette\Application\UI\Form $form
  * @throws InvalidStateException
  * @throws Exception
  */
 public function newItemFormSubmitted(Form $form)
 {
     /** test for permissions, if user can add new item */
     $permissions = $this->getUser()->isLoggedIn() ? $this->getUser()->getIdentity()->getRoles() : NULL;
     if (isset($permissions[$this->pageUrl]) && $this->pageConfig['settings']['lvlForAdding'] <= $permissions[$this->pageUrl] || $permissions['admin'] || $this->pageConfig['settings']['lvlForAdding'] == 0) {
         try {
             /** validate date inputs */
             $values = $form->getValues();
             unset($values['kontrolni']);
             // remove antispam
             unset($values['form_created']);
             // remove antispam
             foreach ($values as $key => &$value) {
                 // Because email is added to all forms and not in config,
                 //  it could cause error.
                 if ($key == 'email') {
                     continue;
                 }
                 $confItem = $this->pageConfig['form'][$key];
                 // if date is empty and this item is not mandatory
                 // also skip
                 if ($value == "" && (!isset($confItem['mandatory']) || !$confItem['mandatory'])) {
                     continue;
                 }
                 if ($confItem['type'] == 'calendar') {
                     // check for another conditions
                     if (!empty($this->pageConfig["form"][$key]["greaterEqualThen"])) {
                         $cond = $this->pageConfig["form"][$key]["greaterEqualThen"];
                         if (strtotime($values[$cond]) > strtotime($value)) {
                             $tmp = $value;
                             $value = $values[$cond];
                             $values[$cond] = $tmp;
                             $this->flashMessage('Akce nemůže skončit dříve než začne! Opravte prosím data.', 'error');
                             throw new Exception('badDateFormat');
                             // dump("gg");
                         }
                     }
                     $value = preg_replace('/\\s\\s+/', '', $value);
                     if ($this->itemRepository->isValidDate($value)) {
                         //$value = date('d.m.Y',$date)
                     } else {
                         $this->flashMessage('Zadali jste neplatné datum pro položku ' . $confItem['text'] . '!', 'error');
                         throw new Exception('badDateFormat');
                     }
                 }
             }
             unset($value);
             // get email and save it also to session
             if (isset($values->email)) {
                 $session = $this->getSession('agility');
                 $session->email = $values->email;
                 $email = $values->email;
             } else {
                 $email = '';
             }
             /** create hash for editing link */
             $hash = sha1(microtime() . $email);
             /** add new item to DB */
             $this->itemRepository->add($this->pageUrl, $hash, $this->pageConfig, $this->getHttpRequest(), $values);
             // also dont forget for calendar
             if (isset($this->pageConfig['settings']['calendar'])) {
                 // get from date
                 $dateFrom = date('Y-m-d', strtotime($values[$this->pageConfig['settings']['calendar']['from']]));
                 // get to date
                 if (isset($this->pageConfig['settings']['calendar']['to'])) {
                     // if TO is set
                     $dateTo = date('Y-m-d', strtotime($values[$this->pageConfig['settings']['calendar']['to']]));
                 } else {
                     if (isset($this->pageConfig['settings']['calendar']['duration'])) {
                         // if only duration is known
                         $dateTo = date('Y-m-d', strtotime($values[$this->pageConfig['settings']['calendar']['from']] . ' + ' . $values[$this->pageConfig['settings']['calendar']['duration']] . ' days'));
                     } else {
                         // if TO date is not set
                         $dateTo = NULL;
                     }
                 }
                 $this->calendarRepository->add($this->itemRepository->lastInsertId(), $dateFrom, $dateTo, $this->pageUrl);
             }
             /** auto delete items if wanted */
             if (isset($this->pageConfig['settings']['delete'])) {
                 $this->deleteOld();
             }
             /** sent email if it is enabled */
             if (!empty($this->pageConfig["settings"]["sendEmail"]) && $this->context->parameters['email']['send']) {
                 try {
                     $this->sendMail($this->context->parameters['email']['from'], $email, "Potvrzení nového záznamu", 'newItem', array('title' => $values->title, 'values' => $values, 'hash' => $hash));
                     $this->flashMessage($this->pageConfig["texts"]["successAdd"], 'success');
                 } catch (Exception $e) {
                     $this->flashMessage("Záznam byl uložen, ale došlo k chybě při odesílání emailu - pokud budete potřebovat upravit záznamy, kontaktujte nás na agility.tulak.me.", 'error');
                     \Nette\Diagnostics\Debugger::log('Email cannot be sent! ' . $e->getMessage());
                 }
             } else {
                 $this->flashMessage($this->pageConfig["texts"]["successAdd"], 'success');
             }
             // invalidate cache
             $cache = \Nette\Environment::getCache('Nette.Templating.Cache');
             $cache->clean(array(\Nette\Caching\Cache::TAGS => array('items/' . $this->pageUrl)));
             if (!$this->isAjax()) {
                 // $this->redirect('this');
             } else {
                 $this->invalidateControl('list');
                 $this->invalidateControl('form');
                 $form->setValues(array(), TRUE);
             }
             $this->redirect('Item:default', array('item' => $this->pageUrl));
         } catch (InvalidStateException $e) {
             $this->flashMessage($this->pageConfig["texts"]["failAdd"], 'error');
             throw $e;
         } catch (Exception $e) {
             if ($e->getMessage() != 'badDateFormat') {
                 throw $e;
             }
         }
     }
 }
Esempio n. 18
0
 protected static function getCache()
 {
     return Nette\Environment::getCache(str_replace('\\', '.', get_called_class()));
 }
Esempio n. 19
0
    public function getSubjectsForSelect($what = 'name')
    {
        $cache = \Nette\Environment::getCache('application/system');
        $cacheName = 'subjects_to_select-by-' . $what;
        if (isset($cache[$cacheName])) {
            return unserialize($cache[$cacheName]);
        } else {
            $res = dibi::query('
	      SELECT [s.id], [s.' . $what . '] as [name]
	      FROM [subject] as [s]
	      WHERE [deleted] = 0
	      ORDER BY [s.' . $what . ']
	      ')->fetchPairs('id', 'name');
            $a = array(0 => '---');
            $res = $a + $res;
            $cache->save($cacheName, serialize((array) $res), array('expire' => time() + 60 * 60 * 30, 'refresh' => TRUE, 'tags' => array('system', 'subjects')));
            return $res;
        }
    }
Esempio n. 20
0
 /** Catch submitted editItem
  * is used both by user and admin edit
  * 
  * @param \Nette\Application\UI\Form $form
  * @throws InvalidStateException
  * @throws Exception
  */
 public function editItemFormSubmitted(Form $form)
 {
     /** test for permissions, if user can add new item */
     $permissions = $this->getUser()->isLoggedIn() ? $this->getUser()->getIdentity()->getRoles() : NULL;
     if (isset($permissions[$this->pageUrl]) && $this->pageConfig['settings']['lvlForAdding'] <= $permissions[$this->pageUrl] || $permissions['admin'] || $this->pageConfig['settings']['lvlForAdding'] == 0) {
         try {
             $values = $form->getValues();
             unset($values['kontrolni']);
             // remove antispam
             unset($values['form_created']);
             // remove antispam
             /** if we want to delete, simply delete and skip validations */
             if (!empty($values->delete)) {
                 $this->itemRepository->delete($this->pageUrl, $this->editingRow->authorHash);
                 /** show message and redirect */
                 $this->flashMessage($this->pageConfig["texts"]["successRemove"], 'success');
                 $this->redirect('Item:default', array('item' => $this->pageUrl));
             } else {
                 foreach ($values as $key => &$value) {
                     // Because email and delete is added to all forms and not in config,
                     //  it could cause error.
                     if ($key == 'email' || $key == 'delete') {
                         continue;
                     }
                     $confItem = $this->pageConfig['form'][$key];
                     // if date is empty and this item is not mandatory
                     // also skip
                     if ($value == "" && (!isset($confItem['mandatory']) || !$confItem['mandatory'])) {
                         continue;
                     }
                     if ($confItem['type'] == 'calendar') {
                         $value = preg_replace('/\\s\\s+/', '', $value);
                         if ($this->itemRepository->isValidDate($value)) {
                             //$value = date('d.m.Y',$date);
                         } else {
                             $this->flashMessage('Zadali jste neplatné datum pro položku ' . $confItem['text'] . '!', 'error');
                             throw new Exception('badDateFormat');
                         }
                     }
                 }
                 unset($value);
                 /** edit item in DB */
                 $this->itemRepository->update($this->pageUrl, $this->editingRow->authorHash, $this->pageConfig, $this->getHttpRequest(), $values);
                 // get last edited id
                 $lastId = $this->itemRepository->findByHash($this->editingRow->authorHash)->fetch()->id;
                 // also dont forget for calendar
                 if (isset($this->pageConfig['settings']['calendar'])) {
                     // get from date
                     $dateFrom = date('Y-m-d', strtotime($values[$this->pageConfig['settings']['calendar']['from']]));
                     // get to date
                     if (isset($this->pageConfig['settings']['calendar']['to'])) {
                         // if TO is set
                         $dateTo = date('Y-m-d', strtotime($values[$this->pageConfig['settings']['calendar']['to']]));
                     } else {
                         if (isset($this->pageConfig['settings']['calendar']['duration'])) {
                             // if only duration is known
                             $dateTo = date('Y-m-d', strtotime($values[$this->pageConfig['settings']['calendar']['from']] . ' + ' . $values[$this->pageConfig['settings']['calendar']['duration']] . ' days'));
                         } else {
                             // if TO date is not set
                             $dateTo = NULL;
                         }
                     }
                     $this->calendarRepository->update($lastId, $dateFrom, $dateTo);
                 }
                 /** show message and redirect */
                 if (!$this->noFlashes) {
                     $this->flashMessage($this->pageConfig["texts"]["successEdit"], 'success');
                 }
                 // invalidate cache
                 $cache = \Nette\Environment::getCache('Nette.Templating.Cache');
                 $cache->clean(array(\Nette\Caching\Cache::TAGS => array('items/' . $this->pageUrl)));
                 if (!$this->isAjax()) {
                     //$this->redirect('this');
                 } else {
                     $this->invalidateControl('editUserForm');
                     $this->invalidateControl('editAdminForm');
                     // send the edited ID
                     $this->payload->editSaved = $lastId;
                     //$form->setValues(array(), TRUE);
                 }
             }
         } catch (InvalidStateException $e) {
             $this->flashMessage($this->pageConfig["texts"]["failEdit"], 'error');
             throw $e;
         } catch (Exception $e) {
             if ($e->getMessage() != 'badDateFormat') {
                 throw $e;
             }
         }
     }
 }
Esempio n. 21
0
 /**
  * Returns mimetype of the file
  *
  * @param string $location  Everithing what accepts pathinfo()
  * @return string           Mime type
  */
 public function getMimeType()
 {
     if ($this->vMimeType !== null) {
         return $this->vMimeType;
     }
     $mime = "";
     if (extension_loaded('fileinfo') and function_exists("finfo_open")) {
         //TODO: test this code:
         if ($finfo = @finfo_open(FILEINFO_MIME)) {
             $mime = @finfo_file($finfo, $this->sourceFile);
             @finfo_close($finfo);
             if (FDTools::isValidMimeType($mime)) {
                 return $mime;
             }
         }
     }
     if (function_exists("mime_content_type")) {
         $mime = mime_content_type($this->sourceFile);
         if (FDTools::isValidMimeType($mime)) {
             return $mime;
         }
     }
     // By file extension from ini file
     $cache = Environment::getCache("FileDownloader");
     if (!isset($cache["mime-types"])) {
         $cache["mime-types"] = parse_ini_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . "mime.ini");
     }
     $mimetypes = $cache["mime-types"];
     $extension = pathinfo($this->sourceFile, PATHINFO_EXTENSION);
     if (array_key_exists($extension, $mimetypes)) {
         $mime = $mimetypes[$extension];
     }
     if (FDTools::isValidMimeType($mime)) {
         return $mime;
     } else {
         return "application/octet-stream";
     }
 }
Esempio n. 22
0
 protected function getImageSrc()
 {
     $userAgentStart = substr($_SERVER['HTTP_USER_AGENT'], 0, 32);
     $oldIE = $userAgentStart == "Mozilla/4.0 (compatible; MSIE 6." || $userAgentStart == "Mozilla/4.0 (compatible; MSIE 7.";
     $base64 = 'data:image/png;base64,' . $this->drawImage();
     if ($oldIE) {
         $md5 = md5($base64);
         $cache = Nette\Environment::getCache(\vBuilder\Application\UI\Controls\ImageFixer::CACHE_NS);
         $cache->save($md5, $base64);
         return $this->form->presenter['imageFixer']->link('//getFixedImage!', array('base64' => $md5));
     } else {
         return $base64;
     }
 }
Esempio n. 23
0
 /**
  * @return Nette\Caching\Cache
  */
 protected static function getCache()
 {
     return Environment::getCache('Nette.Template.Cache');
 }
Esempio n. 24
0
 public static function fetchNews($offset = 0, $limit = 10)
 {
     $cache = \Nette\Environment::getCache('stream');
     $cacheName = 'mainStream-' . $offset . $limit;
     if (0 && isset($cache[$cacheName])) {
         return unserialize($cache[$cacheName]);
     } else {
         $res = self::getNews($offset, $limit);
         $cache->save($cacheName, serialize((array) $res), array('expire' => time() + 60 * 10, 'refresh' => TRUE, 'tags' => array('stream', 'news', 'events', 'articles', 'subjects', 'comments')));
         return $res;
     }
 }
Esempio n. 25
0
 /**
  * Get cache
  * @return Cache
  */
 public static function getCache()
 {
     return Environment::getCache(__CLASS__);
 }
Esempio n. 26
0
    public function getShiresToSelect($what = 'name', $zero = false)
    {
        $cache = Environment::getCache('application/system');
        $cacheName = 'shires_to_select-by-' . $what . '-' . $zero;
        if (isset($cache[$cacheName])) {
            return unserialize($cache[$cacheName]);
        } else {
            $res = dibi::query('
	      SELECT [s.id], [s.' . $what . '] as [name]
	      FROM [shire] as [s]
	      ORDER BY [s.' . $what . ']
	      ')->fetchPairs('id', 'name');
            if ($zero) {
                $a = array(0 => '---');
                $res = $a + $res;
            }
            $cache->save($cacheName, serialize((array) $res), array('expire' => time() + 60 * 60 * 30, 'refresh' => TRUE, 'tags' => array('system', 'shires')));
            return $res;
        }
    }
Esempio n. 27
0
 /**
  * @return Nette\Caching\Cache
  */
 protected function getCache()
 {
     return Nette\Environment::getCache('Nette.RobotLoader');
 }
Esempio n. 28
0
 public function handleApproveEventsComment($id)
 {
     Model\EventsComments::approveComment($id);
     $this->flashMessage('Comment Approved.', 'ok');
     $cache = \Nette\Environment::getCache();
     $cache->clean(array('tags' => array('comments', 'events')));
     $this->redirect('this');
 }