Exemplo n.º 1
0
 public function createComponent($name)
 {
     switch ($name) {
         case 'searchForm':
             $form = new AppForm($this, $name);
             $form->addText('q', __('Query:'));
             $form['q']->getControlPrototype()->onclick('if (this.value === "' . __('Input search keywords') . '") {
                     this._default = this.value;
                     this.value = "";
                 }');
             $form['q']->getControlPrototype()->onblur('if (this.value === "" && this._default !== undefined) {
                     this.value = this._default;
                 }');
             $form->setAction($this->link('Search:default'));
             $form->setMethod('get');
             if (isset(Environment::getSession(SESSION_SEARCH_NS)->last)) {
                 $form->setDefaults(array('q' => Environment::getSession(SESSION_SEARCH_NS)->last));
             } else {
                 $form->setDefaults(array('q' => __('Input search keywords')));
             }
             break;
         default:
             return parent::createComponent($name);
     }
 }
Exemplo n.º 2
0
 public static function increaseRead($id)
 {
     $reader = Environment::getSession('reader');
     if ($reader[$id] == NULL) {
         dibi::query('UPDATE [works] SET [read] = [read] + 1 WHERE workId=%i', $id);
         $reader[$id] = TRUE;
     }
 }
Exemplo n.º 3
0
 public function __construct($parent = NULL, $name = NULL)
 {
     parent::__construct($parent, $name);
     $this->form = new AppForm($this, 'form');
     $this->form->addSubmit('yes', _('Yes'))->onClick[] = array($this, 'confirmClicked');
     $this->form->addSubmit('no', _('No'))->onClick[] = array($this, 'cancelClicked');
     $this->form->addHidden('token');
     $this->question = Html::el('p');
     $this->session = Environment::getSession('ConfirmationDialog/tokens');
 }
Exemplo n.º 4
0
 public function handleSubmit($form)
 {
     $values = $form->getValues();
     $query = $values['query'];
     $data = $this->presenter->model('search')->search($query);
     $session = Environment::getSession('search');
     $session->query = $query;
     $session->search_result = $data;
     $this->getPresenter()->redirect('Search:search', array('query' => $query));
 }
Exemplo n.º 5
0
 /**
  * Gets the service object of the specified type.
  * @param  string service name
  * @param  array  options in case service is not singleton
  * @return mixed
  */
 public static function getService($name, array $options = NULL)
 {
     if (!is_string($name) || $name === '') {
         throw new InvalidArgumentException("Service name must be a non-empty string, " . gettype($name) . " given.");
     }
     $session = Environment::getSession('MokujiServiceLocator');
     $lower = strtolower($name);
     if (isset($session->{$lower})) {
         // instantiated singleton
         if ($options) {
             throw new InvalidArgumentException("Service named '{$name}' is singleton and therefore can not have options.");
         }
         return $session->{$lower};
     } elseif (isset($session->factories[$lower])) {
         list($factory, $singleton, $defOptions) = $session->factories[$lower];
         if ($singleton && $options) {
             throw new InvalidArgumentException("Service named '{$name}' is singleton and therefore can not have options.");
         } elseif ($defOptions) {
             $options = $options ? $options + $defOptions : $defOptions;
         }
         if (is_string($factory) && strpos($factory, ':') === FALSE) {
             // class name
             Framework::fixNamespace($factory);
             if (!class_exists($factory)) {
                 throw new AmbiguousServiceException("Cannot instantiate service '{$name}', class '{$factory}' not found.");
             }
             $service = new $factory();
             if ($options && method_exists($service, 'setOptions')) {
                 $service->setOptions($options);
                 // TODO: better!
             }
         } else {
             // factory callback
             $factory = callback($factory);
             if (!$factory->isCallable()) {
                 throw new InvalidStateException("Cannot instantiate service '{$name}', handler '{$factory}' is not callable.");
             }
             $service = $factory->invoke($options);
             if (!is_object($service)) {
                 throw new AmbiguousServiceException("Cannot instantiate service '{$name}', value returned by '{$factory}' is not object.");
             }
         }
         if ($singleton) {
             $session->{$lower} = $service;
             unset($session->factories[$lower]);
         }
         return $service;
     }
     if ($this->parent !== NULL) {
         return $this->parent->getService($name, $options);
     } else {
         throw new InvalidStateException("Service '{$name}' not found.");
     }
 }
