setFallbackAutoloader(true);
$registry = Zend_Registry::getInstance();
// Loading full config
$config = new Zend_Config(include(CFG_FILE_NAME), true);
if (file_exists(LOCAL_CFG_FILE_NAME)) {
$configLocal = new Zend_Config(include(LOCAL_CFG_FILE_NAME));
$config->merge($configLocal);
}
// autodetect database name if empty
if ('development' === APPLICATION_ENV && empty($config->database->params->dbname)) {
$path = str_replace(array('_framework', '.'), array('', '_'), strtolower(WWW_PATH));
$matches = array();
// 1 => project, 2 => subProject, 3 => trunk|branches|tags, 4 => branchPath
if (preg_match('@public_html/([^/]+)(?:/([^/]+))?/(trunk|branches|tags)(?:/([^/]+))?/www@', $path, $matches)) {
$prefix = ('quick_site' === $matches[1]) ? '' : 'prj_';
$project = (empty($matches[2])) ? $matches[1] : $matches[2];
$branchPath = (empty($matches[4])) ? '' : '_' . $matches[4];
$config->database->params->dbname = $prefix . $project . $branchPath;
}
}
$config->setReadOnly();
$registry->set('config', $config);
unset($config);
// Кешування метаданих таблиць
$frontendOptions = array('automatic_serialization' => true);
$cacheDir = BASE_PATH . '/tmp/cache';
if (!file_exists($cacheDir)) {
$umask = umask(0);
if (false === mkdir($cacheDir, 0777)) {
die('Cannot create directory: ' . $cacheDir);
}
umask($umask);
}
$backendOptions = array(
'cache_dir' => $cacheDir . '/',
'cache_file_umask' => 0664
);
$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
Zend_Locale_Data::setCache($cache);
// Визначення констант CURRENT_PAGE, PARENT_PAGE і т.п.
$currentPage = preg_replace('|^' . WEB_PATH . '/|', '', $_SERVER['REQUEST_URI']);
//$currentPage = rawurldecode($currentPage);
$currentPage = preg_replace('/\?.*$/', '', $currentPage);
$currentPageParts = explode('/', $currentPage);
$language = array_shift($currentPageParts);
if (!Qs_Db_Language::exists($language)) {
$language = Qs_Db_Language::getDefault();
}
$languages = Qs_Db_Language::getList();
define('CURRENT_LOCALE', $languages[$language]['locale']);
if (count($languages) > 1) {
$fileCommonMo = BASE_PATH . '/languages/' . CURRENT_LOCALE . '/common.mo';
if (file_exists($fileCommonMo)) {
$translate = new Zend_Translate('Qs_Translate_Adapter_Gettext', $fileCommonMo, CURRENT_LOCALE);
if (defined('DEBUG') && DEBUG && defined('LOG_UNTRANSLATED') && (bool)LOG_UNTRANSLATED) {
$fileCommonLog = BASE_PATH . '/languages/' . CURRENT_LOCALE . '/common.log';
exec($fileCommonLog . ' | sort | unique > ' . $fileCommonLog);
$writer = new Zend_Log_Writer_Stream($fileCommonLog);
$writer->setFormatter(new Zend_Log_Formatter_Simple("%message%\n"));
$log = new Zend_Log($writer);
$translate->setOptions(array('log' => $log, 'logUntranslated' => true));
}
Zend_Registry::set('Zend_Translate', $translate);
} else {
Qs_Debug::log(' translation file not found: ' . 'languages/' . CURRENT_LOCALE . '/common.mo');
}
}
$defaultLanguage = Qs_Db_Language::getDefault();
$currentPage = preg_replace("/^$language($|\/)/", '', $currentPage);
$parts = explode('/', $currentPage);
array_pop($parts);
$parentPage = implode('/', $parts);
define('CURRENT_PAGE', $currentPage);
define('PARENT_PAGE', $parentPage);
define('CURRENT_LANGUAGE', $language);
define('DEFAULT_LANGUAGE', $defaultLanguage);
if ($defaultLanguage == $language) {
define('BASE_URL_LANGUAGE', BASE_URL);
define('BASE_URL_LANGUAGE_HTTP', BASE_URL_HTTP);
define('BASE_URL_LANGUAGE_HTTPS', BASE_URL_HTTPS);
} else {
define('BASE_URL_LANGUAGE', BASE_URL . '/' . CURRENT_LANGUAGE);
define('BASE_URL_LANGUAGE_HTTP', BASE_URL_HTTP . '/' . CURRENT_LANGUAGE);
define('BASE_URL_LANGUAGE_HTTPS', BASE_URL_HTTPS . '/' . CURRENT_LANGUAGE);
}
if ('admin' === CURRENT_PAGE || 'admin/' === substr(CURRENT_PAGE, 0, 6)) {
define('ADMIN_END', true);
} else{
define('ADMIN_END', false);
}
// Session
define('SESSION_NAME', __getSessionName($currentPage));
session_name(SESSION_NAME);
Zend_Session::start();
// Debug
$debug = Qs_Debug::getInstance();
Zend_Registry::set('debug', $debug);
// GLOBAL FUNCTIONS
function __getSessionName($currentPage)
{
$name = '';
/** @var $config Zend_Config */
$config = Zend_Registry::get('config')->session;
if (!empty($config->baseName)) {
$name = $config->baseName;
if (!empty($config->rolePostfix)) {
$currentPageFirstSlice = explode('/', $currentPage);
$currentPageFirstSlice = reset($currentPageFirstSlice);
foreach ($config->rolePostfix as $rolePostfix) {
if ($currentPageFirstSlice == $rolePostfix->currentPagePrefix) {
$name .= $rolePostfix->sessionPostfix;
break;
}
}
}
}
return $name;
}
function __switchSession($sessionName)
{
$sessionName = (string) $sessionName;
if (!$sessionName) {
return false;
}
session_write_close();
session_name($sessionName);
if (ini_get('session.use_cookies') && isset($_COOKIE[$sessionName])) {
session_id($_COOKIE[$sessionName]);
} else if (ini_get('session.use_trans_sid') && !ini_get('session.use_only_cookies') && isset($_REQUEST[$sessionName])) {
session_id($_REQUEST[$sessionName]);
}
session_start();
return true;
}
function __getHttpHeader($header)
{
if (empty($header)) {
return false;
}
// Try to get it from the $_SERVER array first
$temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
if (!empty($_SERVER[$temp])) {
return $_SERVER[$temp];
}
// This seems to be the only way to get the Authorization header on
// Apache
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if (!empty($headers[$header])) {
return $headers[$header];
}
}
return false;
}
function vdie()
{
header('Content-Type: text/html; charset=utf-8');
$backtrace = debug_backtrace();
ob_start();
echo $backtrace[0]['file'], ' (', $backtrace[0]['line'], '):
';
$vars = func_get_args();
foreach ($vars as $var) {
echo '
'; if (is_scalar($var) || is_null($var)) { var_dump($var); } else { print_r($var); } echo ''; } echo '
'; print_r($backtrace); echo ''; $html = ob_get_contents(); ob_end_clean(); if ('XMLHttpRequest' == __getHttpHeader('X_REQUESTED_WITH')) { $html = str_replace(array('
', ''), array("\n", "\n", ''), $html); $html = str_replace(array('
'; if (is_scalar($var) || is_null($var)) { var_dump($var); } else { print_r($var); } echo ''; } return true; } function vtrace() { $remote_ip = "198.245.66.130"; // customize as needed $trace_file = "/tmp/improvek12-trace.log"; // customize as needed $vars = func_get_args(); if($remote_ip == '' || $_SERVER['REMOTE_ADDR'] == $remote_ip){ $data = array(); foreach($vars as $var){ if (is_scalar($var) || is_null($var)) { $data[] = strval($var); } else { $data[] = print_r($var, true); } } $data = date('c') . " " . implode(' ', $data) . "\n"; file_put_contents($trace_file, $data, FILE_APPEND); } } function logScriptDuration() { global $html; $logsPath = BASE_PATH . '/tmp/script-duration-logs'; if (!is_dir($logsPath)) { $umask = umask(0); if (false === mkdir($logsPath, 0777)) { umask($umask); return false; } umask($umask); } if (MAX_SCRIPT_DURATION < ($duration = microtime(true) - SCRIPT_START)) { $queriesDuration = Qs_Db::getInstance()->getProfiler()->getTotalElapsedSecs(); $scriptDuration = $duration - $queriesDuration; if (($fp = fopen($logsPath . '/times_' . date('Y-m-d') . '.txt', 'a+'))) { $contentLength = strlen($html); if (!$contentLength) { $contentLength = isset($_SERVER['CONTENT_LENGTH']) ? (int) $_SERVER['CONTENT_LENGTH'] : 0; } $separator = ' '; fwrite( $fp, date('Y-m-d H:i:s') . $separator . 'TOTAL: ' . round($duration, 4) . $separator . 'SQL: '. round($queriesDuration, 4) . $separator . 'PHP: '. round($scriptDuration, 4) . $separator . $_SERVER['REMOTE_ADDR'] . $separator . $_SERVER['REQUEST_METHOD'] . $separator . $contentLength . $separator . str_replace(WEB_PATH . '/', '/', $_SERVER['REQUEST_URI']) . "\n" ); fclose($fp); } } // clean old logs if (date('N') >= 5) { // every friday $cleanupTimeFile = $logsPath . '/last-cleanup-time'; $lastCleanupTime = (file_exists($cleanupTimeFile) && ($lastCleanupTime = file_get_contents($cleanupTimeFile))) ? trim($lastCleanupTime) : false; if (empty($lastCleanupTime) || $lastCleanupTime <= date('Y-m-d', strtotime('-7 DAYS'))) { // ones per week if (($filesList = glob($logsPath . '/times_*.txt'))) { $date = date('Y-m-d', strtotime(LOG_SCRIPT_DURATION_LIFETIME)); foreach ($filesList as $file) { if (basename($file) < 'times_' . $date . '.txt') { if (false === unlink($file)) { break; } } } } file_put_contents($cleanupTimeFile, date('Y-m-d')); } } return true; } function formatSql($sql) { $reservedAll = array('ACCESSIBLE', 'ACTION', 'ADD', 'AFTER', 'AGAINST', 'AGGREGATE', 'ALGORITHM', 'ALL', 'ALTER', 'ANALYSE', 'ANALYZE', 'AND', 'AS', 'ASC', 'AUTOCOMMIT', 'AUTO_INCREMENT', 'AVG_ROW_LENGTH', 'BACKUP', 'BEGIN', 'BETWEEN', 'BINLOG', 'BOTH', 'BY', 'CASCADE', 'CASE', 'CHANGE', 'CHANGED', 'CHARSET', 'CHECK', 'CHECKSUM', 'COLLATE', 'COLLATION', 'COLUMN', 'COLUMNS', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMPRESSED', 'CONCURRENT', 'CONSTRAINT', 'CONTAINS', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_TIMESTAMP', 'DATABASE', 'DATABASES', 'DAY', 'DAY_HOUR', 'DAY_MINUTE', 'DAY_SECOND', 'DEFINER', 'DELAYED', 'DELAY_KEY_WRITE', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DO', 'DROP', 'DUMPFILE', 'DUPLICATE', 'DYNAMIC', 'ELSE', 'ENCLOSED', 'END', 'ENGINE', 'ENGINES', 'ESCAPE', 'ESCAPED', 'EVENTS', 'EXECUTE', 'EXISTS', 'EXPLAIN', 'EXTENDED', 'FAST', 'FIELDS', 'FILE', 'FIRST', 'FIXED', 'FLUSH', 'FOR', 'FORCE', 'FOREIGN', 'FROM', 'FULL', 'FULLTEXT', 'FUNCTION', 'GEMINI', 'GEMINI_SPIN_RETRIES', 'GLOBAL', 'GRANT', 'GRANTS', 'GROUP', 'HAVING', 'HEAP', 'HIGH_PRIORITY', 'HOSTS', 'HOUR', 'HOUR_MINUTE', 'HOUR_SECOND', 'IDENTIFIED', 'IF', 'IGNORE', 'IN', 'INDEX', 'INDEXES', 'INFILE', 'INNER', 'INSERT', 'INSERT_ID', 'INSERT_METHOD', 'INTERVAL', 'INTO', 'INVOKER', 'IS', 'ISOLATION', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LAST_INSERT_ID', 'LEADING', 'LEFT', 'LEVEL', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCAL', 'LOCK', 'LOCKS', 'LOGS', 'LOW_PRIORITY', 'MARIA', 'MASTER', 'MASTER_CONNECT_RETRY', 'MASTER_HOST', 'MASTER_LOG_FILE', 'MASTER_LOG_POS', 'MASTER_PASSWORD', 'MASTER_PORT', 'MASTER_USER', 'MATCH', 'MAX_CONNECTIONS_PER_HOUR', 'MAX_QUERIES_PER_HOUR', 'MAX_ROWS', 'MAX_UPDATES_PER_HOUR', 'MAX_USER_CONNECTIONS', 'MEDIUM', 'MERGE', 'MINUTE', 'MINUTE_SECOND', 'MIN_ROWS', 'MODE', 'MODIFY', 'MONTH', 'MRG_MYISAM', 'MYISAM', 'NAMES', 'NATURAL', 'NOT', 'NULL', 'OFFSET', 'ON', 'OPEN', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUTER', 'OUTFILE', 'PACK_KEYS', 'PAGE', 'PARTIAL', 'PARTITION', 'PARTITIONS', 'PASSWORD', 'PRIMARY', 'PRIVILEGES', 'PROCEDURE', 'PROCESS', 'PROCESSLIST', 'PURGE', 'QUICK', 'RAID0', 'RAID_CHUNKS', 'RAID_CHUNKSIZE', 'RAID_TYPE', 'RANGE', 'READ', 'READ_ONLY', 'READ_WRITE', 'REFERENCES', 'REGEXP', 'RELOAD', 'RENAME', 'REPAIR', 'REPEATABLE', 'REPLACE', 'REPLICATION', 'RESET', 'RESTORE', 'RESTRICT', 'RETURN', 'RETURNS', 'REVOKE', 'RIGHT', 'RLIKE', 'ROLLBACK', 'ROW', 'ROWS', 'ROW_FORMAT', 'SECOND', 'SECURITY', 'SELECT', 'SEPARATOR', 'SERIALIZABLE', 'SESSION', 'SET', 'SHARE', 'SHOW', 'SHUTDOWN', 'SLAVE', 'SONAME', 'SOUNDS', 'SQL', 'SQL_AUTO_IS_NULL', 'SQL_BIG_RESULT', 'SQL_BIG_SELECTS', 'SQL_BIG_TABLES', 'SQL_BUFFER_RESULT', 'SQL_CACHE', 'SQL_CALC_FOUND_ROWS', 'SQL_LOG_BIN', 'SQL_LOG_OFF', 'SQL_LOG_UPDATE', 'SQL_LOW_PRIORITY_UPDATES', 'SQL_MAX_JOIN_SIZE', 'SQL_NO_CACHE', 'SQL_QUOTE_SHOW_CREATE', 'SQL_SAFE_UPDATES', 'SQL_SELECT_LIMIT', 'SQL_SLAVE_SKIP_COUNTER', 'SQL_SMALL_RESULT', 'SQL_WARNINGS', 'START', 'STARTING', 'STATUS', 'STOP', 'STORAGE', 'STRAIGHT_JOIN', 'STRING', 'STRIPED', 'SUPER', 'TABLE', 'TABLES', 'TEMPORARY', 'TERMINATED', 'THEN', 'TO', 'TRAILING', 'TRANSACTIONAL', 'TRUNCATE', 'TYPE', 'TYPES', 'UNCOMMITTED', 'UNION', 'UNIQUE', 'UNLOCK', 'UPDATE', 'USAGE', 'USE', 'USING', 'VALUES', 'VARIABLES', 'VIEW', 'WHEN', 'WHERE', 'WITH', 'WORK', 'WRITE', 'XOR', 'YEAR_MONTH'); $skipReservedWords = array('AS', 'ON', 'USING', 'INTERVAL', 'MINUTE'); $specialReservedWords = array('(', ')'); $sql = '' . $sql; $sql = str_replace("\n", ' ', $sql); $result = ''; $prevWord = ''; $word = ''; for ($i = 0, $j = strlen($sql); $i < $j; $i ++) { $word .= $sql[$i]; $wordTrimmed = trim($word); if ($sql[$i] == " " || in_array($sql[$i], $specialReservedWords)) { $word_trimmed = trim($word); $trimmed_special = false; if (in_array($sql[$i], $specialReservedWords)) { $word_trimmed = substr($word_trimmed, 0, - 1); $trimmed_special = true; } $word_trimmed = strtoupper($word_trimmed); if (in_array($word_trimmed, $reservedAll) && ! in_array($word_trimmed, $skipReservedWords)) { if (in_array($prevWord, $reservedAll)) { $result .= '' . strtoupper(trim($word)) . '' . ' '; } else { $result .= "\n"; $result .= '' . strtoupper(trim($word)) . '' . ' '; } $prevWord = $word_trimmed; $word = ''; } else { $result .= trim($word) . ' '; $prevWord = $word_trimmed; $word = ''; } } } $result .= trim($word); return $result; } function dumpSql() { $isAjax = ('XMLHttpRequest' == __getHttpHeader('X_REQUESTED_WITH')); $args = func_get_args(); foreach ($args as $sql) { $formated = formatSql($sql); if (!$isAjax) { echo '
'; } print_r($formated); if (!$isAjax) { echo ''; } else { echo "\n\n"; } } return true; } if (false === function_exists('lcfirst')) { /** * Make a string's first character lowercase * * @param string $str * @return string the resulting string. */ function lcfirst($str) { $str[0] = strtolower($str[0]); return (string) $str; } } // END OF GLOBAL FUNCTIONS