Exemplo n.º 1
0
 public function testAddJavascript()
 {
     View::useLib('Mock');
     $view = new View();
     $view->js(array('test.js'));
     $this->assertEqual(1, count($view->_js));
 }
Exemplo n.º 2
0
Arquivo: Basic.php Projeto: atk4/atk4
 /**
  * Recursively render this view.
  */
 public function recursiveRender()
 {
     // get data source
     if (!$this->source) {
         // force grid sorting implemented in Grid_Advanced
         if ($this->owner instanceof Grid_Advanced) {
             $this->owner->getIterator();
         }
         // set data source for Paginator
         if ($this->owner->model) {
             $this->setSource($this->owner->model);
         } elseif ($this->owner->dq) {
             $this->setSource($this->owner->dq);
         } else {
             throw $this->exception('Unable to find source for Paginator');
         }
     }
     // calculate found rows
     if ($this->source instanceof DB_dsql) {
         $this->source->preexec();
         $this->found_rows = $this->source->foundRows();
     } elseif ($this->source instanceof Model) {
         $this->found_rows = (int) $this->source->count();
     } else {
         $this->found_rows = count($this->source);
     }
     // calculate current page and total pages
     $this->cur_page = (int) floor($this->skip / $this->ipp) + 1;
     $this->total_pages = (int) ceil($this->found_rows / $this->ipp);
     if ($this->cur_page > $this->total_pages || $this->cur_page == 1 && $this->skip != 0) {
         $this->cur_page = 1;
         if ($this->memorize) {
             $this->memorize('skip', $this->skip = 0);
         }
         if ($this->source instanceof DB_dsql) {
             $this->source->limit($this->ipp, $this->skip);
             $this->source->rewind();
             // re-execute the query
         } elseif ($this->source instanceof Model) {
             $this->source->setLimit($this->ipp, $this->skip);
         } else {
             // Imants: not sure if this is correct, but it was like this before
             $this->source->setLimit($this->ipp, $this->skip);
         }
     }
     // no need for paginator if there is only one page
     if ($this->total_pages <= 1) {
         return $this->destroy();
     }
     if ($this->cur_page > 1) {
         /** @type View $v */
         $v = $this->add('View', null, 'prev');
         $v->setElement('a')->setAttr('href', $this->app->url($this->base_page, $u = array($this->skip_var => $pn = max(0, $this->skip - $this->ipp))))->setAttr('data-skip', $pn)->set('« Prev');
     } else {
         $this->template->tryDel('prev');
     }
     if ($this->cur_page < $this->total_pages) {
         /** @type View $v */
         $v = $this->add('View', null, 'next');
         $v->setElement('a')->setAttr('href', $this->app->url($this->base_page, $u = array($this->skip_var => $pn = $this->skip + $this->ipp)))->setAttr('data-skip', $pn)->set('Next »');
     } else {
         $this->template->tryDel('next');
     }
     // First page
     if ($this->cur_page > $this->range + 1) {
         /** @type View $v */
         $v = $this->add('View', null, 'first');
         $v->setElement('a')->setAttr('href', $this->app->url($this->base_page, $u = array($this->skip_var => $pn = max(0, 0))))->setAttr('data-skip', $pn)->set('1');
         if ($this->cur_page > $this->range + 2) {
             /** @type View $v */
             $v = $this->add('View', null, 'points_left');
             $v->setElement('span')->set('...');
         }
     }
     // Last page
     if ($this->cur_page < $this->total_pages - $this->range) {
         /** @type View $v */
         $v = $this->add('View', null, 'last');
         $v->setElement('a')->setAttr('href', $this->app->url($this->base_page, $u = array($this->skip_var => $pn = max(0, ($this->total_pages - 1) * $this->ipp))))->setAttr('data-skip', $pn)->set($this->total_pages);
         if ($this->cur_page < $this->total_pages - $this->range - 1) {
             /** @type View $v */
             $v = $this->add('View', null, 'points_right');
             $v->setElement('span')->set('...');
         }
     }
     // generate source for Paginator Lister (pages, links, labels etc.)
     $data = array();
     //setting cur as array seems not working in atk4.3. String is working
     $tplcur = $this->template->get('cur');
     $tplcur = isset($tplcur[0]) ? $tplcur[0] : '';
     $range = range(max(1, $this->cur_page - $this->range), min($this->total_pages, $this->cur_page + $this->range));
     foreach ($range as $p) {
         $data[] = array('href' => $this->app->url($this->base_page, array($this->skip_var => $pn = ($p - 1) * $this->ipp)), 'pn' => $pn, 'cur' => $p == $this->cur_page ? $tplcur : '', 'label' => $p);
     }
     if ($this->ajax_reload) {
         $this->js('click', $this->owner->js()->reload(array($this->skip_var => $this->js()->_selectorThis()->attr('data-skip'))))->_selector('#' . $this->name . ' a');
     }
     parent::setSource($data);
     return parent::recursiveRender();
 }
