From 3595dbbf1aac5d7ecf1bc5eba74c7653c3c6fd7d Mon Sep 17 00:00:00 2001 From: JohnJ Date: Fri, 24 May 2013 14:49:52 +0700 Subject: [PATCH 1/4] add template helper --- application/helpers/template_helper.php | 161 ++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 application/helpers/template_helper.php diff --git a/application/helpers/template_helper.php b/application/helpers/template_helper.php new file mode 100644 index 0000000000..6c23a33e21 --- /dev/null +++ b/application/helpers/template_helper.php @@ -0,0 +1,161 @@ + + * Date: 08.05.13 + */ + +if (!function_exists('include_file')) { + /** + * Рус: Выводит содержимое шаблона внутри другого шаблона + * Анг: Write template content in other template + * @exapmle: {include_file('templatename', array('var1' => 'value1', 'var2' => 'value2'))} + * @param string $filename - имя файла + * @param array $vars - переданные в шаблон переменные + * @return null + */ + function include_file($filename = '', array $vars = array()) { + $CI =& get_instance(); + $templator = $CI->template; + + $filename = (strrpos($filename, '.tpl') == strlen($filename) - 4) ? substr($filename, 0, -4) : $filename; + + $templator->add_array($vars); + $templator->display($filename); + } +} + +if (!function_exists('smarty_make_timestamp')) { + /** + * Рус: Внутренняя функция Smarty по обработке входной строки даты/времени. + * Анг: Smarty-function for processing string parameter for date/time + * @param $string - дата в формате строки или UNIX_TIMESTAMP (из MySQL) + * @return int|string - дата в формате UNIX_TIMESTAMP + */ + function smarty_make_timestamp($string) + { + if(empty($string)) { + $string = "now"; + } + $time = strtotime($string); + if (is_numeric($time) && $time != -1) + return $time; + + // is mysql timestamp format of YYYYMMDDHHMMSS? + if (preg_match('/^\d{14}$/', $string)) { + $time = mktime(substr($string,8,2),substr($string,10,2),substr($string,12,2), + substr($string,4,2),substr($string,6,2),substr($string,0,4)); + + return $time; + } + + // couldn't recognize it, try to return a time + $time = (int) $string; + if ($time > 0) + return $time; + else + return time(); + } +} + +if (!function_exists('date_format_likeuser_rus')) { + /** + * Рус: Выводит время в указанном формате. Во многом аналогичная php функции date, за исключением того, что вывод русифицирован и добавлены новые обозначения в форматной строке. + * Принцип: преимущественно названия выводятся с большой буквы. Если нужны все маленькие (например, "3 января"), то нужно использовать функцию toLowerCase() + * Особенности форматной строки (чем отличается от пхп-функции date): + * M - три первые буквы месяца + * F - полное название месяца в инфинитиве + * f - полное название месяца в родительном падеже + * a - относительная дата (сегодня, вчера) + * A - относительная дата (Сегодня, Вчера) + * D - кратко дни недели (Пн, Вт, ...) + * l - полно дни недели (Понедельник, Вторник, ...) + * Анг: php function date-analog for russian language + * @param $string - дата и время в строковом формате, либо в формате UNIX_TIMESTAMP (из MySQL) + * @param string $format - формат, в котором выводится дата + * @param string $default_format - формат, в котором выводится дата, если предыдущий формат вывести не удалось (если там используется a или A) + * @return string - дата по формату + */ + function date_format_likeuser_rus($string, $format = 'd M Y', $default_format = 'd M Y') { + if ($string == '') return ''; + $timestamp = smarty_make_timestamp($string); + + $rus_words = array( + 'M' => array('code' => 'n', + 'values' => array('', 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'), + ), + 'F' => array('code' => 'n', + 'values' => array('', 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'), + ), + 'f' => array('code' => 'n', + 'values' => array('', 'Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря'), + ), + 'a' => array('code' => '', + 'values' => array('cегодня', 'вчера'), + ), + 'A' => array('code' => '', + 'values' => array('Сегодня', 'Вчера'), + ), + 'D' => array('code' => 'w', + 'values' => array('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'), + ), + 'l' => array('code' => 'w', + 'values' => array('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'), + ), + ); + + $result = ""; + for ($i = 0; $i < strlen($format); $i++) { + $symbol = $format{$i}; + if (array_key_exists($symbol, $rus_words)) { + if (!empty($rus_words[$symbol]['code'])) { + $id = date($rus_words[$symbol]['code'], $timestamp); + if (is_numeric($id) && array_key_exists($id, $rus_words[$symbol]['values'])) { + $result .= $rus_words[$symbol]['values'][$id]; + } + } else { + $id = 2; + $today = mktime(0, 0, 0, date('m'), date('d'), date('Y')); + if ($timestamp >= $today) { + $id = 0; + } elseif ($timestamp >= $today - 86400) { + $id = 1; + } + + if (array_key_exists($id, $rus_words[$symbol]['values'])) { + $result .= $rus_words[$symbol]['values'][$id]; + } else { + $format = str_replace($symbol, $default_format, $format); + $i--; + } + } + } else { + $result .= date($symbol, $timestamp); + } + } + + return $result; + } +} + +if (!function_exists('cutLongWords')) { + /** + * Рус: обрезает длинные слова, подставляя в конце "..." + * Анг: cut long words + * @param $text - текст, который нужно уберечь от длинных слов + * @param int $max_long - разрешённая длина слова + * @param string $replace - шаблон замены обрезанной части. Тут ?0 означает всё слово целиком, а ?1 - необрезанная часть (начинается с ?, так как движок imageCMS ругается, если использовать знак $ в шаблоне, даже если в строке). + * @return mixed|string + */ + function cutLongWords($text, $max_long = 10, $replace = '?1...') { + if (!is_string($text)) { + $text = (string)$text; + } + $max_long = (int)$max_long; + if ($max_long <= 0) return $text; + if (!is_string($replace)) { + $replace = '?1...'; + } + $replace = preg_replace('/\?(\d+)/', '\$$1', $replace); + return preg_replace('/([^\s]{' . $max_long . '})[^\s]+/', $replace, $text); + } +} \ No newline at end of file From d4eb7d5288ea5a101d9a42e84892bcd855c717eb Mon Sep 17 00:00:00 2001 From: JohnJ Date: Fri, 24 May 2013 15:13:50 +0700 Subject: [PATCH 2/4] upgrade registerStyle and registerScript functions --- .../modules/CMSFactory/assetManager.php | 91 ++++++++++++------- 1 file changed, 56 insertions(+), 35 deletions(-) diff --git a/application/modules/CMSFactory/assetManager.php b/application/modules/CMSFactory/assetManager.php index 6aa596384f..3f95dc57a9 100755 --- a/application/modules/CMSFactory/assetManager.php +++ b/application/modules/CMSFactory/assetManager.php @@ -6,6 +6,8 @@ * @copyright ImageCMS (c) 2013, Kaero */ class assetManager { + const REGISTER_FILE_TYPE_STYLE = 'style'; + const REGISTER_FILE_TYPE_SCRIPT = 'script'; protected static $_BehaviorInstance; @@ -25,23 +27,19 @@ private function __clone() { */ public function Get_trace($list = 'first_file') { $trace = debug_backtrace(); - if ($list == 'first_file') - { + if ($list == 'first_file') { $paths = explode(DIRECTORY_SEPARATOR, $trace[0]['file']); return $paths[count($paths) - 2]; } - if ($list == 'first') - { + if ($list == 'first') { return $trace[0]; } - if ($list == 'all') - { + if ($list == 'all') { return $trace; } - if (is_numeric($list)) - { + if (is_numeric($list)) { return $trace[$list]; } // exit('error get trace file. (assetManager)'); @@ -66,48 +64,71 @@ public function setData($item, $value = null) { /** * @return assetManager * @access public - * @author Kaero + * @author Kaero / modified by JohnJ * @copyright ImageCMS (c) 2013, Kaero */ - public function registerScript($name) { - $paths = $this->Get_trace('first_file'); - if (is_array($name) and count($name) >= 1 ) - { - foreach ($name as $v) - { - \CI_Controller::get_instance()->template->registerJsFile(APPPATH . 'modules/' . $paths . '/assets/js/' . $v . '.js', 'after'); - } - } - else - { - \CI_Controller::get_instance()->template->registerJsFile(APPPATH . 'modules/' . $paths . '/assets/js/' . $name . '.js', 'after'); + public function registerScript($name, $pattern = 'default') { + $paths = $this->Get_trace('first_file'); + $pattern = $this->processingPatternName($pattern); + + if (!is_array($name)) $name = array($name); + + foreach ($name as $v) { + $this->registerByType(self::REGISTER_FILE_TYPE_SCRIPT, APPPATH . 'modules/' . $paths . '/assets' . $pattern . '/js/' . $v . '.js'); } + return $this; } /** * @return assetManager * @access public - * @author Kaero + * @author Kaero / modified by JohnJ * @copyright ImageCMS (c) 2013, Kaero */ - public function registerStyle($name) { - $paths = $this->Get_trace('first_file'); - - if (is_array($name) and count($name) >= 1 ) - { - foreach ($name as $v) - { - \CI_Controller::get_instance()->template->registerCssFile(APPPATH . 'modules/' . $paths . '/assets/css/' . $v . '.css', 'before'); - } - } - else - { - \CI_Controller::get_instance()->template->registerCssFile(APPPATH . 'modules/' . $paths . '/assets/css/' . $name . '.css', 'before'); + public function registerStyle($name, $pattern = 'default') { + $paths = $this->Get_trace('first_file'); + $pattern = $this->processingPatternName($pattern); + + if (!is_array($name)) $name = array($name); + + foreach ($name as $v) { + \CI_Controller::get_instance()->template->registerCssFile(APPPATH . 'modules/' . $paths . '/assets' . $pattern . '/css/' . $v . '.css', 'before'); } + return $this; } + /** + * Includes some register* functions + * @param $type - one of constants assetManager::REGISTER_FILE_TYPE_* + * @param $path - path to file + * @return $this + * @author JohnJ + * @copyright Free + */ + private function registerByType($type, $path) { + if ($type == self::REGISTER_FILE_TYPE_SCRIPT) { + \CI_Controller::get_instance()->template->registerJsFile($path, 'after'); + return $this; + } elseif ($type == self::REGISTER_FILE_TYPE_STYLE) { + \CI_Controller::get_instance()->template->registerCssFile($path, 'before'); + return $this; + } + throwException('Unknown register file type: "' . $type . '" for path "' . $path . '"'); + } + + /** + * Change pattern string for using in path + * @param $pattern + * @return string + * @author JohnJ + * @copyright Free + */ + private function processingPatternName($pattern) { + return !is_string($pattern) || empty($pattern) ? '' : '/' . trim($pattern, '/\\'); + } + /** * Render Admin view * @param string $tpl Template file name From 84b2c02362ac97961e2761065dded8c9e07b0b93 Mon Sep 17 00:00:00 2001 From: JohnJ Date: Fri, 24 May 2013 15:22:01 +0700 Subject: [PATCH 3/4] ugrade code --- .../modules/CMSFactory/assetManager.php | 23 +------------------ 1 file changed, 1 insertion(+), 22 deletions(-) diff --git a/application/modules/CMSFactory/assetManager.php b/application/modules/CMSFactory/assetManager.php index 3f95dc57a9..ba9ede3db5 100755 --- a/application/modules/CMSFactory/assetManager.php +++ b/application/modules/CMSFactory/assetManager.php @@ -6,8 +6,6 @@ * @copyright ImageCMS (c) 2013, Kaero */ class assetManager { - const REGISTER_FILE_TYPE_STYLE = 'style'; - const REGISTER_FILE_TYPE_SCRIPT = 'script'; protected static $_BehaviorInstance; @@ -74,7 +72,7 @@ public function registerScript($name, $pattern = 'default') { if (!is_array($name)) $name = array($name); foreach ($name as $v) { - $this->registerByType(self::REGISTER_FILE_TYPE_SCRIPT, APPPATH . 'modules/' . $paths . '/assets' . $pattern . '/js/' . $v . '.js'); + \CI_Controller::get_instance()->template->registerJsFile(APPPATH . 'modules/' . $paths . '/assets' . $pattern . '/js/' . $v . '.js', 'after'); } return $this; @@ -99,25 +97,6 @@ public function registerStyle($name, $pattern = 'default') { return $this; } - /** - * Includes some register* functions - * @param $type - one of constants assetManager::REGISTER_FILE_TYPE_* - * @param $path - path to file - * @return $this - * @author JohnJ - * @copyright Free - */ - private function registerByType($type, $path) { - if ($type == self::REGISTER_FILE_TYPE_SCRIPT) { - \CI_Controller::get_instance()->template->registerJsFile($path, 'after'); - return $this; - } elseif ($type == self::REGISTER_FILE_TYPE_STYLE) { - \CI_Controller::get_instance()->template->registerCssFile($path, 'before'); - return $this; - } - throwException('Unknown register file type: "' . $type . '" for path "' . $path . '"'); - } - /** * Change pattern string for using in path * @param $pattern From 0da8e996c6449fe1a59fbae8dfe450b2a63c8286 Mon Sep 17 00:00:00 2001 From: JohnJ Date: Sat, 25 May 2013 21:20:43 +0700 Subject: [PATCH 4/4] pattern in assetManager and template_helper for development branch --- .../modules/CMSFactory/assetManager.php | 107 +++++++++--------- 1 file changed, 53 insertions(+), 54 deletions(-) diff --git a/application/modules/CMSFactory/assetManager.php b/application/modules/CMSFactory/assetManager.php index a859d6ac82..afea2002b9 100755 --- a/application/modules/CMSFactory/assetManager.php +++ b/application/modules/CMSFactory/assetManager.php @@ -7,9 +7,11 @@ */ class assetManager { + public $useCompress = false; + public $activePattern = null; + protected static $_BehaviorInstance; protected $callMapp = null; - protected $useCompress = false; private function __construct() { @@ -62,28 +64,28 @@ public function appendData($item, $value) { * @return assetManager * @access public * @author Kaero - * @param type $name - * @param type $useCompress + * @param string $name + * @param string $pattern * @return \CMSFactory\assetManager * @copyright ImageCMS (c) 2013, Kaero */ - public function registerScript($name, $useCompress = FALSE) { + public function registerScript($name, $pattern = 'default') { /** Start. Load JS file into template */ - if ($useCompress) - \CI_Controller::get_instance()->template->registerJsScript('', 'after'); + if ($this->useCompress) + \CI_Controller::get_instance()->template->registerJsScript('', 'after'); else - \CI_Controller::get_instance()->template->registerJsFile($this->buildScriptPath($name), 'after'); + \CI_Controller::get_instance()->template->registerJsFile($this->buildScriptPath($name, $pattern), 'after'); return $this; } - public function registerScriptWithoutTemplate($name){ - $script = '/' . $this->buildScriptPath($name); + public function registerScriptWithoutTemplate($name, $pattern = 'default') { + $script = '/' . $this->buildScriptPath($name, $pattern); $this->setData(array($name=>$script)); } - public function registerStyleWithoutTemplate($name){ - $script = '/' . $this->buildStylePath($name); + public function registerStyleWithoutTemplate($name, $pattern = 'default') { + $script = '/' . $this->buildStylePath($name, $pattern); $this->setData(array($name=>$script)); } @@ -92,14 +94,13 @@ public function registerStyleWithoutTemplate($name){ * @return assetManager * @access public * @author a.gula - * @param type $script - * @param type $useCompress + * @param string $script * @return \CMSFactory\assetManager * @copyright ImageCMS (c) 2013, a.gula */ - public function registerJsScript($script, $useCompress = FALSE) { + public function registerJsScript($script) { /** Start. Load JS script into template */ - if ($useCompress) + if ($this->useCompress) \CI_Controller::get_instance()->template->registerJsScript('', 'after'); else \CI_Controller::get_instance()->template->registerJsScript('', 'after'); @@ -111,17 +112,17 @@ public function registerJsScript($script, $useCompress = FALSE) { * @return assetManager * @access public * @author Kaero - * @param type $name - * @param type $useCompress + * @param string $name + * @param string $pattern * @return \CMSFactory\assetManager * @copyright ImageCMS (c) 2013, Kaero */ - public function registerStyle($name, $useCompress = FALSE) { + public function registerStyle($name, $pattern = 'default') { /** Start. Load file into template */ - if ($useCompress) - \CI_Controller::get_instance()->template->registerCss('', 'before'); + if ($this->useCompress) + \CI_Controller::get_instance()->template->registerCss('', 'before'); else - \CI_Controller::get_instance()->template->registerCssFile($this->buildStylePath($name), 'before'); + \CI_Controller::get_instance()->template->registerCssFile($this->buildStylePath($name, $pattern), 'before'); return $this; } @@ -131,13 +132,12 @@ public function registerStyle($name, $useCompress = FALSE) { * @return assetManager * @access public * @author a.gula - * @param type $css - * @param type $useCompress + * @param string $css * @copyright ImageCMS (c) 2013, a.gula */ - public function registerStyleStr($css, $useCompress = FALSE) { + public function registerStyleStr($css) { /** Start. Load file into template */ - if ($useCompress) + if ($this->useCompress) \CI_Controller::get_instance()->template->registerCss('', 'before'); else \CI_Controller::get_instance()->template->registerCss('', 'before'); @@ -156,7 +156,7 @@ public function registerStyleStr($css, $useCompress = FALSE) { public function renderAdmin($tpl) { try { /** Start. If file doesn't exists thorow exception */ - file_exists($this->buildAdminTemplatePath($tpl) . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/admin/%s.tpl', $this->getTrace(), $tpl)); + file_exists($this->buildTemplatePath($tpl, 'admin') . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/admin/%s.tpl', $this->getTrace(), $tpl)); /** Start. Load template file */ \CI_Controller::get_instance()->template->show('file:' . $this->buildAdminTemplatePath($tpl)); @@ -173,13 +173,13 @@ public function renderAdmin($tpl) { * @author Kaero * @copyright ImageCMS (c) 2013, Kaero */ - public function render($tpl, $ignoreWrap = FALSE) { + public function render($tpl, $ignoreWrap = FALSE, $pattern = 'default') { try { /** Start. If file doesn't exists thorow exception */ - file_exists($this->buildTemplatePath($tpl) . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/%s.tpl', $this->getTrace(), $tpl)); + file_exists($this->buildTemplatePath($tpl, $pattern) . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/%s.tpl', $this->getTrace(), $tpl)); /** Start. Load template file */ - \CI_Controller::get_instance()->template->show('file:' . $this->buildTemplatePath($tpl), !$ignoreWrap); + \CI_Controller::get_instance()->template->show('file:' . $this->buildTemplatePath($tpl, $pattern), !$ignoreWrap); } catch (\Exception $exc) { log_message('error', $exc->getMessage()); show_error($exc->getMessage(), 500, 'An Template Error Was Encountered'); @@ -188,18 +188,18 @@ public function render($tpl, $ignoreWrap = FALSE) { /** Render public view * @param string $tpl Template file name - * @return void + * @return string * @access public * @author Kaero * @copyright ImageCMS (c) 2013, Kaero */ - public function fetchTemplate($tpl) { + public function fetchTemplate($tpl, $pattern = 'default') { try { /** Start. If file doesn't exists thorow exception */ - file_exists($this->buildTemplatePath($tpl) . '.tpl') OR throwException('Can\'t load template file: ' . $paths . DIRECTORY_SEPARATOR . $tpl . '.tpl'); + file_exists($this->buildTemplatePath($tpl, $pattern) . '.tpl') OR throwException('Can\'t load template file: ' . $paths /* ?? what is $paths ?? */ . DIRECTORY_SEPARATOR . $tpl . '.tpl'); /** Start. Return template file */ - return \CI_Controller::get_instance()->template->fetch('file:' . $this->buildTemplatePath($tpl)); + return \CI_Controller::get_instance()->template->fetch('file:' . $this->buildTemplatePath($tpl, $pattern)); } catch (\Exception $exc) { log_message('error', $exc->getMessage()); show_error($exc->getMessage(), 500, 'An Template Error Was Encountered'); @@ -249,43 +249,43 @@ private function getTrace($list = 'first_file') { * @access private * @copyright ImageCMS (c) 2013, Kaero */ - private function buildTemplatePath($tpl) { - return sprintf('%smodules/%s/assets/%s', APPPATH, $this->getTrace(), $tpl); + private function buildTemplatePath($tpl, $pattern) { + return sprintf('%smodules/%s/assets%s/%s', APPPATH, $this->getTrace(), $this->processingPatternName($pattern), $tpl); } /** - * Return formated path + * Return formated path for JS - script files * @return string * @access private * @copyright ImageCMS (c) 2013, Kaero */ - private function buildAdminTemplatePath($tpl) { - return sprintf('%smodules/%s/assets/admin/%s', APPPATH, $this->getTrace(), $tpl); + private function buildScriptPath($tpl, $pattern) { + return sprintf('%smodules/%s/assets%s/js/%s.js', APPPATH, $this->getTrace(), $this->processingPatternName($pattern), $tpl); } /** - * Return formated path for JS - script files + * Return formated path for css * @return string * @access private * @copyright ImageCMS (c) 2013, Kaero */ - private function buildScriptPath($tpl) { - return sprintf('%smodules/%s/assets/js/%s.js', APPPATH, $this->getTrace(), $tpl); + private function buildStylePath($tpl, $pattern) { + return sprintf('%smodules/%s/assets%s/css/%s.css', APPPATH, $this->getTrace(), $this->processingPatternName($pattern), $tpl); } /** - * Return formated path for css + * Return formatted pattern name for include it in file path + * @param string $pattern * @return string - * @access private - * @copyright ImageCMS (c) 2013, Kaero */ - private function buildStylePath($tpl) { - return sprintf('%smodules/%s/assets/css/%s.css', APPPATH, $this->getTrace(), $tpl); + private function processingPatternName($pattern) { + if (is_string($this->activePattern)) $pattern = $this->activePattern; + return !is_string($pattern) || empty($pattern) ? '' : '/' . trim($pattern, '\//'); } /** * Compressing js file - * @param type $js text of js + * @param string $js text of js * @copyright ImageCMS (c) 2013, a.gula */ private function compressJs($js) { @@ -301,18 +301,17 @@ private function compressJs($js) { /** * Compressing css file - * @param type $css text of css file + * @param string $css text of css file * @copyright ImageCMS (c) 2013, a.gula */ private function compressCss($css) { $css = preg_replace('#\s+#', ' ', $css); $css = preg_replace('#/\*.*?\*/#s', '', $css); - $css = str_replace('; ', ';', $css); - $css = str_replace(': ', ':', $css); - $css = str_replace(' {', '{', $css); - $css = str_replace('{ ', '{', $css); - $css = str_replace(', ', ',', $css); - $css = str_replace('} ', '}', $css); + foreach (str_split(';:{},') as $symbol) { + $css = str_replace(' ' . $symbol, $symbol, $css); + $css = str_replace($symbol . ' ', $symbol, $css); + } + $css = str_replace('- ', '-', $css); $css = str_replace(';}', '}', $css); return $css;