public function save(Nette\Application\UI\Form $form) { $flag = $this->context->createServiceFlags(); try { $vars = $form->getValues(); if ($vars['www'] !== '') { $form->addError('Are you a spam robot, right?'); throw new AuthorizationException('Are you a spam robot, right?'); } unset($vars['www']); $flag->flag = $vars; $flag->save(); $cache = new Nette\Caching\Cache($this->context->cacheStorage); $cache->clean(array('flags', 'flag')); $this->flashMessage('Děkujeme! Váš podnět k aktualizaci zpracujeme. Peknyden.cz.', 'success'); $this->hide = true; } catch (AuthorizationException $e) { $this->flashMessage($e->getMessage(), 'error'); } catch (Exception $e) { $this->flashMessage('There is error during saving flag! We know about this. Try it later, please.', 'error'); } if ($this->parent->isAjax()) { $this->redrawControl('form'); } }
public function near($lat, $lon, $distance = 100000) { $key = 'events' . $lat . $lon . $distance; $cache = new Nette\Caching\Cache($this->context->cacheStorage); $ids = $cache->load($key); $ids = NULL; if ($ids === NULL) { /* 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) { throw new DibiException('There is no places', 1); } 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); $cache->save($key, $ids, array(Nette\Caching\Cache::TAGS => array("events", "event", "distance"), Nette\Caching\Cache::EXPIRATION => '4 hours')); } $this->where('subject_id', $ids); return $this; }
/** * @return void */ protected function shutdown($exception) { if ($this->cacheKey) { $content = ob_get_flush(); if ($content) { // byl vůbec nějaký výstup? To je nutné zkontrolovat, co když byl // presenter ukončen třeba metodou lastModified() $cache = new \Nette\Caching\Cache($this->context->cacheStorage, 'htmlFront'); $cache->save($this->cacheKey, $content, array('expire' => 3600, 'tags' => $this->cacheTags)); } } }
public function fileUploadSuccess(AppForm $form) { try { foreach ($form->values->image as $image) { $file = new \File(); $d = $image->getImageSize(); if ($d[0] < 300 && $d[1] < 300) { throw new InvalidArgumentException('Obrázek je příliš malý. Musí mít minimálně jeden rozměr vyšší než 300px. Nahrajte prosím větší obrázek.'); } if ($d[0] > 3000 || $d[1] > 3000) { throw new InvalidArgumentException('Obrázek je až zbytečně veliký. Žádný rozměr by neměl být vyšší než 3000px. Nahrajte prosím menší obrázek.'); } $file->file_prefix = ""; $file->file_sufix = "_u" . $this->context->user->id . "_" . substr(sha1(time()), 0, 4); $file->user_id = $this->context->user->id; $file->insertUploaded($image, FILESTORAGE_DIR); $file->visible = 1; // automaticka publikace $file->save(); if ($form->values->type == "event") { dibi::query('INSERT INTO event_x_file', array('event_id' => $form->values->id, 'file_id' => $file->id)); $res = dibi::select('*')->from('event_x_file')->where('first', '=', 1)->where('event_id', '=', $form->values->id); if (count($res) == 0) { $res = dibi::select('*')->from('event_x_file')->where('event_id', '=', $form->values->id)->fetch(); dibi::query('UPDATE event_x_file SET ', array('first' => 1), 'WHERE event_id = ', $res->event_id, 'AND file_id =', $res->file_id); } } elseif ($form->values->type == "place") { dibi::query('INSERT INTO subject_x_file', array('subject_id' => $form->values->id, 'file_id' => $file->id)); $res = dibi::select('*')->from('subject_x_file')->where('first', '=', 1)->where('subject_id', '=', $form->values->id); if (count($res) == 0) { $res = dibi::select('*')->from('subject_x_file')->where('subject_id', '=', $form->values->id)->fetch(); dibi::query('UPDATE subject_x_file SET ', array('first' => 1), 'WHERE subject_id = ', $res->subject_id, 'AND file_id =', $res->file_id); } } } } catch (Exception $e) { $form->addError($e->getMessage()); } if ($form->isSuccess()) { $cache = new \Nette\Caching\Cache($this->context->cacheStorage); $cache->clean(array('files', 'images', 'file', 'image', $form->values->type, $form->values->type . 's')); $this->presenter->flashMessage('Dobrá zpráva, fotografie se podařilo vložit!', 'success'); $this->redirect('this'); } }
/** * Returns "generated" data. * NOTE: This location is only for demo! * @return array */ private function getData($cacheKey = 'data') { $storage = new \Nette\Caching\Storages\FileStorage($this->context->parameters['tempDir']); $cache = new \Nette\Caching\Cache($storage, 'example_data'); $data = $cache->load($cacheKey); if (empty($data)) { $data = array(array('id' => 1, 'firstname' => 'Eva', 'surname' => 'Malá'), array('id' => 2, 'firstname' => 'Adéla', 'surname' => 'Střední'), array('id' => 3, 'firstname' => 'Jana', 'surname' => 'Absolonová'), array('id' => 4, 'firstname' => 'Lucie', 'surname' => 'Šikovná'), array('id' => 5, 'firstname' => 'Andrea', 'surname' => 'Potřebná'), array('id' => 6, 'firstname' => 'Michala', 'surname' => 'Zadní'), array('id' => 7, 'firstname' => 'Markéta', 'surname' => 'Mladá'), array('id' => 8, 'firstname' => 'Lenka', 'surname' => 'Přední'), array('id' => 9, 'firstname' => 'Marie', 'surname' => 'Dolní'), array('id' => 10, 'firstname' => 'Hanka', 'surname' => 'Horní'), array('id' => 11, 'firstname' => 'Petra', 'surname' => 'Vysoká')); $limit = array(1, 9); foreach ($data as &$item) { $d = rand($limit[0], $limit[1]); $h = rand($limit[0], $limit[1]); $m = rand($limit[0], $limit[1]); $s = rand($limit[0], $limit[1]); $item['last_login'] = $item['id'] == 4 ? NULL : new \Nette\DateTime("NOW - {$d}day {$h}hour {$m}minute {$s}second"); $item['allowance'] = rand(10000, 100000) / 10; $item['ok'] = (bool) rand(0, 1); } $cache->save($cacheKey, $data, array(\Nette\Caching\Cache::EXPIRE => '+ 60 minutes')); } return $data; }
/** * Returns annotations. * @param \ReflectionClass|\ReflectionMethod|\ReflectionProperty * @return array */ public static function getAll(\Reflector $r) { if ($r instanceof ReflectionClass) { $type = $r->getName(); $member = 'class'; } elseif ($r instanceof ReflectionMethod) { $type = $r->getDeclaringClass()->getName(); $member = $r->getName(); } else { $type = $r->getDeclaringClass()->getName(); $member = '$' . $r->getName(); } if (!self::$useReflection) { // auto-expire cache $file = $r instanceof ReflectionClass ? $r->getFileName() : $r->getDeclaringClass()->getFileName(); // will be used later if ($file && isset(self::$timestamps[$file]) && self::$timestamps[$file] !== filemtime($file)) { unset(self::$cache[$type]); } unset(self::$timestamps[$file]); } if (isset(self::$cache[$type][$member])) { // is value cached? return self::$cache[$type][$member]; } if (self::$useReflection === NULL) { // detects whether is reflection available self::$useReflection = (bool) XApp_Reflection_ClassType::from(__CLASS__)->getDocComment(); } if (self::$useReflection) { $annotations = self::parseComment($r->getDocComment()); } else { if (!self::$cacheStorage) { // trigger_error('Set a cache storage for annotations parser via Nette\Reflection\AnnotationParser::setCacheStorage().', E_USER_WARNING); self::$cacheStorage = new Nette\Caching\Storages\DevNullStorage(); } $outerCache = new Nette\Caching\Cache(self::$cacheStorage, 'Nette.Reflection.Annotations'); if (self::$cache === NULL) { self::$cache = (array) $outerCache->load('list'); self::$timestamps = isset(self::$cache['*']) ? self::$cache['*'] : array(); } if (!isset(self::$cache[$type]) && $file) { self::$cache['*'][$file] = filemtime($file); foreach (self::parsePhp(file_get_contents($file)) as $class => $info) { foreach ($info as $prop => $comment) { if ($prop !== 'use') { self::$cache[$class][$prop] = self::parseComment($comment); } } } $outerCache->save('list', self::$cache); } if (isset(self::$cache[$type][$member])) { $annotations = self::$cache[$type][$member]; } else { $annotations = array(); } } if ($r instanceof \ReflectionMethod && !$r->isPrivate() && (!$r->isConstructor() || !empty($annotations['inheritdoc'][0]))) { try { $inherited = self::getAll(new \ReflectionMethod(get_parent_class($type), $member)); } catch (\ReflectionException $e) { try { $inherited = self::getAll($r->getPrototype()); } catch (\ReflectionException $e) { $inherited = array(); } } $annotations += array_intersect_key($inherited, array_flip(self::$inherited)); } return self::$cache[$type][$member] = $annotations; }
public function renderDefault() { $httpRequest = $this->context->getService('httpRequest'); $this->template->hash = $hash = $httpRequest->getUrl()->path; $cache = new \Nette\Caching\Cache($this->context->getService('cacheStorage')); $key = $hash . "count"; dump($key); $count = $cache->load($key); if ($count === NULL) { $count = $this->context->createServiceTimes()->fetchPublic()->group('event_time.event_id')->count(); $cache->save($key, $count, array(\Nette\Caching\Cache::EXPIRE => '2 hours', \Nette\Caching\Cache::TAGS => array('events', 'event'), \Nette\Caching\Cache::SLIDING => TRUE)); } $this->template->eventsCount = $count; $this->template->events = $this->items; $this->template->page = $this->page; // omezeni na lokalitu $this->template->locality = false; if ($this->locality) { $this->items->where('event_time.event.subject.locality.code', $this->locality); $this->template->locality = true; } // omezeni na kraje if ($this->shire) { $this->items->where('(event_time.event.shire.code = "' . $this->shire . '") OR (event_time.event.shire_id = 99)'); } // omezeni na kategorie if ($this->category || count($this->categories) > 0) { $this->items->where('event_time.event:event_x_category.category_id', array_keys($this->categories)); if (count($this->categories) == 1) { $this->template->category = $this->context->createServiceCategories()->get(key($this->categories)); } else { $this->template->categories = $this->context->createServiceCategories(); } } else { //$this['categories']['category']['all']->setValue(1); } // nastavi casovy ramec if ($this->timeframe) { $this->items->setTimeframe($this->timeframe); $this->template->timeframe = $this->timeframe; } $this->template->dates = array(); for ($i = 2; $i < 13; $i++) { $ts = time() + $i * 86400; if (strftime("%u", $ts) == 6 || strftime("%u", $ts) == 7) { $this->template->dates[date("Y-m-d", $ts)]['time'] = strftime("%a %e. %m.", $ts); $this->template->dates[date("Y-m-d", $ts)]['day'] = 'weekend'; //$this->template->dates[date("Y-m-d", $ts)] = strftime("%A", $ts); } else { $this->template->dates[date("Y-m-d", $ts)]['time'] = strftime("%a %e. %m.", $ts); $this->template->dates[date("Y-m-d", $ts)]['day'] = 'weekday'; } } // pocet polozek s omezenimi $key = $hash . $this->timeframe . "/page-" . $this->pagerPlaces->getPage() . "/" . serialize($this->categories); $this->template->pagingHash = $key; dump($key); $count = $cache->load($key); if ($count === NULL) { $count = $this->items->count(); $cache->save($key, $count, array(\Nette\Caching\Cache::EXPIRE => '2 hours', \Nette\Caching\Cache::TAGS => array('events', 'event'), \Nette\Caching\Cache::SLIDING => TRUE)); } $this->template->count = $count; if ($this->page * $this->limit > $count - $this->limit) { //zkontroluje, zda se jedna o posledni stranku vypisu $this->limit = 9999; // nastavi limi na hodne velky cislo, aby se vypsalo vse zbyvajici $this->template->limit = $this->limit; } elseif (($this->page + 1) * $this->limit > $count - $this->limit) { // zkontroluje, zda se jedna o predposledni stranku vypisu $this->template->limit = 9998; } else { $this->template->limit = $this->limit; } //nastavi razeni if ($this->order == "created DESC") { $this->items->order($this->order); } else { // ostatni razeni se resi v modelu dle timeframe } // strankovani $this->pagerPlaces->itemsPerPage = $this->limit; $this->pagerPlaces->itemCount = $count; if ($this->pagerPlaces->getOffset() == 9999 && $this->pagerPlaces->getPage() > 1) { $this->redirect('this', array('pagingPlaces-page' => 1)); } if ($this->isAjax()) { $this->template->newEntry = $this->items->limit($this->pagerPlaces->getLimit(), $this->pagerPlaces->getOffset()); } else { $this->template->events = $this->items->limit($this->pagerPlaces->getLimit(), $this->pagerPlaces->getOffset()); } }
/** * @param \Nette\DI\Container $dic * @throws \Kdyby\Autowired\MemberAccessException * @internal */ public function injectComponentFactories(\Nette\DI\Container $dic) { if (!$this instanceof \Nette\Application\UI\PresenterComponent) { throw new \Kdyby\Autowired\MemberAccessException('Trait ' . __TRAIT__ . ' can be used only in descendants of PresenterComponent.'); } $this->autowireComponentFactoriesLocator = $dic; $cache = new \Nette\Caching\Cache($dic->getByType('Nette\\Caching\\IStorage'), 'Kdyby.Autowired.AutowireComponentFactories'); if ($cache->load($presenterClass = get_class($this)) !== NULL) { return; } $rc = $this->getReflection(); $ignore = class_parents('Nette\\Application\\UI\\Presenter') + array('ui' => 'Nette\\Application\\UI\\Presenter'); foreach ($rc->getMethods() as $method) { /** @var Property $prop */ if (in_array($method->getDeclaringClass()->getName(), $ignore) || !Strings::startsWith($method->getName(), 'createComponent')) { continue; } foreach ($method->getParameters() as $parameter) { if (!($class = $parameter->getClassName())) { // has object type hint continue; } if (!$this->findByTypeForFactory($class) && !$parameter->allowsNull()) { throw new \Kdyby\Autowired\MissingServiceException("No service of type {$class} found. Make sure the type hint in {$method} is written correctly and service of this type is registered."); } } } $files = array_map(function ($class) { return \Nette\Reflection\ClassType::from($class)->getFileName(); }, array_diff(array_values(class_parents($presenterClass) + array('me' => $presenterClass)), $ignore)); $files[] = \Nette\Reflection\ClassType::from($this->autowireComponentFactoriesLocator)->getFileName(); $cache->save($presenterClass, TRUE, array($cache::FILES => $files)); }