Пример #1
0
 private function _prepare()
 {
     db::connect();
     dibi::addSubst('table', 'students');
     dibi::addSubst('courses_students', 'courses_students');
     dibi::addSubst('courses', 'courses');
 }
Пример #2
0
 public function renderDefault($url)
 {
     $res = dibi::query('
   SELECT
         workId,
         url as file,
         title,
         text,', Model::sqlCategory() . ' as category,
         authorUrl,
         CONCAT_WS(" ", name, surname) as authorName,
         year,', Model::sqlWorkClassName() . 'as workClass,', 'award,
         type, 
         pages,
         words,
         characters,
         [read],
         added,
         edited             
         FROM [works] 
         join [authors] on author = authorId
         WHERE `url`=%s', $url)->fetchAll();
     //$res[0]['award'] = ($res[0]['award'] != 99) ? $res[0]['award'] . ". místo" : "nominaci";
     //2010-08-19 22:43:25
     $res[0]['added'] = preg_replace('/(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})/', '$3.$2.$1 $4:$5', $res[0]['added']);
     $res[0]['edited'] = preg_replace('/(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})/', '$3.$2.$1 $4:$5', $res[0]['edited']);
     $this->template->data = $res[0];
     $this->template->files = FileModel::getFiles($res[0]['workId']);
     Model::increaseRead($res[0]['workId']);
 }
Пример #3
0
 /**
  * Nacte data.
  *
  * @return Bobr_Page_Page
  * @throws Bobr_Page_PageIAException Pokud neni vyplnena vlastnosti id.
  * @throws Bobr_Page_PageException Pokud nenajde zadne data.
  */
 public function load()
 {
     if (0 > $this->id) {
         throw new Bobr_Page_PageIAException('Neni zadano pageId ktere se ma nacist.');
     }
     if (!$this->loadFromCache()) {
         $query = 'SELECT `container_id`, `block_id`, `weight`
             FROM `' . Config::DB_PREFIX . 'pageid_container_block`
             WHERE `pageid_id` = ' . $this->id . ' ORDER BY `container_id`, `weight`';
         $data = dibi::query($query)->fetchAssoc('container_id,block_id');
         if (empty($data)) {
             throw new Bobr_Page_PageException('Zadana stranka nema zadne data.');
         }
         // Naimportujem data.
         $this->importRecord($data);
         try {
             $this->setPageId(new Bobr_Page_PageId($this->id));
         } catch (Bobr_Page_PageIdException $e) {
             // Nelze nacist PageId nelze sestavit Page.
             throw new Bobr_Page_PageException($e->getMessage());
         }
         // Ulozime Page do cache.
         $this->saveToCache();
     }
     return $this;
 }
Пример #4
0
 /**
  *
  */
 public function indexAction()
 {
     die('todo');
     $overwrite = !is_null(Core_Request::getInstance()->getArgv(4)) ? Core_Request::getInstance()->getArgv(4) : false;
     foreach (dibi::getDatabaseInfo()->getTables() as $table_data) {
         if ($table_data->getName() == Migration_MigrationModel::getTableName()) {
             continue;
         }
         $ddl_data = dibi::query('SHOW CREATE TABLE ' . $table_data->getName())->fetch()->toArray();
         $ddl_query = $ddl_data['Create Table'];
         $migration_time = time();
         $migration_name = 'Create' . ucfirst($table_data->getName());
         $migration_name = str_replace(' ', '', $migration_name);
         $migration_name = str_replace('-', '', $migration_name);
         $migration_name = str_replace('_', '', $migration_name);
         $filename = cfg()->migration_path . $migration_name . '.php';
         if (Core_Files::fileSize($filename) && !$overwrite) {
             echo PHP_EOL . 'Migration "Create ' . ucfirst($table_data->getName()) . '" Exists' . PHP_EOL;
             continue;
         }
         $template_data = Core_Files::getContent(cfg()->migration_path . Migration_FilesHelper::TEMPLATE_FILE_NAME);
         $template_data = str_replace('Template', $migration_name, $template_data);
         $template_data = str_replace('__NAME__', $migration_name, $template_data);
         $template_data = str_replace('__CREATED_AT__', $migration_time, $template_data);
         $template_data = str_replace('__CREATED_CFG__', Core_Request::getInstance()->getArgv(1), $template_data);
         $template_data = preg_replace('#//__UP_ACTION__#', $ddl_query, $template_data);
         $down_query = 'DROP TABLE IF EXISTS `' . $table_data->getName() . '`';
         $template_data = preg_replace('#//__DOWN_ACTION__#', $down_query, $template_data);
         Core_Files::putContent($filename, $template_data);
         echo PHP_EOL . 'Migration ' . $filename . ' created' . PHP_EOL;
     }
 }
Пример #5
0
 /**
  * Spoji se z databzi.
  *
  * @return Bobr_Bobr
  * @throws DibiDriverException
  */
 private function connectToDatabase()
 {
     // @todo odchytavat vyjimku pri nepovedenem spojeni.
     $config = new Config();
     $connect = dibi::connect(array('driver' => 'postgre', 'string' => ' host=' . $config->dbHost . ' port=' . $config->dbPort . ' dbname=' . $config->dbName . ' user='******' password='******'', 'persistent' => $config->dbPersistent), $config->dbConnectionName);
     return $this;
 }
Пример #6
0
 function __construct()
 {
     //-----vytvorenie objektu menu
     $menu = new MenuItem();
     $menu->menuAction();
     //-----vytvorenie objektu node
     $node = new node();
     $node->nodeAction();
     MT::addContent($menu->render(), 'leftHolder');
     try {
         if (isset($_GET['id_menu_item']) or isset($_GET['addMenuItem']) or isset($_GET['changeMenuItem'])) {
             MT::addTemplate(APP_DIR . '/templates/admin/modulHolder.phtml', 'modulHolder');
             MT::addVar('modulHolder', 'type_modul', dibi::fetchAll("SELECT * FROM [type_modul] WHERE visible_for_user='******'"));
         }
         //zobrazenie zmeny polozky pre menu
         if (isset($_GET['changeMenuItem'])) {
             $menu->showChangeMenuItem($_GET['id_menu_item']);
         }
         if (isset($_GET['id_menu_item']) and !isset($_GET['changeMenuItem'])) {
             $node->showModul();
         }
         //pridanie polozky do menu
         if (isset($_GET['addMenuItem'])) {
             $menu->showAddMenuItem();
         }
         //zachytenie vynimie
     } catch (NodeException $e) {
         echo '<div style="border: 2px solid red; padding: 5px;">' . $e->getMessage() . '</div>';
         exit;
     }
 }
Пример #7
0
 /**
  * Maps HTTP request to a PresenterRequest object.
  * @param  Nette\Web\IHttpRequest
  * @return PresenterRequest|NULL
  */
 public function match(IHttpRequest $context)
 {
     \Nette\Diagnostics\FireLogger::log('-------------');
     \Nette\Diagnostics\FireLogger::log($context);
     return NULL;
     if (!preg_match('#^/([a-zA-Z0-9-]+)/?$#', $context->getUri()->path, $matches)) {
         return NULL;
     }
     $id = $matches[1];
     if (dibi::fetchSingle("SELECT COUNT(*) FROM tabulka_produktu WHERE nameid=%s", $id)) {
         $presenter = 'Front:Product';
     } elseif (dibi::fetchSingle("SELECT COUNT(*) FROM tabulka_kategorie WHERE nameid=%s", $id)) {
         $presenter = 'Front:Category';
     } elseif (dibi::fetchSingle("SELECT COUNT(*) FROM tabulka_s_clanky WHERE nameid=%s", $id)) {
         $presenter = 'Front:Article';
     } else {
         return NULL;
     }
     // alternativa: použít jednu tabulku s páry URL -> jméno Presenteru
     // výhoda: jeden lookup místo (až) tří, neměřitelně vyšší rychlost ;)
     // nevýhoda: nutnost ji udržovat :-(
     // alternativa č.2: místo COUNT(*) načíst z DB celý záznam a předat v parametru presenteru
     // výhoda: stejně jej bude potřebovat
     // nevýhoda: nadstandardní závislost mezi routerem a presenterem
     $params = $context->getQuery();
     $params['id'] = $id;
     return new PresenterRequest($presenter, $context->getMethod(), $params, $context->getPost(), $context->getFiles(), array('secured' => $context->isSecured()));
 }
Пример #8
0
 /**
  * Maps HTTP request to a PresenterRequest object.
  * @param  Nette\Web\IHttpRequest
  * @return PresenterRequest|NULL
  */
 public function match(IHttpRequest $context)
 {
     if (!preg_match('#^/([a-z0-9]{1,3})/(.*?)/?$#', $context->getUri()->path, $matches)) {
         return NULL;
     }
     $lang = $matches[1];
     $categories = $matches[2];
     $pom = explode("/", $categories);
     $last = end($pom);
     if (dibi::fetchSingle("\n\t\t\tSELECT\n\t\t\t    COUNT(*)\n\t\t\tFROM\n\t\t\t    category\n\t\t\t    JOIN category_lang USING(id_category)\n\t\t\t    JOIN [lang] USING(id_lang)\n\t\t\tWHERE iso=%s", $lang, "AND link_rewrite = %s", $last)) {
         $presenter = 'Front:Eshop';
     } elseif (dibi::fetchSingle("SELECT COUNT(*) FROM menu_item WHERE lang = %s", $lang, "AND url_identifier=%s", $last)) {
         $presenter = 'Front:List';
     } else {
         return NULL;
     }
     // alternativa: použít jednu tabulku s páry URL -> jméno Presenteru
     // výhoda: jeden lookup místo (až) tří, neměřitelně vyšší rychlost ;)
     // nevýhoda: nutnost ji udržovat :-(
     // alternativa č.2: místo COUNT(*) načíst z DB celý záznam a předat v parametru presenteru
     // výhoda: stejně jej bude potřebovat
     // nevýhoda: nadstandardní závislost mezi routerem a presenterem
     $params = $context->getQuery();
     //                $params['link_rewrite'] = $last;
     $params['lang'] = $lang;
     return new NPresenterRequest($presenter, $context->getMethod(), $params, $context->getPost(), $context->getFiles(), array('secured' => $context->isSecured()));
 }
Пример #9
0
 public function renderDefault()
 {
     //uvod
     $home = dibi::fetch("SELECT * FROM [menu_item] WHERE home = 1 AND lang = %s", $this->lang);
     if (!$home) {
         $home = dibi::fetch("SELECT * FROM [menu_item] WHERE lang = %s", $this->lang, "ORDER BY sequence LIMIT 1");
     }
     $this->template->id_menu_item = $home['id_menu_item'];
     /*
      * META INFO
      */
     $this['header']->addTitle($home['meta_title']);
     $this['header']->setDescription($home['meta_description']);
     $node = $this->getService('Node');
     $query = $node->getAll($this->template->id_menu_item);
     $this->template->node_list = $query->fetchAll();
     //produkty na uvode
     $list = dibi::select('id_product')->from('product')->where('home = 1');
     $count_list = clone $list;
     $count = $count_list->removeClause('select')->select('COUNT(id_product)')->fetchSingle();
     $vp = new VisualPaginator($this, 'paginator');
     $paginator = $vp->getPaginator();
     $paginator->itemsPerPage = 12;
     $paginator->itemCount = (int) $count;
     $this->template->products = $list->limit($paginator->offset . ',' . $paginator->itemsPerPage)->fetchAll();
     $this->template->paginator = $paginator;
     foreach ($this->template->products as $k => $p) {
         $this->template->products[$k] = ProductModel::getProductWithParams($p['id_product'], $this->id_lang, $this->user);
     }
     /* widget */
     $this['productNewsSaleAvaiableTable']->setIdLang($this->id_lang);
     $this['productNewsSaleAvaiableTable']->setUser($this->user);
 }
Пример #10
0
    public function renderXml()
    {
        $this->template->items = dibi::query('
SELECT 
product.id_product AS id, 
product_lang.name, 
product_lang.description, 
product_lang.link_rewrite AS product_link,
category_product.id_category AS id_category,
category_lang.name AS category_name,
category_lang.link_rewrite AS category_link
FROM `product`
LEFT JOIN product_lang USING (id_product)
LEFT JOIN category_product USING (id_product)
LEFT JOIN category_lang USING (id_category)
WHERE product_lang.id_lang = 1 AND
 category_lang.id_lang = 1
GROUP BY (id_product)')->fetchAll();
        $this->template->baseUri = 'http://www.matrace-rosty.sk';
        $this->id_lang = 1;
        for ($i = 0; $i < count($this->template->items); $i++) {
            $productWithLowestPrice = dibi::query('SELECT * FROM product_param WHERE id_product = %i', $this->template->items[$i]['id'], ' ORDER BY price LIMIT 0,1')->fetch();
            $this->template->items[$i]['url'] = $this->getPresenter()->link('Eshop:current', array('categories' => $this->template->items[$i]['category_link'], 'url_identifier' => NStrings::webalize($this->template->items[$i]['product_link'])));
            $this->template->items[$i]['image'] = ProductModel::getImage($this->template->items[$i]['id']);
            $this->template->items[$i]['price_vat'] = round($productWithLowestPrice['price'], 2);
            $this->template->items[$i]['price'] = round($this->template->items[$i]['price_vat'] / 1.2, 2);
            $this->template->items[$i]['vat'] = '0.20';
            $this->template->items[$i]['size'] = $productWithLowestPrice['size'];
            $this->template->items[$i]['material'] = $productWithLowestPrice['material'];
        }
    }
Пример #11
0
/**
 * Metainformation catalogue
 * --------------------------------------------------
 *
 * MICKA_LIB_INSERT.PHP for MicKa
 *
 * @link       http://www.bnhelp.cz
 * @package    Micka
 * @category   Metadata
 * @version    20101120
 * @authors		 DZ
 */
function deleteMd($user, $type, $value, $mode, $par = NULL)
{
    setMickaLog('micka_lib_insert.php (deleteMd)', 'DEBUG', "user={$user}, {$type}={$value}, mode={$mode}, par={$par}");
    $rs = FALSE;
    // autorizace
    if ($user == 'guest' || !canAction()) {
        return $rs;
    }
    $record = getMdHeader($type, $value, $col = '', $fetch = array('all', '='));
    if (isset($record[0]['RECNO']) && $record[0]['RECNO'] > -1) {
        if (!getMdRight('edit', $user, $record[0]['DATA_TYPE'], $record[0]['CREATE_USER'], $record[0]['EDIT_GROUP'], $record[0]['VIEW_GROUP'])) {
            return $rs;
        } else {
            $sql = array();
            if ($mode == 'all') {
                array_push($sql, 'DELETE FROM [md_values] WHERE [recno]=%i;', $record[0]['RECNO']);
                array_push($sql, 'DELETE FROM [md] WHERE [recno]=%i;', $record[0]['RECNO']);
            } elseif ($mode == 'value') {
                array_push($sql, 'DELETE FROM [md_values] WHERE [recno]=%i  AND md_id<>38;', $record[0]['RECNO']);
            }
            dibi::begin();
            try {
                dibi::query($sql);
                dibi::commit();
                $rs = TRUE;
            } catch (DibiException $e) {
                setMickaLog($e, 'ERROR', 'micka_lib_insert.php (deleteMd)');
                dibi::rollback();
            }
        }
    }
    //Debug::dump($rs);
    setMickaLog('micka_lib_insert.php (deleteMd)', 'DEBUG', "return={$rs}");
    return $rs;
}
Пример #12
0
    /**
     * Constractor creates connection and checks/creates tables stucture
     */
    public function __construct()
    {
        $dibiConfig = dibi::getConnection()->getConfig();
        $dbname = isset($dibiConfig['dbname']) ? $dibiConfig['dbname'] : $dibiConfig['database'];
        $config = array('driver' => 'sqlite', 'profiler' => Environment::getConfig('perform')->storage_profiler, 'database' => realpath(Environment::getConfig('perform')->modelCache) . '/' . $dbname . '-storage.sdb');
        parent::__construct($config, 'storage');
        if (!$this->getDatabaseInfo()->hasTable('fields')) {
            $this->query('CREATE TABLE [fields] ([id] INTEGER NOT NULL PRIMARY KEY,
		[name] VARCHAR(100) NOT NULL, [table] VARCHAR(50) NOT NULL,
		[hash] VARCHAR(32) NOT NULL, [type] VARCHAR(50));
		CREATE UNIQUE INDEX [fields_idx] on [fields] ( [name], [table]);');
        }
        if (!$this->getDatabaseInfo()->hasTable('tables')) {
            $this->query('CREATE TABLE [tables] ( [id] INTEGER NOT NULL PRIMARY KEY,
		[name] VARCHAR(100) NOT NULL UNIQUE, [hash] VARCHAR(32) NOT NULL);');
        }
        if (!$this->getDatabaseInfo()->hasTable('views')) {
            $this->query('CREATE TABLE [views] ( [id] INTEGER NOT NULL PRIMARY KEY,
		[name] VARCHAR(100) NOT NULL UNIQUE, [hash] VARCHAR(32) NOT NULL);');
        }
        if (!$this->getDatabaseInfo()->hasTable('indexes')) {
            $this->query('CREATE TABLE [indexes] ([id] INTEGER NOT NULL PRIMARY KEY,
		[name] VARCHAR(100) NOT NULL, [table] VARCHAR(50) NOT NULL,
		[hash] VARCHAR(32) NOT NULL, [unique] BOOLEAN);
		CREATE UNIQUE INDEX [indexes_idx] on [indexes] ( [name], [table]);');
        }
    }
Пример #13
0
 protected function setUp()
 {
     $this->db = dibi::getConnection("ormion");
     $this->db->delete("comments")->execute();
     $this->db->delete("pages")->execute();
     $this->db->query("insert into [pages]", array("name" => "Clanek", "description" => "Popis", "text" => "Text", "visits" => 0, "allowed" => true), array("name" => "Article", "description" => "Description", "text" => "Text emericky.", "visits" => 5, "allowed" => false), array("name" => "Nepovolený článek", "description" => "Popis nepovoleného článku", "text" => "Dlouhý text. By byl delší než tento.", "visits" => 3, "allowed" => false), array("name" => "Jinačí článek", "description" => "Ryze alternativní popis", "text" => "Duchaplný text.", "visits" => 8, "allowed" => true));
 }
Пример #14
0
    function renderXml_old()
    {
        //$this->id_lang
        $this->template->items = dibi::query('
SELECT 
product.id_product AS id, 
product_lang.name, 
product_lang.meta_description, 
product_lang.link_rewrite AS product_link,
category_product.id_category AS id_category,
category_lang.name AS category_name,
category_lang.link_rewrite AS category_link

FROM `product`
LEFT JOIN product_lang USING (id_product)
LEFT JOIN category_product USING (id_product)
LEFT JOIN category_lang USING (id_category)
WHERE product_lang.id_lang = 1 AND
 category_lang.id_lang = 1
GROUP BY (id_product)')->fetchAll();
        $this->template->baseUri = 'http://' . $_SERVER['HTTP_HOST'];
        $this->id_lang = 1;
        for ($i = 0; $i < count($this->template->items); $i++) {
            $this->template->items[$i]['url'] = $this->link(':Front:Product:default', array('id' => $this->template->items[$i]['id'], 'id_category' => $this->template->items[$i]['id_category']));
            $this->template->items[$i]['image'] = ProductModel::getImage($this->template->items[$i]['id']);
            $this->template->items[$i]['price_vat'] = round($productWithLowestPrice['price'], 2);
            $this->template->items[$i]['price'] = round($this->template->items[$i]['price_vat'] / 1.2, 2);
            $this->template->items[$i]['vat'] = '0.20';
            $this->template->items[$i]['size'] = $productWithLowestPrice['size'];
            $this->template->items[$i]['material'] = $productWithLowestPrice['material'];
        }
        dde($this->template->items);
    }
Пример #15
0
 public function getToken()
 {
     session_start();
     $code = $_REQUEST["code"];
     if (empty($code)) {
         $_SESSION['state'] = md5(uniqid(rand(), TRUE));
         //CSRF protection
         $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . APP_ID . "&redirect_uri=" . urlencode(REDIRECT_URI) . "&scope=" . PERMISSIONS . "&state=" . $_SESSION['state'];
         echo "<script> top.location.href='" . $dialog_url . "'</script>";
     }
     if ($_SESSION['state'] && $_SESSION['state'] === $_REQUEST['state']) {
         $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . APP_ID . "&redirect_uri=" . urlencode(REDIRECT_URI) . "&client_secret=" . APP_SECRET . "&code=" . $code;
         $response = file_get_contents($token_url);
         $params = null;
         parse_str($response, $params);
         $date = new DateTime();
         $date->add(new DateInterval('PT' . $params["expires"] . 'S'));
         $arr = array('token' => $params['access_token'], 'expiration' => $date);
         dibi::query('TRUNCATE tokens');
         dibi::query('INSERT INTO tokens', $arr);
         echo "Thanks for your token :)";
     } else {
         echo "The state does not match. You may be a victim of CSRF.";
     }
 }
Пример #16
0
 public function __construct(IComponentContainer $parent = NULL, $name = NULL)
 {
     parent::__construct($parent, $name);
     $this->db = dibi::getConnection();
     self::$count++;
     //		$this->setWebloaderPaths();
 }
Пример #17
0
 private function loadAll()
 {
     // @todo odchytavat vyjimky z dibi pro pripad neexistujici tabulky.
     $query = "SELECT `module_functions_id`, `webinstance_id`, `pageid_id`, `command` FROM `" . Config::DB_PREFIX . 'routedynamic_' . $this->langSymbol . "`";
     $record = dibi::query($query)->fetchAll();
     $this->importRecord($record);
 }
Пример #18
0
 /**
  * Performs an authentication
  *
  * @param  array
  * @return void
  * @throws AuthenticationException
  */
 public function authenticate(array $credentials)
 {
     $username = $credentials[self::USERNAME];
     $password = $credentials[self::PASSWORD];
     $sql = dibi::query('SELECT * FROM [' . TABLE_USERS . '] WHERE name=%s;', $username);
     $sql->setType('permission', Dibi::BOOL);
     $row = $sql->fetch();
     /*if (count($sql)==0) {
           throw new AuthenticationException('Unknown user', self::IDENTITY_NOT_FOUND);
       }*/
     /*if ($row->password !== md5($password)) {
           throw new AuthenticationException('Password not match', self::INVALID_CREDENTIAL);
       }*/
     if (count($sql) == 0 or $row->password !== md5($password)) {
         throw new AuthenticationException('Incorrect password or name', self::INVALID_CREDENTIAL);
     }
     // get roles
     $sql = dibi::query('SELECT r.key_name
                             FROM [' . TABLE_ROLES . '] AS r
                             RIGHT JOIN [' . TABLE_USERS_ROLES . '] AS us ON r.id=us.role_id
                             WHERE us.user_id=%i;', $row->id);
     $roles = $sql->fetchPairs();
     unset($row->password);
     return new Identity($username, $roles, $row);
 }
Пример #19
0
 /**
  * Translates the given string.
  * @param  string	translation string
  * @param  int		count (positive number)
  * @return string
  */
 public function translate($message, $count = 1)
 {
     $message = (string) $message;
     //		if (!empty($message) && isset($this->dictionary[$message])) {
     //			$word = $this->dictionary[$message];
     //			if ($count === NULL) $count = 1;
     //
     //			$s = preg_replace('/([a-z]+)/', '$$1', "n=$count;" . $this->meta['Plural-Forms']);
     //			eval($s);
     //			$message = $word->translate($plural);
     //		}
     if (!isset($this->translate[$message]) or $this->translate[$message] == '') {
         $message = $message;
         //			echo $message;exit;
         if (!dibi::fetchSingle("SELECT 1 FROM [lang_translate] WHERE [key] LIKE %s", $message, "AND [id_lang] = %i", $this->id_lang)) {
             //				echo dibi::$sql;
             Lang::insertTranslateKey($message, $this->id_lang);
         }
         $this->translate[$message] = $message;
         Lang::invalidateCache();
     } else {
         $message = $this->translate[$message];
     }
     //
     //		$args = func_get_args();
     //		if (count($args) > 1) {
     //			array_shift($args);
     //			$message = vsprintf($message, $args);
     //		}
     //
     //
     return $message;
 }
Пример #20
0
 public function beforeRender()
 {
     $filters = $this->getUniqueValues(array('works' => array('year', 'award', 'type'), 'authors' => array('class')));
     $temp = $filters['authors'];
     unset($filters['authors']);
     //$filters['works']['category'] = Model::palicky();// + array(5=>'palice');    // 'category'=>'Kategorie',
     $filters['works']['grade'] = Model::rocniky();
     $filters['palicka']['category'] = Model::palicky();
     $filters['authors'] = $temp;
     //{link :Front:Default:works "category"=>palicka}
     $this->template->filters = $filters;
     $this->template->schoolYear = Model::getSchoolYear();
     $newest = dibi::query('SELECT
       url,
       title,
       CONCAT_WS(" ", name, surname) as authorName          
       FROM [works] 
       join [authors] on author = authorId', 'ORDER BY %by', array('added' => 'desc'), 'LIMIT %i', 2)->fetchAll();
     $this->template->newest = $newest;
     $mostread = dibi::query('SELECT
       url,
       title,
       CONCAT_WS(" ", name, surname) as authorName          
       FROM [works] 
       join [authors] on author = authorId', 'ORDER BY %by', array('read' => 'desc'), 'LIMIT %i', 3)->fetchAll();
     $this->template->mostread = $mostread;
     $user = Environment::getUser();
     if ($user->isLoggedIn()) {
         $this->template->adminMode = true;
     }
 }
Пример #21
0
 public function __construct($app)
 {
     $app->post('/rest/login/', function () use($app) {
         $user = json_decode($app->request->getBody(), true);
         if (!isset($user['username']) || empty($user['username'])) {
             $app->error();
         }
         if (!isset($user['password']) || empty($user['password'])) {
             $app->error();
         }
         $result = \dibi::query('select username FROM ::user where username = %s and password = %s', $user['username'], md5($user['password']))->fetchAll();
         if (sizeof($result) != 1) {
             return $app->error();
         }
         $oldToken = \dibi::query('select token from ::oauth where username = %s', $user['username'])->fetch();
         $token = bin2hex(openssl_random_pseudo_bytes(16));
         $auth = array();
         $auth["username"] = $user['username'];
         $auth["token"] = $token;
         if ($oldToken["token"]) {
             \dibi::query('update ::oauth set token = %s where username = %s', $token, $user['username']);
         } else {
             \dibi::query('insert into ::oauth', $auth);
         }
         echo json_encode($token);
     });
 }
Пример #22
0
 /**
  * Component factory.
  * @see Nette/ComponentContainer#createComponent()
  */
 protected function createComponentDataGrid($name)
 {
     $grid = new DataGrid();
     $grid->bindDataTable(dibi::getConnection()->dataSource('SELECT
       authorId as id,
       name,
       surname,
       class,', Model::sqlClassName(Model::getSchoolYear()) . 'as classMark,
       (SELECT COUNT(workId) FROM [works] WHERE author=authorId) as sum                        
       FROM [authors]
     '));
     $grid->addColumn('name', 'Jméno');
     $grid->addColumn('surname', 'Příjmení')->addDefaultSorting('asc');
     $grid->addColumn('class', 'Maturita')->getCellPrototype()->style('text-align: center;');
     $grid->addColumn('classMark', 'Třída')->getCellPrototype()->style('text-align: right;');
     $grid->addColumn('sum', 'Počet prací')->getCellPrototype()->style('text-align: right;')->class('pages');
     $grid->addActionColumn('Akce');
     $grid->keyName = 'id';
     $grid->addAction('Smazat', 'delete!', NULL, FALSE, DataGridAction::WITH_KEY);
     $grid['name']->addFilter();
     $grid['surname']->addFilter();
     $grid['class']->addSelectboxFilter();
     $grid['classMark']->addSelectboxFilter();
     $grid['sum']->addSelectboxFilter();
     $grid->multiOrder = FALSE;
     $grid->itemsPerPage = $this->getCookiesItemsCount(15);
     $renderer = $grid->getRenderer();
     $renderer->paginatorFormat = '%label% %input% z %count%';
     $renderer->infoFormat = 'Autoři %from%. - %to%. z %count% | Zobrazit: %selectbox% | %reset%';
     $renderer->onRowRender[] = array($this, 'OnRowRendered');
     //$grid->rememberState = TRUE;
     $this->addComponent($grid, $name);
     return;
 }
Пример #23
0
 public static function show()
 {
     if (isset($_GET['ajax_action_section']) and $_GET['ajax_action_section'] == 'save_description') {
         dibi::query("\n  \t\t\tUPDATE [newsletter_emails] \n  \t\t\tSET description = %s", $_POST['description'], "WHERE id_newsletter_emails = %i", $_POST['id_newsletter_emails']);
         exit;
     }
     MT::addTemplate(APP_DIR . '/require_modules/newsletter/default.phtml', 'newsletter');
     $ds = NewsletterModel::getDatasource();
     if (isset($_GET['id_newsletter_delete'])) {
         NewsletterModel::delete($_GET['id_newsletter_delete']);
         header('location: admin.php?section=newsletter');
         exit;
     }
     if (isset($_GET['export'])) {
         $dse = clone $ds;
         MT::addVar('newsletter', 'export', $dse->where('active = 1 AND id_newsletter_emails IN %l', $_GET['id'])->fetchAll());
     }
     if (@$_GET['order_by'] == 'email') {
         $ds->orderBy('email');
     } else {
         $ds->orderBy('adddate');
     }
     //$vp = new MyPaginator($ds, 10);
     MT::addVar('newsletter', 'emails', $ds->fetchAll());
     //  	MT::addVar('newsletter', 'vp', $vp);
 }
Пример #24
0
 public function loadGroupsByUserId($id)
 {
     $query = "SELECT `id`, `pid`, `title`, `description` FROM\n\t\t\t`" . Config::DB_PREFIX . "user_groups` ug\n\t\t\tJOIN  `" . Config::DB_PREFIX . "groups` g ON g.`id` = ug.`group_id`\n\t\t\tWHERE ug.`user_id` = " . $id;
     $result = dibi::query($query)->fetchAssoc('id');
     $this->importRecord($result);
     return $this;
 }
Пример #25
0
 static function createTable($table, $group)
 {
     // header
     $header = array();
     $res = dibi::select('COLUMN_COMMENT, COLUMN_NAME')->from('information_schema.COLUMNS')->where('(TABLE_NAME = %s AND COLUMN_NAME = %s)', 'general', 'name')->or('(TABLE_NAME = %s AND COLUMN_NAME = %s)', 'general', 'id')->or('(TABLE_NAME = %s)', $table)->execute();
     $header = $res->fetchAll();
     // Changing header so that it fits the JOINed select
     $header[1]['COLUMN_COMMENT'] = 'Summoner name';
     $header[1]['COLUMN_NAME'] = 'summoner_name';
     // body
     $existing_players = $group->getExistingPlayers();
     $t1_select = dibi::select('summoner_name, id')->as('id_general')->from('general');
     $t2_select = dibi::select("*")->from($table);
     $res = dibi::select('*')->from($t1_select)->as('t1')->innerJoin($t2_select)->as('t2')->on('t1.id_general = t2.id')->where('( id, region) ')->in($existing_players);
     // create column names to check if table can be ordered
     $column_names = array();
     foreach ($header as $column) {
         array_push($column_names, $column["COLUMN_NAME"]);
     }
     // check if ordering is set and according to it, rearrange selection from database
     if (isset($_SESSION["orderby"]) && isset($_SESSION["way"])) {
         if (in_array($_SESSION["orderby"], $column_names)) {
             $res = $res->orderBy($_SESSION["orderby"]);
             if ($_SESSION["way"] == "asc") {
                 $res = $res->asc();
             } else {
                 $res = $res->desc();
             }
         }
     }
     $res = $res->execute();
     $body = $res->fetchAll();
     $table_elements = array($header, $body);
     return $table_elements;
 }
Пример #26
0
 public static function duplicate($id_node, $new_id_node)
 {
     // nacitanie, co ma skopirovat
     $values = dibi::fetch("SELECT * FROM [" . self::TABLE . "] WHERE id_node = %i", $id_node);
     //vytvorenie
     self::add($new_id_node);
     self::saveHome($values, $new_id_node);
 }
Пример #27
0
 /**
  * Returns custom panels.
  * @return array
  */
 public function getPanels()
 {
     $panels = array();
     if ($this->sql !== NULL) {
         $panels['SQL'] = array('expanded' => TRUE, 'content' => dibi::dump($this->sql, TRUE));
     }
     return $panels;
 }
Пример #28
0
 /**
  * get owners' ids of packages containing checked file
  *
  * @return array
  */
 public function getOwnersOfPackagesContainingFile()
 {
     if (empty($this->ownersOfPackagesContainingFile)) {
         $this->ownersOfPackagesContainingFile = dibi::select('owner_id')->from(BaseModel::CLIENT_PACKAGES_TABLE)->as('cp')->join(BaseModel::FILES_2_CLIENT_PACKAGES_TABLE)->as('f2cp')->on('f2cp.client_packages_id = cp.id')->where('f2cp.files_id = %i', $this->id)->fetchAssoc('owner_id');
         $this->ownersOfPackagesContainingFile = array_keys($this->ownersOfPackagesContainingFile);
     }
     return $this->ownersOfPackagesContainingFile;
 }
Пример #29
0
 /**
  * Use this function to connect, if you want to use dibi::setProxyOverride
  *
  * @param array $config
  * @param int $name
  * @return DibiConnection|void
  * @throws DibiProxyException
  */
 public static function connect($config = array(), $name = 0)
 {
     if ($name !== 0) {
         throw new DibiProxyException('Named connection are not supported in this version of dibi, due to proxying issues.');
     }
     $connection = new DibiProxyConnection($config, $name);
     parent::setConnection($connection);
 }
Пример #30
0
 protected function _writeMethodsForEavAttributes($model, $table)
 {
     $query = 'SELECT attribute_code as Field
         FROM eav_attribute a
         JOIN eav_entity_type t ON t.entity_type_id = a.entity_type_id
         WHERE entity_model = %s';
     $this->_writeMethodsForFields($model, $table, \dibi::query($query, $this->_classIdentifiers[$model]), 'eav');
 }