public function __construct() { $this->db = App::db(); $db_map = App::conf('db_map'); $this->db_name = current(array_keys($db_map)); $this->db->usedb($this->db_name); }
/** * Clean expired sessions * * @param int $maxlifetime The session lifetime (not used) */ public function gc($maxlifetime) { if (!$maxlifetime) { $maxlifetime = max(App::conf()->get('session.lifetime'), ini_get('session.gc_maxlifetime')); } return (bool) SessionModel::deleteBySQL(':lifetime AND mtime + :lifetime < :now', array('lifetime' => $maxlifetime, 'now' => time())); }
/** * Open a log file * * @param string $level The level of the log file */ private function open($level) { $basename = $level . '.log'; $dirname = App::conf()->get('log.dir') ? App::conf()->get('log.dir') : LOG_DIR; $filename = $dirname . $basename; if (is_file($filename) && filesize($filename) >= self::MAX_FILE_SIZE) { // Archive the last file and create a new one // rename all archives already existing (keep only last 9 archives) $archives = array_reverse(glob($filename . '.*.zip')); foreach ($archives as $archive) { preg_match('/^' . preg_quote($basename, '/') . '\\.(\\d+)\\.zip$/', basename($archive), $match); if ($match[1] > self::MAX_FILES_BY_LEVEL) { unlink($archive); } else { rename($archive, $filename . '.' . ($match[1] + 1) . '.zip'); } } // Create the new archive $zip = new \ZipArchive(); $zip->open($filename . '.0.zip', \ZipArchive::CREATE); $zip->addFile($filename); $zip->close(); unlink($filename); } $this->resources[$level] = fopen($filename, 'a+'); }
private function assignGlobalVars() { $this->assign('loginUser', array('user_id' => $this->adminId, 'user_name' => $this->userName, 'sex' => $this->adminSex)); $powers = $this->powers; // 菜单 $pageName = ''; $menuList = \App::conf('menu'); foreach ($menuList as $k => &$group) { $group['active'] = ''; foreach ($group['submenu'] as $kk => &$submenu) { if ($this->adminId > 1 && !in_array($submenu['route'], $powers)) { unset($group['submenu'][$kk]); } $submenu['active'] = ''; if (CUR_ROUTE == $submenu['route']) { $submenu['active'] = 'active'; $group['active'] = 'active open'; $pageName = $submenu['name']; } } if (empty($group['submenu'])) { unset($menuList[$k]); } } $this->assign(array('menuList' => $menuList, 'pageName' => $pageName)); }
/** * 初始化模板对象 * 对同一个模板对象重复使用可通过该方法清空/重置所有模板变量 * * @return void */ public function init() { $this->var_map = array(); $this->var_map['static_url'] = App::conf('static_url'); $config_ext = App::conf('template_ext'); if (!empty($config_ext)) { $this->template_ext = $config_ext; } }
/** * 设置数据库 * * @param string $name * @return void */ public function setDb($name) { $db_map = App::conf('db_map'); if (isset($db_map[$name])) { $this->dbname = $db_map[$name]; } else { $this->dbname = $name; } mysql_select_db($this->dbname, $this->link); }
public function __construct() { if (!extension_loaded('memcache')) { throw new AppException('Memcache extension not loaded'); } $this->memcache = new Memcache(); if ($temp = explode(':', App::conf('memcache_host'))) { $host = !empty($temp[0]) ? $temp[0] : 'localhost'; $port = !empty($temp[1]) ? intval($temp[1]) : 11211; $this->memcache->connect($host, $port); } }
/** * Get the body contents of the current section. */ public static function body() { $conf = App::conf(); if (!is_array($conf['Sections'])) { return ''; } if (!isset($conf['Sections'][self::$section])) { return ''; } $keys = array_keys($conf['Sections'][self::$section]); $handler = array_shift($keys); return App::$controller->run($handler); }
/** * 构造方法,初始化相关参数并判断是否可以写入 * * @return void */ public function __construct() { if ($cache_level = App::conf('file_cache_level')) { if ($cache_level > 3) { $cache_level = 3; } $this->cache_level = intval($cache_level); } $this->path = DATA_PATH . '/cache'; if (!is_dir($this->path) && !mkdir($this->path, 0777, true) || !touch($this->path . '/write_test.data')) { throw new AppException('Path ' . $this->path . ' not writable!'); } }
public function main() { $this->layout = 'demo'; $this->scriptTime = false; $phpver = phpversion(); $sysDir = strtoupper(str_replace('\\', '/', App::$sysroot)); $appDir = pathinfo($_SERVER['SCRIPT_FILENAME']); $appDir = strtoupper($appDir['dirname']); if (0 === strpos($sysDir, '..') || 0 === strpos($sysDir, '/') || 0 !== strpos($sysDir, $appDir)) { $integration = 'Centralized'; } else { $integration = 'Portable'; } if (function_exists('apache_get_modules')) { $modules = apache_get_modules(); $modules = in_array('mod_rewrite', $modules) ? 'ok' : 'failed'; } else { $modules = 'unknown'; } $fallback = function_exists('json_decode') && function_exists('json_encode') ? 5 <= (int) $phpver && 2 <= (int) substr($phpver, 2) ? 'ignored' : 'ok' : 'failed'; $tmp = new File(App::conf('file.tmp')); if (touch(App::conf('file.tmp') . '/demo.txt')) { $tempFolder = 'ok'; unlink(App::conf('file.tmp') . '/demo.txt'); } else { $tempFolder = 'failed'; } $dbs = App::conf('database'); if (empty($dbs)) { $db = 'empty'; } else { list($dbName, $dbConf) = each($dbs); $modelMySQL = new MysqlDatabase(); $modelOracle = new OracleDatabase(); if ($modelMySQL->connect($dbConf)) { $db = 'ok'; } else { $db = 'failed'; } } $siteurl = false === App::conf('site_url') ? 'unset' : 'ok'; $this->show('phpversion', $phpver); $this->show('integration', $integration); $this->show('rewrite', $modules); $this->show('fallback', $fallback); $this->show('tempfolder', $tempFolder); $this->show('dbname', $dbName); $this->show('db', $db); $this->show('siteurl', $siteurl); }
/** * Initialize the session user */ public function init() { if (!$this->getData('user.id')) { $this->setData('user.id', 0); } if (App::conf()->has('db')) { // Get the user from the database $this->user = User::getById($this->getData('user.id')); } else { // The database does not exists yet. Create a 'fake' guest user $this->user = new User(array('id' => User::GUEST_USER_ID, 'username' => 'guest', 'active' => 0)); $this->logged = false; } $this->logged = $this->user->isLogged(); }
/** * Parses the URL to determine what controller, method and properties will be used. * Returns <b>TRUE</b> when no error occured, else <b>FALSE</b>. * @static * @param array $routes re-routing rule. * @return boolean **/ public static function parse($routes = array()) { self::$class = null; self::$method = null; self::$params = null; $url = strtok($_SERVER['QUERY_STRING'], '&'); unset($_GET[$url]); $keys = array_keys($routes); sort($keys); $tmp = strtoupper($url); for ($i = count($keys) - 1; 0 <= $i; $i--) { if (0 === strpos($tmp, strtoupper($keys[$i]))) { $url = $routes[$keys[$i]] . substr($url, strlen($keys[$i])); break; } } $url = self::applyDefault($url, $routes); if (!empty($url[0])) { $controller = ucfirst(App::toMethodName(array_shift($url))) . 'Controller'; } if (empty($controller)) { return false; } $defaultAction = App::conf('APPLICATION.default_method'); $action = empty($url[0]) ? $defaultAction : App::toMethodName($url[0]); $allow = array_diff(get_class_methods($controller), get_class_methods(get_parent_class($controller))); // try to know which method to use. if (in_array($action, $allow) && method_exists($controller, $action)) { array_shift($url); } elseif (method_exists($controller, $defaultAction)) { $action = $defaultAction; } else { return false; } self::$class = $controller; self::$method = $action; self::$params = $url; return true; }
private function getPowerList($chkpower = '') { $chkpower = empty($chkpower) ? [] : explode(',', $chkpower); $menuList = \App::conf('menu'); $powerList = []; foreach ($menuList as $row) { $group['name'] = $row['name']; $group['list'] = []; foreach ($row['submenu'] as $r) { $group['list'][] = ['name' => $r['name'], 'route' => $r['route'], 'checked' => in_array($r['route'], $chkpower)]; } $powerList[] = $group; } return $powerList; }
public static function message($msg, $type = 'error') { self::log($type, $msg); if (App::conf('debug_model')) { App::finish($msg, true); } }
/** * Loads the configurations to the class. * Calling this multiple times will append/overwrite the previous configuration keys. * @param array|string $conf configuration source. * @param string $namespace namespace of the contents. * @static */ public static function initialize($conf, $namespace = '') { $conf = !is_array($conf) ? parse_ini_file($conf, true) : $conf; if (empty($conf)) { return false; } if (!empty($namespace)) { $conf = array($namespace => $conf); } $conf['FILE_APPLICATION'] = empty($conf['FILE_APPLICATION']) ? array() : $conf['FILE_APPLICATION']; $conf['FILE_SYSTEM'] = empty($conf['FILE_SYSTEM']) ? array() : $conf['FILE_SYSTEM']; $conf['file'] = array_merge($conf['FILE_APPLICATION'], $conf['FILE_SYSTEM']); unset($conf['FILE_APPLICATION'], $conf['FILE_SYSTEM']); if (!empty($conf['DEFINE'])) { foreach ($conf['DEFINE'] as $k => $v) { if (!defined($k)) { define($k, $v); } } } unset($conf['DEFINE']); self::$conf = array_merge_recursive_distinct(self::$conf, $conf); }
spl_autoload_register(array('App', 'load')); ini_set('unserialize_callback_func', 'spl_autoload_call'); File::defaultPath(App::conf('file.tmp')); App::$sysroot = $ini['system_root']; // For accurate date transactions. date_default_timezone_set(App::conf('timezone')); // Activates/Deactivates debug mode. App::debug(); // Overwritting the error handler will the one in App Class. set_error_handler(array('App', 'errorHandler')); if (!RestRoute::parse(App::conf('route'))) { App::throwError('404'); } // Everything is OK so far. start executing the method. $params = RestRoute::$params; $controller = new RestRoute::$class(RestRoute::$method, $params); call_user_func_array(array($controller, RestRoute::$method), $params); $layout = $controller->layout; $viewData = $controller->getViewData(); $scriptTime = $controller->scriptTime; unset($controller); // Loading the View module if (!empty($layout)) { // assumes that layout is an HTML format if it's not specified. AbstractFormat::factory($viewData, $layout, App::conf('view.compress')); } if ($scriptTime) { $ms = round((array_sum(explode(' ', microtime())) - $ms) * 1000, 4); // setting the end time. echo '<pre>script execution: ', $ms, 'ms</pre>'; }
/*** Access to the OS database (MySQL) ***/ try { DB::add(MAINDB, App::conf()->get('db.maindb')); App::getInstance()->singleton('db', DB::get(MAINDB)); } catch (DBException $e) { // The database is not configured, redirect to the installation exit(DEBUG_MODE ? $e->getMessage() : Lang::get('main.connection-error')); } } /*** Open the session ***/ if (App::conf()->has('db')) { session_set_save_handler(new DatabaseSessionHandler()); } session_set_cookie_params((int) App::conf()->get('session.lifetime'), '/'); session_start(); App::session()->init(); /*** Constants depending to the options ***/ if (App::request()->getCookies('language')) { define('LANGUAGE', App::request()->getCookies('language')); } elseif (App::conf()->has('db')) { if (App::session()->getUser()->getProfileData('language')) { define('LANGUAGE', App::session()->getUser()->getProfileData('language')); } elseif (Option::get('main.language')) { define('LANGUAGE', Option::get('main.language')); } } else { define('LANGUAGE', Lang::DEFAULT_LANGUAGE); } /*** Timezone ***/ define("TIMEZONE", App::conf()->has('db') && Option::get('main.timezone') ? Option::get('main.timezone') : DEFAULT_TIMEZONE); date_default_timezone_set(TIMEZONE);
/** * Get the real name of a table, with the configured prefix * * @param string $table The base table name * @param string $prefix If set, this prefix will replace the one configured for the application * * @return string The complete name of the table */ public static function getFullTablename($table, $prefix = null) { if ($prefix === null) { $prefix = App::conf()->get('db.prefix'); } return $prefix . $table; }
/*** Define the main paths ***/ define('STATIC_URL', ROOT_URL . '/static/'); define('THEMES_ROOT_URL', STATIC_URL . 'themes/'); define('PLUGINS_ROOT_URL', STATIC_URL . 'plugins/'); /*** Access to the OS database (MySQL) ***/ try { DB::add(MAINDB, App::conf()->get('db.maindb')); $app->singleton('db', DB::get(MAINDB)); } catch (DBException $e) { // The database is not configured, redirect to the installation exit(DEBUG_MODE ? $e->getMessage() : Lang::get('main.connection-error')); } /*** Open the session ***/ session_set_save_handler(new DatabaseSessionHandler()); session_set_cookie_params((int) App::conf()->get('session.lifetime'), '/'); session_start(); App::session()->init(); /*** Constants depending to the options ***/ define('LANGUAGE', Option::get('main.language')); /*** Timezone ***/ define("TIMEZONE", Option::get('main.timezone')); date_default_timezone_set(TIMEZONE); /*** Initialize the plugins ***/ $plugins = App::conf()->has('db') ? Plugin::getActivePlugins() : array(Plugin::get('main'), Plugin::get('install')); foreach ($plugins as $plugin) { if (is_file($plugin->getStartFile())) { include $plugin->getStartFile(); } } $filename = $argv[1]; include $filename;
/** * 语言包解析 * * 如果$langId不包含点号,则从公共语言包 common.php 文件搜索对应索引,如果 * 公共语言包文件不存在,则直接返回 $langId。 * * @param string $langId 语言ID,格式:文件名.数组key * @param array $params * @throws InvalidArgumentException * @return string */ public static function lang($langId, $params = array()) { static $cache = array(); if (false === strpos($langId, '.')) { if (!isset($cache['common'])) { $filename = App::conf('app', 'lang', 'zh_CN') . "/language.php"; if (is_file(LANG_PATH . $filename)) { $lang = array(); include LANG_PATH . $filename; $cache['common'] = $lang; } } if (isset($cache['common'][$langId])) { $file = 'common'; $idx = $langId; } else { return $langId; } } else { list($file, $idx) = explode('.', $langId); if ($file && !isset($cache[$file])) { $lang = array(); $filename = App::conf('app', 'lang', 'zh_CN') . "/{$file}.php"; if (!is_file(LANG_PATH . $filename)) { throw new InvalidArgumentException("lang file {$filename} not exists."); } include LANG_PATH . $filename; $cache[$file] = $lang; } if (!isset($cache[$file][$idx])) { throw new InvalidArgumentException("lang {$langId} not exists."); } } return preg_replace_callback('/{\\$(\\d+)}/', function ($m) use(&$params) { return $params[$m[1] - 1]; }, $cache[$file][$idx]); }
/** * Get all the plugins * * @param bool $includeMain If true, include main plugins to the returned list * @param bool $loadConf If set to true, load the plugins conf in the database * * @return array The list of plugin instances */ public static function getAll($includeMain = true, $loadConf = false) { $plugins = array(); $dirs = $includeMain ? array(MAIN_PLUGINS_DIR, PLUGINS_DIR) : array(PLUGINS_DIR); if ($loadConf && App::conf()->has('db')) { $configs = PluginModel::getAll(PluginModel::getPrimaryColumn()); } else { $configs = array(); } foreach ($dirs as $dir) { foreach (glob($dir . '*', GLOB_ONLYDIR) as $dir) { $name = basename($dir); $config = isset($configs[$name]) ? $configs[$name] : null; $plugin = self::get($name); if ($loadConf && !$plugin->isMainPlugin()) { $plugin->active = isset($config->active) ? (bool) $config->active : false; } $plugins[$name] = $plugin; } } return $plugins; }
/** * Get the application favicon URL */ public function getFaviconUrl() { if (App::conf()->has('db')) { $favicon = Option::get($this->_plugin . '.favicon') ? Option::get($this->_plugin . '.favicon') : Option::get($this->_plugin . '.logo'); } if (empty($favicon)) { return $this->getPlugin()->getStaticUrl('img/hawk-favicon.ico'); } else { return $this->getPlugin()->getUserfilesUrl($favicon); } }
require 'init.php'; if ($argc < 3) { echo "\nНеверные параметры запуска. Первым параметром должен быть указан ключ блока\n" . "разделяемой памяти. Второй параметр - длина блока.\n\n"; exit(0); } $key = $argv[1]; $size = $argv[2]; echo "Ключ : {$key}\n" . "Длина блока: {$size}\n"; $conf = App::conf('dealer'); $conf['size'] = $size; $conf['key'] = $key; $dealer = new $conf['class']($conf); if (!($data = $dealer->readData())) { throw new \Exception($dealer->getErrors()); } echo "Данные:\n"; var_dump($data); $worker = $data['worker']; if ($isClass = is_array($worker)) { $class = new $worker[0]($dealer); $worker[0] = $class; } echo App::conf('codePhrase') . "\n"; if ($isClass) { $result = is_null($data['params']) ? call_user_func($worker) : call_user_func($worker, $data['params']); //функция вне класса } else { $result = is_null($data['params']) ? call_user_func($worker, $dealer) : call_user_func($worker, $dealer, $data['params']); } //TODO что делать с $result? Оно никому не нужно. echo "Starter.Done\n";
/** * Get the table name of this model * * @return string the table name of the model */ public static function getTable() { return (static::$dbname == MAINDB ? App::conf()->get('db.prefix') : '') . static::$tablename; }
/*** Initialize the plugins ***/ $plugins = App::conf()->has('db') ? Plugin::getActivePlugins() : array(Plugin::get('main'), Plugin::get('install')); foreach ($plugins as $plugin) { if (is_file($plugin->getStartFile())) { include $plugin->getStartFile(); } } /*** Initialize the theme ***/ if (is_file(Theme::getSelected()->getStartFile())) { include Theme::getSelected()->getStartFile(); } (new Event('before-routing'))->trigger(); /*** Execute action just after routing ***/ Event::on('after-routing', function ($event) { $route = $event->getData('route'); if (!App::conf()->has('db') && App::request()->getUri() == App::router()->getUri('index')) { // The application is not installed yet App::logger()->notice('Hawk is not installed yet, redirect to install process page'); App::response()->redirectToAction('install'); return; } }); /*** Compute the routage ***/ App::router()->route(); } catch (HTTPException $err) { App::response()->setStatus($err->getStatusCode()); $response = array('message' => $err->getMessage(), 'details' => $err->getDetails()); if (App::request()->getWantedType() === 'json') { App::response()->setContentType('json'); App::response()->setBody($response); } else {
public function __construct() { $this->path_model = App::conf('path_model'); }
/** * Initializes the cache object. * @final * @return object */ public function startCache() { $key = $this->conf; if (!is_array($key)) { $key = array($key); } if (empty($key)) { App::kill('Cannot start caching without a database configuration.'); } $confs = App::conf('database'); $keyStr = array(); foreach ($key as $v) { if (!empty($v) && isset($confs[$v])) { $keyStr[] = $confs[$v]['username'] . '@' . $confs[$v]['db']; } } if (empty($keyStr)) { App::kill('Configuration key cannot be found in database.ini.'); } $key = $this->type . ':' . implode('-', $keyStr); $conf = App::conf('file.cache') . '/_modelcache'; return new FileCache($conf, $key, $this->expiresCache); }