Exemplo n.º 3
0
 /**
  * Display upload button
  */
 static function uploadBtn()
 {
     View::js("img_loading()", "var d=document.createElement('div'); d.setAttribute('style','position:fixed;display:table-cell;top:0px;left:0px;width:100%;height:100%;z-index:2001;background:#000;opacity:0.4;text-align:center;padding-top:50%;');d.innerHTML='<img src=\"images/upload.gif\" style=\"position:fixed;top:50%;left:50%;transform:translateX(-50%) translateY(-50%);\">';document.body.appendChild(d);");
     return "<input type='file' name='imglist_upload' onchange='img_loading();this.form.submit();' style='display:none;'>" . "<input type='button' value='" . L("Upload") . "' class='setsel_button' onclick=\"this.form['pe_f'].value='imglist';this.form['imglist_upload'].click();\">";
 }
Exemplo n.º 4
0
 static function start()
 {
     try {
         Session::start();
         //загрузка параметров движка
         Settings::$ENGINE = Engine::loadSettings();
         //проверка закрыт сайт или нет
         if (Settings::$ENGINE['site'] == 0) {
             View::renderClosed('Извините, доступ на сайт закрыт');
         }
         View::$template = Settings::$ENGINE['template'];
         Controller::$lang = Settings::$ENGINE['default_lang'];
         $route = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
         //считываем из сессии id пользователя (-1 назначаем неавторизованным пользователям)
         $user_id = -1;
         if (isset($_SESSION['uid']) && !empty($_SESSION['uid']) && is_numeric($_SESSION['uid'])) {
             $user_id = $_SESSION['uid'];
         }
         /*$pwd = "ruh";
           $hash = Crypt::password_hash($pwd);
           if(Crypt::password_verify($pwd,$hash)) echo "true";
           else echo "false";
           exit;*/
         /*print_r(AclModel::getRoles());
           exit;*/
         //проверяем, не был ли передан тип запроса (например при ajax запросе)
         $request_type = null;
         if (isset($_POST["request_type"]) && is_numeric($_POST["request_type"])) {
             $request_type = $_POST["request_type"];
             ini_set('display_errors', 0);
         } else {
             $page = PageManager::findPage($route == '/' ? '/main' : $route);
             if (!$page) {
                 throw new Exception404();
             }
             View::setTitle($page['title']);
             View::css(explode('|', $page['css']));
             View::js(explode('|', $page['js']));
             //TODO: замутить парсер META
             $args = json_decode($page['content'], true);
             foreach ($args as $key => $val) {
                 $class = new $args[$key]['c']();
                 View::$args[$key] = $class->{$args}[$key]['m'](!empty($args[$key]['a']) ? $args[$key]['a'] : null);
             }
             //print_r(View::$args);
             View::render('index', Settings::$ENGINE['template']);
         }
         //Если страницы не были найдены, то обращаемся напрямую к контроллеру
         $routes = explode('/', $route);
         array_shift($routes);
         if ($routes) {
             //задаем контроллер и его метод по умолчанию
             $controller_name = Settings::$DEFAULT_CONTROLLER;
             $action = 'index';
             //распарсиваем адресную строку
             //определяем имя контроллера
             if (!empty($routes[0])) {
                 $controller_name = $routes[0];
             }
             //его метод
             if (!empty($routes[1])) {
                 $action = $routes[1];
             }
             //все остальные параметры адресной строки преобразуем в аргументы
             $i = 2;
             $arg = array();
             while (!empty($routes[$i])) {
                 $arg[] = $routes[$i++];
             }
             //создаем объект для работы контроллером
             if (!class_exists($controller_name)) {
                 throw new Exception404();
             }
             $controller = new $controller_name();
             //проверяем, если это пост запрос c request_type, обрабатываем его соответственно
             if ($request_type != null) {
                 //проверяем, есть ли данный метод у контроллера
                 if (method_exists($controller_name, $action)) {
                     //если метод есть, то
                     //запускаем главную функцию обработки запроса
                     $res = $controller->{$action}(isset($arg) ? $arg : NULL);
                     //выводим результат
                     echo json_encode(array('answer' => $res));
                 } else {
                     //если функция не видна, то выдаем сответствующюю инфу
                     echo json_encode(array("error" => 'Не найдена функция для обработки запроса (' . $controller_name . '::' . $action . ')!'));
                 }
                 exit;
             }
             //если это не запрос, просто вызываем метод
             $controller->{$action}(isset($arg) ? $arg : NULL);
             unset($routes);
         } else {
             throw new Exception404();
         }
     } catch (mysqli_sql_exception $e) {
         if (Settings::$DEBUG) {
             echo '<br>DEBUG: mysqli_sql_exception: ' . $e->getMessage() . ' => ' . $e->getCode() . '<br>';
         }
         Log::writeLog($e->getMessage() . ' ' . $e->getCode());
     } catch (Exception404 $e) {
         //         Здесь сделаем так, что бы 404 выдавалось в контент или куда-то еще, что бы не нарушать целостность сайта
         //         View::render404();
         echo '404';
     } catch (Exception $e) {
         if (Settings::$DEBUG) {
             echo '<br>DEBUG: Exception: ' . $e->getMessage() . ' => ' . $e->getCode() . '<br>';
         }
     }
     ////        проверка на запрещенные или разрешенные IP-адреса
     //        if(Settings::$ENGINE['checkIP'] > 0)
     //        {
     //            $ip = Engine::checkIp($_SERVER['REMOTE_ADDR']);
     //
     //            if($ip && Settings::$ENGINE['checkIP'] == 1)
     //                View::renderClosed($ip['reason'], $ip['date']);
     //            else
     //                if(!$ip && Settings::$ENGINE['checkIP'] == 2)
     //                    View::renderClosed('Доступ к сайту с Вашего IP-адреса запрещен');
     //        }
     //
     //        /**
     //         * проверка на запрещенные или разрешенные ОС, браузеры или их версии
     //         * TODO: тут, по-хороошему, нужно поближе рассмотреть этот мехвнизм, обточить
     //         */
     //        if(Settings::$ENGINE['checkFStuff'] > 0)
     //        {
     //            $r = Engine::checkForbiddenStuff(self::getUserBrowser());
     //            if($r && Settings::$ENGINE['checkFStuff'] == 1)
     //                View::renderClosed($r);
     //            else
     //                if(!$r && Settings::$ENGINE['checkFStuff'] == 2)
     //                    View::renderClosed('Сайт не поддерживает работу с Вашими устройствами');
     //        }
     //
     //
     ////        проверка включена ли мультиязычность или нет, по умолчанию используется только русский язык
     //        if(Settings::$ENGINE['multiLang'])
     //            if(!empty($_COOKIE['lang']))
     //                Controller::$lang = $_COOKIE['lang'];
 }