Exemplo n.º 6
0
 public function actionSearch($query)
 {
     $session = Environment::getSession('search');
     if ($session->query != $query) {
         $data = $this->model('search')->search($query);
     } else {
         $data = $session->search_result;
     }
     $this->template->query = $query;
     $this->template->data = $data;
     $this->view = 'results';
 }
Exemplo n.º 7
0
 public function createComponentTree()
 {
     $tree = new TreeView();
     $tree->useAjax = true;
     $mode = null === $this->mode ? 1 : $this->mode;
     $session = Environment::getSession();
     $tree->mode = $mode;
     $tree->rememberState = true;
     $tree->addLink('default', 'name', 'id', true, $this->presenter);
     $tree->dataSource = SitemapModel::findAll();
     //$tree->enableSorting(array($this, 'move'));
     //$tree->renderer->wrappers['link']['collapse'] = null;
     //$tree->renderer->wrappers['link']['expand'] = null;
     //$tree->renderer->wrappers['node']['icon'] = null;
     $tree->renderer->wrappers['link']['collapse'] = 'a class="ui-icon ui-icon-circlesmall-minus" style="float: left"';
     $tree->renderer->wrappers['link']['expand'] = 'a class="ui-icon ui-icon-circlesmall-plus" style="float: left"';
     $tree->renderer->wrappers['node']['icon'] = 'span class="ui-icon ui-icon-document" style="float: left"';
     return $tree;
 }
Exemplo n.º 8
0
 public function renderDefault($q, $page = 1)
 {
     try {
         $ids = array();
         foreach (fulltext::index()->find($q) as $hit) {
             $ids[] = $hit->getDocument()->id;
         }
         $this->template->paginator = new Paginator();
         $this->template->paginator->setItemCount(count($ids));
         $this->template->paginator->setItemsPerPage(Environment::getVariable('itemsPerPage', 30));
         $this->template->paginator->setPage($page);
         $this->template->products = mapper::products()->findByIds(array_slice($ids, $this->template->paginator->getOffset(), $this->template->paginator->getLength()));
         $this->template->title = __('Search results for ``%s"', $q);
         $this->template->q = $q;
         Environment::getSession(SESSION_SEARCH_NS)->last = $q;
         searchlog::log($q);
     } catch (Exception $e) {
         $this->template->products = array();
     }
 }
Exemplo n.º 9
0
 public function renderProduct()
 {
     // recent products
     if (!isset(Environment::getSession(SESSION_RECENTPRODUCTS_NS)->recent)) {
         Environment::getSession(SESSION_RECENTPRODUCTS_NS)->recent = array();
     }
     array_unshift(Environment::getSession(SESSION_RECENTPRODUCTS_NS)->recent, $this->template->product);
     $already_in = array();
     foreach (Environment::getSession(SESSION_RECENTPRODUCTS_NS)->recent as &$_) {
         $id = $_->getId();
         if (isset($already_in[$id])) {
             $_ = FALSE;
         }
         $already_in[$id] = TRUE;
     }
     Environment::getSession(SESSION_RECENTPRODUCTS_NS)->recent = array_slice(array_filter(Environment::getSession(SESSION_RECENTPRODUCTS_NS)->recent), 0, 5);
     // visited products
     array_push(Environment::getSession(SESSION_ORDER_NS)->visited, array($this->template->product, time()));
     // fill template
     $this->template->nav = mapper::categories()->findForNavByProductId($this->template->product->getId());
 }