Exemplo n.º 5
0
 private function loadNavigation()
 {
     $arr = array('NAME' => $_SERVER['PHP_AUTH_USER']);
     $arr['NODES'] = View::load(array('engine', 'adminNavigationNode'), array('HREF' => '/' . __CLASS__, 'alias' => 'Статистика', 'img' => View::img('chart', 'icons')));
     $files = Engine::loadControllers();
     $permissions = Users::getAdminPermissions($_SERVER['PHP_AUTH_USER']);
     if (count($permissions) == 1 && empty($permissions[0]['controller'])) {
         $permissions = false;
     }
     foreach ($files as $row) {
         if ($permissions && !in_array($row['name'], $permissions)) {
             continue;
         }
         if (strstr($row['name'], strtolower(__CLASS__))) {
             $row['name'] = 'admin';
         }
         $row['HREF'] = '/' . __CLASS__ . '/' . $row['name'];
         $row['img'] = View::img($row['img'], 'icons');
         $arr['NODES'] .= View::load(array('engine', 'adminNavigationNode'), $row);
     }
     View::setTitle('Страница статистики');
     View::css('engine');
     View::css('admin');
     View::js('engine');
     View::js('admin');
     View::loadContent('adminNavigation', $arr, 'engine');
 }
Exemplo n.º 6
0
 /**
  * Register GeoLocation
  *
  * @param cfg not used
  */
 function init($cfg)
 {
     //! check whether we are enabled
     if (empty($cfg['type'])) {
         return false;
     }
     if (Core::$client->ip != "CLI") {
         //! AJAX helper to save javascript variables into php session
         if (Core::$core->app == "geo" && !empty($_REQUEST['pe_s']) && $_REQUEST['pe_s'] == $_SESSION['pe_s']['geo.action']) {
             foreach ($_GET as $k => $v) {
                 if ($k != "pe_s") {
                     $_SESSION['pe_geo'][$k] = $v;
                 }
             }
             //! mark that we have a high accuracy latitude and longitude values from client
             $_SESSION['pe_geoclient'] = 1;
             die("OK");
         }
         //! query location
         //! 1-server side (common)
         if (function_exists("geoip_record_by_name")) {
             if (empty($_SESSION['pe_geo'])) {
                 $_SESSION['pe_geo'] = geoip_record_by_name(Core::$client->ip);
             }
         }
         //! 2-client side
         if ($cfg['type'] == 2) {
             View::js("init()", "if(navigator.geolocation)navigator.geolocation.getCurrentPosition(pe_geo,pe_geo);", true);
         } elseif ($cfg['type'] == 3) {
             View::js("init()", "if(navigator.geolocation)navigator.geolocation.watchPosition(pe_geo,pe_geo);", true);
         } elseif ($cfg['type'] == 4 && empty($_SESSION['pe_geoclient'])) {
             $ret = @json_decode(Http::get("http://ipinfo.io/" . Core::$client->ip), true);
             if (is_array($ret) && !empty($ret['ip'])) {
                 $r = explode(",", $ret['loc']);
                 $_SESSION['pe_geo']['postal_code'] = $ret['postal'];
                 $_SESSION['pe_geo']['country_code'] = $ret['country'];
                 $_SESSION['pe_geo']['region'] = $ret['region'];
                 $_SESSION['pe_geo']['city'] = $ret['city'];
                 $_SESSION['pe_geo']['latitude'] = floatval($r[0]);
                 $_SESSION['pe_geo']['longitude'] = floatval($r[1]);
                 $_SESSION['pe_geoclient'] = 1;
             }
         }
         //! both 2 and 3 needs this helper function to make an AJAX call
         if ($cfg['type'] == 2 && empty($_SESSION['pe_geoclient']) || $cfg['type'] == 3) {
             View::js("pe_geo(p)", "var s='',k,h=new XMLHttpRequest();if(p.code){if(document.body.getAttribute('data-geowarn')==null){document.body.setAttribute('data-geowarn',1);alert('E-GEO: '+L(p.message));}return;}else{document.body.removeAttribute('data-geowarn');for(k in p.coords)if(p.coords.hasOwnProperty(k)){s+='&'+encodeURIComponent(k)+'='+encodeURIComponent(p.coords[k]);}h.open('GET','" . Http::url("geo") . "?pe_s=" . urlencode($_SESSION['pe_s']['geo.action']) . "&timestamp='+(p.timestamp?p.timestamp:0)+s,true);h.send(null);}");
         }
         //! validation
         if (!is_array($_SESSION['pe_geo'])) {
             $_SESSION['pe_geo'] = [];
         }
         $_SESSION['pe_geo']['postal_code'] = trim($_SESSION['pe_geo']['postal_code']);
         $_SESSION['pe_geo']['country_code'] = trim(strtoupper($_SESSION['pe_geo']['country_code']));
         $_SESSION['pe_geo']['region'] = trim($_SESSION['pe_geo']['region']);
         $_SESSION['pe_geo']['city'] = trim($_SESSION['pe_geo']['city']);
         $_SESSION['pe_geo']['latitude'] = floatval($_SESSION['pe_geo']['latitude']);
         $_SESSION['pe_geo']['longitude'] = floatval($_SESSION['pe_geo']['longitude']);
         $_SESSION['pe_geo']['altitude'] = floatval($_SESSION['pe_geo']['altitude']);
         //! set geo information on client object
         Core::$client->geo = $_SESSION['pe_geo'];
     }
     return true;
 }