Exemplo n.º 10
0
 public function editFormSubmitted($form)
 {
     $func = 'save';
     switch ($form->name) {
         case 'studentsEditForm':
             $model = 'students';
             break;
         case 'teachersEditForm':
             $model = 'teachers';
             break;
         case 'coursesEditForm':
             $model = 'courses';
             break;
         case 'roomsEditForm':
             $model = 'school';
             $func = 'saveNewRoom';
             break;
         case 'departmentsEditForm':
             $model = 'school';
             $func = 'saveNewDepartment';
             break;
         case 'learning_timesEditForm':
             $model = 'school';
             $func = 'saveNewLearningTime';
             break;
     }
     $values = $form->getValues();
     $this->model($model)->{$func}($values);
     $namespace = Environment::getSession()->getNamespace('table');
     $table = $namespace->table;
     unset($namespace->table);
     $this->redirect('default', array('table' => $table));
 }
Exemplo n.º 11
0
 /**
  * Data form
  * @param string
  */
 public function onDataFormSubmit(Form $form)
 {
     // check for validity
     if (!$form->isValid()) {
         return;
     }
     // get data
     $order = Environment::getSession(SESSION_ORDER_NS);
     $order->data = $form->getValues();
     if ($order->data['same_delivery']) {
         foreach ($order->data as $k => $v) {
             if (strncmp($k, 'payer_', strlen('payer_')) === 0) {
                 $order->data['delivery_' . substr($k, strlen('payer_'))] = $v;
             }
         }
     }
     $this->redirect('complete');
 }
Exemplo n.º 12
0
<?php

/**
 * Nette TreeView example bootstrap file.
 *
 * @copyright  Copyright (c) 2010 Roman Novák
 * @package    nette-treeview
 */
// Step 1: Load Nette Framework
// this allows load Nette Framework classes automatically so that
// you don't have to litter your code with 'require' statements
require LIBS_DIR . '/Nette/loader.php';
// Step 2: Configure environment
// 2a) enable Nette\Debug for better exception and error visualisation
Debug::enable(false);
Debug::enableProfiler();
// 2b) load configuration from config.ini file
Environment::loadConfig();
Environment::getSession()->start();
dibi::connect(Environment::getConfig('database'));
// Step 3: Configure application
// 3a) get and setup a front controller
$application = Environment::getApplication();
//$application->errorPresenter = 'Error';
$application->catchExceptions = false;
// Step 4: Setup application router
$router = $application->getRouter();
$router[] = new Route('index.php', array('presenter' => 'Homepage', 'action' => 'default'), Route::ONE_WAY);
$router[] = new Route('<presenter>/<action>/<id>', array('presenter' => 'Homepage', 'action' => 'default', 'id' => NULL));
// Step 5: Run the application!
$application->run();
Exemplo n.º 13
0
//Environment::setMode(Environment::DEVELOPMENT, false);
// 2b) load configuration from config.ini file
//require LIBS_DIR . '/Custom/MultipleConfigurator.php';
//Environment::setConfigurator(new MultipleConfigurator());
//$config = Environment::loadConfig();
// 2c) check if cache, sessions and log directories are writable
if (@file_put_contents(Environment::expand('%tempDir%/_check'), '') === FALSE) {
    throw new Exception("Make directory '" . Environment::getVariable('tempDir') . "' writable!");
}
if (@file_put_contents(Environment::expand('%sessionDir%/_check'), '') === FALSE) {
    throw new Exception("Make directory '" . Environment::getVariable('sessionDir') . "' writable!");
}
if (@file_put_contents(Environment::expand('%logDir%/_check'), '') === FALSE) {
    throw new Exception("Make directory '" . Environment::getVariable('logDir') . "' writable!");
}
$session = Environment::getSession();
$session->setSavePath(Environment::getVariable('sessionDir'));
//Environment::getHttpResponse()->cookiePath = '/'; // toto tu treba, aby fungovali cookie..v novsej verzii je to uz fixnute
$session->setExpiration($config['session']['lifetime']);
if (!$session->isStarted()) {
    $session->start();
}
/**
 * create new httpRequest for CLI
 * @see http://wiki.nette.org/cs/cookbook/http-routovani-v-cli
 */
if (Environment::isConsole()) {
    function createHttpRequestService()
    {
        $config = Environment::getConfig('httpRequest');
        // params can be taken from config or command line if needed
Exemplo n.º 14
0
 /**
  * @return Session
  */
 protected function getSession($namespace = NULL)
 {
     return Environment::getSession($namespace);
 }
Exemplo n.º 15
0
 protected function getNodeSession()
 {
     return Environment::getSession()->getNamespace('Nette.Extras.TreeView/' . $this->getTreeView()->getName() . '/' . $this->getName());
 }
Exemplo n.º 16
0
 /**
  * Creates secure hash from array of arguments.
  * @param array $param
  * @return string
  */
 protected function createSecureHash($params)
 {
     $ns = Environment::getSession('securedlinks');
     if ($ns->key === NULL) {
         $ns->key = uniqid();
     }
     $s = implode('|', array_keys($params)) . '|' . implode('|', array_values($params)) . $ns->key;
     return substr(md5($s), 4, 8);
 }
Exemplo n.º 17
0
 public function handleAddWork($id)
 {
     $s = Environment::getSession('workform');
     $s->author = $id;
     $this->redirect(':Admin:Editor:work');
 }
 /**
  * Handles an incomuing request and saves the data if necessary.
  */
 public function processRequest()
 {
     // Try starting the session
     try {
         $session = Environment::getSession('Nette.Addons.TranslationPanel');
     } catch (InvalidStateException $e) {
         $session = FALSE;
     }
     $request = Environment::getHttpRequest();
     if ($request->isPost() && $request->isAjax() && $request->getHeader('X-Translation-Client')) {
         $data = json_decode(file_get_contents('php://input'));
         if ($data) {
             if ($session) {
                 $stack = isset($session['stack']) ? $session['stack'] : array();
             }
             foreach ($data as $string => $value) {
                 $this->translator->setTranslation($string, $value);
                 if ($session && isset($stack[$string])) {
                     unset($stack[$string]);
                 }
             }
             $this->translator->save();
             if ($session) {
                 $session['stack'] = $stack;
             }
         }
     }
 }
Exemplo n.º 19
0
 public function FormAddTermSubmitted(Button $button)
 {
     $values = $button->getForm()->getValues();
     $start_datetime = $values['start_date'] . ' ' . $values['start_date_time'];
     unset($values['start_date']);
     unset($values['start_date_time']);
     $values['start_datetime'] = $start_datetime;
     $application_deadline = $values['deadline_date'] . ' ' . $values['deadline_date_time'];
     unset($values['deadline_date']);
     unset($values['deadline_date_time']);
     $values['application_deadline'] = $application_deadline;
     $teacher_id = $this->getUser()->getId();
     $values['teacher_id'] = (int) $teacher_id;
     $values['min_seminar_points'] = (int) $values['min_seminar_points'];
     try {
         $session = Environment::getSession('exam_terms_edit_form_' . $values['id']);
         if (isset($session['form_data'])) {
             ExamManager::update($values);
             $this->flashMessage('Term updated', 'success');
         } else {
             ExamManager::add($values);
             unset($session['form_data']);
             $this->flashMessage('Term added', 'success');
         }
         $this->template->show_popup = false;
         $this->invalidateControl('popup');
         $this->invalidateControl('flash');
         /*if(!$this->isAjax())*/
         $this->redirect('this');
     } catch (DibiException $e) {
         $this->flashMessage($e->getMessage(), 'error');
         $this->invalidateControl('popup_flash');
     }
 }
Exemplo n.º 20
0
 /**
  * Cross-Site Request Forgery (CSRF) form protection.
  * @param  string
  * @param  int
  * @return void
  */
 public function addProtection($message = NULL, $timeout = NULL)
 {
     $session = Environment::getSession(__METHOD__);
     $key = "key{$timeout}";
     if (isset($session->{$key})) {
         $token = $session->{$key};
     } else {
         $session->{$key} = $token = md5(uniqid('', TRUE));
     }
     $session->setExpiration($timeout, $key);
     $this[self::PROTECTOR_ID] = new HiddenField($token);
     $this[self::PROTECTOR_ID]->addRule(':equal', empty($message) ? 'Security token did not match. Possible CSRF attack.' : $message, $token);
 }
Exemplo n.º 21
0
 protected function createComponentForm($name)
 {
     $form = new AppForm();
     //$form->getElementPrototype()->id('editform');
     $form->addText('title', 'Název', 50)->addRule(Form::FILLED, "Jméno je potřeba vyplnit");
     $items = dibi::query('SELECT
     authorId,
     CONCAT_WS(" ", name, surname,', Model::sqlClassName(Model::getSchoolYear()), ') as authorName
     FROM [authors]
     ORDER BY surname, class desc')->fetchPairs();
     $keys = array_keys($items);
     $form->addSelect('author', 'Autor', array("0" => 'Nový') + $items)->setValue($keys[0]);
     $form->addTextArea('text', 'Text')->getControlPrototype()->style = 'width: 100%';
     $form->addSelect('award', 'Ocenění', array("0" => 'Nové') + $this->setKeys(Model::getValues('award', 'works')));
     $form->addText('newAward', '');
     $form->addSelect('year', 'Ročník ChP', $this->generateYears())->setDefaultValue(Model::getSchoolYear());
     $form->addSelect('type', 'Typ', array("0" => 'Nový') + $this->setKeys(Model::getValues('type', 'works')));
     $form->addText('newType', '');
     if ($this->setId == '') {
         $form->addFile('file', "Soubor:");
     }
     $form['newAward']->addConditionOn($form['award'], Form::EQUAL, 0)->addRule(Form::FILLED, 'Pokud nevyberete ocenění, musíte zadat nové');
     $form['newType']->addConditionOn($form['type'], Form::EQUAL, 0)->addRule(Form::FILLED, 'Pokud nevyberete typ, musíte zadat nový');
     $form->addSubmit('ok', 'Přidat práci')->onClick[] = array($this, 'addClicked');
     $form->addHidden("authorId")->setValue('false');
     if ($this->setId != '') {
         $dataSource = dibi::query('SELECT * FROM [works] WHERE workId=%i', $this->setId)->fetch();
         $form->setDefaults($dataSource);
         $form['ok']->onClick = array(array($this, 'saveClicked'));
         $form['ok']->caption = "Uložit práci";
         $form->addHidden("workId")->setValue($this->setId);
     } else {
         $s = Environment::getSession('workform');
         if (isset($s->author) && array_search($s->author, $keys) === FALSE) {
             $s->author = $keys[0];
         }
         if (isset($s->author)) {
             $form->setDefaults($s);
         }
     }
     $this->addComponent($form, $name);
     $form->getRenderer()->wrappers['control']['container'] .= ' class="wide"';
     return;
 }
Exemplo n.º 22
0
 /**
  * @return Session
  */
 protected function getSession()
 {
     return Environment::getSession();
 }
Exemplo n.º 23
0
 public function formEditSubmitted(Button $button)
 {
     $session = Environment::getSession('params')->remove();
     $form = $button->getForm();
     if ($form->isValid()) {
         $values = $form->getValues();
         unset($values['btnClose']);
         try {
             $this->model('pages')->update($values);
             $this->flash('Page updated');
             if (!$this->isAjax()) {
                 $this->redirect('Pages:');
             } else {
                 $this->invalidateControl('form');
                 $this->invalidateControl('grid');
             }
         } catch (DibiDriverException $e) {
             $this->flash($e->getMessage());
         }
     }
 }
Exemplo n.º 24
0
 /**
  * @return Sesssion
  */
 private function getSession()
 {
     return Environment::getSession();
 }
Exemplo n.º 25
0
 public function handleEditPermissions($id)
 {
     Environment::getSession('group_id')->value = $id;
     $this->template->edit = true;
     $this->invalidateControl('form');
 }