quickfw-git Mailing List for QuickFramework (Page 3)
Brought to you by:
ivan1986,
seriousdron
You can subscribe to this list here.
2010 |
Jan
|
Feb
|
Mar
(9) |
Apr
(25) |
May
(22) |
Jun
(22) |
Jul
(15) |
Aug
(16) |
Sep
(4) |
Oct
(9) |
Nov
(9) |
Dec
(6) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2011 |
Jan
(5) |
Feb
(3) |
Mar
(2) |
Apr
(11) |
May
(2) |
Jun
(2) |
Jul
(1) |
Aug
(3) |
Sep
|
Oct
(2) |
Nov
|
Dec
|
From: Ivan1986 <iva...@us...> - 2010-10-05 22:39:54
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 9519e9dc62a721afbe5b902fc62194454542f9fb (commit) from c83e6c80852b7b5959c0a490da165e1859a9ef33 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 9519e9dc62a721afbe5b902fc62194454542f9fb Author: Ivan Borzenkov <iva...@li...> Date: Wed Oct 6 02:39:15 2010 +0400 Добавил несколько deprecated diff --git a/QFW/QuickFW/Cache.php b/QFW/QuickFW/Cache.php index 3fe6f81..f369fd1 100644 --- a/QFW/QuickFW/Cache.php +++ b/QFW/QuickFW/Cache.php @@ -209,6 +209,7 @@ class Cache */ function &getCache($backend='',$opt=array(),$tags=false,$namespace='') { + trigger_error('Используйте Cache::get()', E_USER_DEPRECATED); global $config; static $cachers=array(); if ($backend=='') diff --git a/QFW/QuickFW/Plugs.php b/QFW/QuickFW/Plugs.php index 371d893..6bbd397 100644 --- a/QFW/QuickFW/Plugs.php +++ b/QFW/QuickFW/Plugs.php @@ -17,6 +17,7 @@ class QuickFW_Plugs public function baseUrl() { + trigger_error('Используйте Url::base()', E_USER_DEPRECATED); return QFW::$config['redirection']['baseUrl']; } @@ -25,8 +26,12 @@ class QuickFW_Plugs return $this->siteUrl(QFW::$router->delDef($url), $get); } + /** + * @deprecated Используйте Url::... + */ public function siteUrl($url, $get='') { + trigger_error('Используйте Url::...', E_USER_DEPRECATED); if (QFW::$config['redirection']['delDef']) $url = QFW::$router->delDef($url); if (QFW::$config['redirection']['useRewrite']) diff --git a/QFW/QuickFW/Router.php b/QFW/QuickFW/Router.php index 94e132f..5944058 100644 --- a/QFW/QuickFW/Router.php +++ b/QFW/QuickFW/Router.php @@ -261,12 +261,15 @@ class QuickFW_Router /** * Посылает заголовок Location для перехода на нужное действие * + * @deprecated Используйте redirect(Url::...) + * * @param string $MCA Uri нужного действия (модуль/контроллер/экшен) * @param string|array $get GET парамерты или произвольный хвост * @return exit */ public function redirectMCA($MCA, $get='') { + trigger_error('Используйте redirect(Url::...)', E_USER_DEPRECATED); $base = QFW::$config['redirection']['baseUrl']; $index = QFW::$config['redirection']['useIndex']?'index.php/':''; $url = QFW::$config['redirection']['useRewrite']?$this->backrewrite($MCA):$MCA; @@ -366,6 +369,7 @@ class QuickFW_Router { if (empty($data) || $data[0]!='') return $data; + trigger_error('Вы все еще кипятите? А мы уже рубим!', E_USER_DEPRECATED); array_shift($data); //Удаляем первый пустой параметр $params = array(); while(!empty($data)) ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Cache.php | 1 + QFW/QuickFW/Plugs.php | 5 +++++ QFW/QuickFW/Router.php | 4 ++++ 3 files changed, 10 insertions(+), 0 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-10-05 22:24:43
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via c83e6c80852b7b5959c0a490da165e1859a9ef33 (commit) from 1466ce468b54cfcf8fedb7b09541012d96707c53 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit c83e6c80852b7b5959c0a490da165e1859a9ef33 Author: Ivan Borzenkov <iva...@li...> Date: Wed Oct 6 02:24:03 2010 +0400 По умолчанию юзаем функцию из php 5.3 diff --git a/QFW/QuickFW/Router.php b/QFW/QuickFW/Router.php index 7865a9f..94e132f 100644 --- a/QFW/QuickFW/Router.php +++ b/QFW/QuickFW/Router.php @@ -154,7 +154,7 @@ class QuickFW_Router $MCA = $this->loadMCA($data,'Block'); // Если вы все еще сидите на PHP 5.2 то раскомментируйте старый вариант $MCA['Params'] = empty($patt[4]) ? array() : - $this->parseScobParams($patt[4]); // str_getcsv($patt[4],',',"'",'\\'); + $this->str_getcsv($patt[4],',',"'",'\\'); // parseScobParams($patt[4]); } else { ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Router.php | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-10-05 22:03:38
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 1466ce468b54cfcf8fedb7b09541012d96707c53 (commit) from 4a55c9697e095bca4ae6e94672ec1b8b8bb6af26 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 1466ce468b54cfcf8fedb7b09541012d96707c53 Author: TeXHaPb <st...@in...> Date: Wed Oct 6 01:35:05 2010 +0400 renamed .emptydir to .gitignore diff --git a/application/_common/css/.emptydir b/application/_common/css/.emptydir deleted file mode 100644 index 2d80147..0000000 --- a/application/_common/css/.emptydir +++ /dev/null @@ -1 +0,0 @@ -css dir \ No newline at end of file diff --git a/application/_common/css/.gitignore b/application/_common/css/.gitignore new file mode 100644 index 0000000..b29958e --- /dev/null +++ b/application/_common/css/.gitignore @@ -0,0 +1,2 @@ +# css dir +.gitignore diff --git a/application/_common/js/.emptydir b/application/_common/js/.emptydir deleted file mode 100644 index a103c49..0000000 --- a/application/_common/js/.emptydir +++ /dev/null @@ -1 +0,0 @@ -js dir \ No newline at end of file diff --git a/application/_common/js/.gitignore b/application/_common/js/.gitignore new file mode 100644 index 0000000..599d02b --- /dev/null +++ b/application/_common/js/.gitignore @@ -0,0 +1,2 @@ +# js dir +.gitignore diff --git a/application/_common/models/.emptydir b/application/_common/models/.emptydir deleted file mode 100644 index 625cb36..0000000 --- a/application/_common/models/.emptydir +++ /dev/null @@ -1 +0,0 @@ -models dir \ No newline at end of file diff --git a/application/_common/models/.gitignore b/application/_common/models/.gitignore new file mode 100644 index 0000000..bfb6b48 --- /dev/null +++ b/application/_common/models/.gitignore @@ -0,0 +1,2 @@ +# models dir +.gitignore diff --git a/application/_common/slots/.emptydir b/application/_common/slots/.emptydir deleted file mode 100644 index e89abae..0000000 --- a/application/_common/slots/.emptydir +++ /dev/null @@ -1 +0,0 @@ -slots dir \ No newline at end of file diff --git a/application/_common/slots/.gitignore b/application/_common/slots/.gitignore new file mode 100644 index 0000000..9810424 --- /dev/null +++ b/application/_common/slots/.gitignore @@ -0,0 +1,2 @@ +# slots dir +.gitignore diff --git a/application/_common/tags/.emptydir b/application/_common/tags/.emptydir deleted file mode 100644 index aef7fb2..0000000 --- a/application/_common/tags/.emptydir +++ /dev/null @@ -1 +0,0 @@ -tags dir \ No newline at end of file diff --git a/application/_common/tags/.gitignore b/application/_common/tags/.gitignore new file mode 100644 index 0000000..44fa838 --- /dev/null +++ b/application/_common/tags/.gitignore @@ -0,0 +1,2 @@ +# tags dir +.gitignore diff --git a/log/.emptydir b/log/.emptydir deleted file mode 100644 index bd64b77..0000000 --- a/log/.emptydir +++ /dev/null @@ -1 +0,0 @@ -dir for log files \ No newline at end of file diff --git a/log/.gitignore b/log/.gitignore new file mode 100644 index 0000000..935bebc --- /dev/null +++ b/log/.gitignore @@ -0,0 +1,2 @@ +# dir for log files +* diff --git a/tests/testapp/_common/models/.emptydir b/tests/testapp/_common/models/.emptydir deleted file mode 100644 index 625cb36..0000000 --- a/tests/testapp/_common/models/.emptydir +++ /dev/null @@ -1 +0,0 @@ -models dir \ No newline at end of file diff --git a/tests/testapp/_common/models/.gitignore b/tests/testapp/_common/models/.gitignore new file mode 100644 index 0000000..bfb6b48 --- /dev/null +++ b/tests/testapp/_common/models/.gitignore @@ -0,0 +1,2 @@ +# models dir +.gitignore diff --git a/tests/testapp/_common/slots/.emptydir b/tests/testapp/_common/slots/.emptydir deleted file mode 100644 index e89abae..0000000 --- a/tests/testapp/_common/slots/.emptydir +++ /dev/null @@ -1 +0,0 @@ -slots dir \ No newline at end of file diff --git a/tests/testapp/_common/slots/.gitignore b/tests/testapp/_common/slots/.gitignore new file mode 100644 index 0000000..9810424 --- /dev/null +++ b/tests/testapp/_common/slots/.gitignore @@ -0,0 +1,2 @@ +# slots dir +.gitignore diff --git a/tests/testapp/_common/tags/.emptydir b/tests/testapp/_common/tags/.emptydir deleted file mode 100644 index aef7fb2..0000000 --- a/tests/testapp/_common/tags/.emptydir +++ /dev/null @@ -1 +0,0 @@ -tags dir \ No newline at end of file diff --git a/tests/testapp/_common/tags/.gitignore b/tests/testapp/_common/tags/.gitignore new file mode 100644 index 0000000..44fa838 --- /dev/null +++ b/tests/testapp/_common/tags/.gitignore @@ -0,0 +1,2 @@ +# tags dir +.gitignore diff --git a/tmp/.emptydir b/tmp/.emptydir deleted file mode 100644 index a459890..0000000 --- a/tmp/.emptydir +++ /dev/null @@ -1 +0,0 @@ -dir for temp files \ No newline at end of file diff --git a/tmp/.gitignore b/tmp/.gitignore new file mode 100644 index 0000000..3d1636f --- /dev/null +++ b/tmp/.gitignore @@ -0,0 +1,2 @@ +# dir for temp files +* diff --git a/tmp/cache/.emptydir b/tmp/cache/.emptydir deleted file mode 100644 index c42fd2c..0000000 --- a/tmp/cache/.emptydir +++ /dev/null @@ -1 +0,0 @@ -dir for file cache \ No newline at end of file diff --git a/tmp/cache/.gitignore b/tmp/cache/.gitignore new file mode 100644 index 0000000..13ca1a3 --- /dev/null +++ b/tmp/cache/.gitignore @@ -0,0 +1,2 @@ +# dir for file cache +* diff --git a/www/css/.emptydir b/www/css/.emptydir deleted file mode 100644 index 2d80147..0000000 --- a/www/css/.emptydir +++ /dev/null @@ -1 +0,0 @@ -css dir \ No newline at end of file diff --git a/www/css/.gitignore b/www/css/.gitignore new file mode 100644 index 0000000..b29958e --- /dev/null +++ b/www/css/.gitignore @@ -0,0 +1,2 @@ +# css dir +.gitignore diff --git a/www/img/.emptydir b/www/img/.emptydir deleted file mode 100644 index 6a17a40..0000000 --- a/www/img/.emptydir +++ /dev/null @@ -1 +0,0 @@ -images dir \ No newline at end of file diff --git a/www/img/.gitignore b/www/img/.gitignore new file mode 100644 index 0000000..a786944 --- /dev/null +++ b/www/img/.gitignore @@ -0,0 +1,2 @@ +# images dir +.gitignore ----------------------------------------------------------------------- Summary of changes: application/_common/css/.emptydir | 1 - application/_common/css/.gitignore | 2 ++ application/_common/js/.emptydir | 1 - application/_common/js/.gitignore | 2 ++ application/_common/models/.emptydir | 1 - application/_common/models/.gitignore | 2 ++ application/_common/slots/.emptydir | 1 - application/_common/slots/.gitignore | 2 ++ application/_common/tags/.emptydir | 1 - application/_common/tags/.gitignore | 2 ++ log/.emptydir | 1 - log/.gitignore | 2 ++ tests/testapp/_common/models/.emptydir | 1 - tests/testapp/_common/models/.gitignore | 2 ++ tests/testapp/_common/slots/.emptydir | 1 - tests/testapp/_common/slots/.gitignore | 2 ++ tests/testapp/_common/tags/.emptydir | 1 - tests/testapp/_common/tags/.gitignore | 2 ++ tmp/.emptydir | 1 - tmp/.gitignore | 2 ++ tmp/cache/.emptydir | 1 - tmp/cache/.gitignore | 2 ++ www/css/.emptydir | 1 - www/css/.gitignore | 2 ++ www/img/.emptydir | 1 - www/img/.gitignore | 2 ++ 26 files changed, 26 insertions(+), 13 deletions(-) delete mode 100644 application/_common/css/.emptydir create mode 100644 application/_common/css/.gitignore delete mode 100644 application/_common/js/.emptydir create mode 100644 application/_common/js/.gitignore delete mode 100644 application/_common/models/.emptydir create mode 100644 application/_common/models/.gitignore delete mode 100644 application/_common/slots/.emptydir create mode 100644 application/_common/slots/.gitignore delete mode 100644 application/_common/tags/.emptydir create mode 100644 application/_common/tags/.gitignore delete mode 100644 log/.emptydir create mode 100644 log/.gitignore delete mode 100644 tests/testapp/_common/models/.emptydir create mode 100644 tests/testapp/_common/models/.gitignore delete mode 100644 tests/testapp/_common/slots/.emptydir create mode 100644 tests/testapp/_common/slots/.gitignore delete mode 100644 tests/testapp/_common/tags/.emptydir create mode 100644 tests/testapp/_common/tags/.gitignore delete mode 100644 tmp/.emptydir create mode 100644 tmp/.gitignore delete mode 100644 tmp/cache/.emptydir create mode 100644 tmp/cache/.gitignore delete mode 100644 www/css/.emptydir create mode 100644 www/css/.gitignore delete mode 100644 www/img/.emptydir create mode 100644 www/img/.gitignore hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-10-04 10:52:27
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 4a55c9697e095bca4ae6e94672ec1b8b8bb6af26 (commit) from eac6bd72843cc724df6e90660fe0f1c1660894ec (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 4a55c9697e095bca4ae6e94672ec1b8b8bb6af26 Author: Ivan1986 <iva...@li...> Date: Mon Oct 4 14:51:30 2010 +0400 Исправлена ошибка в скафолдинге - передавался не ключ в display diff --git a/lib/Modules/Scaffold/scaffold/index.html b/lib/Modules/Scaffold/scaffold/index.html index ec3650f..4a7135e 100644 --- a/lib/Modules/Scaffold/scaffold/index.html +++ b/lib/Modules/Scaffold/scaffold/index.html @@ -37,9 +37,9 @@ ?> <td><?php //отображение обычного не связанного поля if (isset($methods['display_'.ucfirst($key)])) - echo call_user_func($class.'::display_'.ucfirst($key), $id, $v); + echo call_user_func($class.'::display_'.ucfirst($key), $row[$primaryKey], $v); else - echo $i->display($id, $v); + echo $i->display($row[$primaryKey], $v); ?></td> <?php } ?> <td><a href="<?php echo Url::C('edit/'.$row[$primaryKey]) ?>">ред.</a></td> ----------------------------------------------------------------------- Summary of changes: lib/Modules/Scaffold/scaffold/index.html | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-10-04 09:54:26
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via eac6bd72843cc724df6e90660fe0f1c1660894ec (commit) from 3ca3ae2f392a0d1a39c6d192a7e0548640ebc1af (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit eac6bd72843cc724df6e90660fe0f1c1660894ec Author: Ivan1986 <iva...@li...> Date: Mon Oct 4 13:42:21 2010 +0400 Убрана ненужная переменная DONE diff --git a/QFW/QuickFW/Router.php b/QFW/QuickFW/Router.php index 7f7821e..7865a9f 100644 --- a/QFW/QuickFW/Router.php +++ b/QFW/QuickFW/Router.php @@ -219,7 +219,6 @@ class QuickFW_Router */ public function show404() { - $GLOBALS['DONE'] = 1; //php_sapi_name если через nginx, то Status //а надо ли? - nginx и так понимает /*if (substr(PHP_SAPI, 0, 3) == 'cgi') @@ -568,7 +567,6 @@ SREG; if ($l>0 && strpos($uri,QFW::$config['redirection']['defExt'],$l)!==false) $uri = substr($uri,0,$l); } - return trim($uri, self::PATH_SEPARATOR.'/'); } diff --git a/www/index.php b/www/index.php index 8819f84..bc7bd62 100644 --- a/www/index.php +++ b/www/index.php @@ -7,11 +7,8 @@ define ('LIBPATH', ROOTPATH . '/lib'); define ('MODPATH', APPPATH . '/_common/models'); - $DONE = 0; - require (QFWPATH.'/Init.php'); QFW::$router->route(); - - $DONE = 1; + ?> \ No newline at end of file ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Router.php | 2 -- www/index.php | 5 +---- 2 files changed, 1 insertions(+), 6 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-09-29 07:03:14
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The tag, 1.7 has been created at 3ca3ae2f392a0d1a39c6d192a7e0548640ebc1af (commit) - Log ----------------------------------------------------------------- commit 3ca3ae2f392a0d1a39c6d192a7e0548640ebc1af Author: Ivan Borzenkov <iva...@li...> Date: Fri Sep 10 23:29:20 2010 +0400 Исправлена ошибка инициализации MCA при повторном вызове route ----------------------------------------------------------------------- hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-09-10 19:29:53
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 3ca3ae2f392a0d1a39c6d192a7e0548640ebc1af (commit) from f8b5340c3633dd292a5aeec43a82da1130cf2801 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 3ca3ae2f392a0d1a39c6d192a7e0548640ebc1af Author: Ivan Borzenkov <iva...@li...> Date: Fri Sep 10 23:29:20 2010 +0400 Исправлена ошибка инициализации MCA при повторном вызове route diff --git a/QFW/QuickFW/Router.php b/QFW/QuickFW/Router.php index 980e5da..7f7821e 100644 --- a/QFW/QuickFW/Router.php +++ b/QFW/QuickFW/Router.php @@ -96,6 +96,9 @@ class QuickFW_Router $data = explode(self::PATH_SEPARATOR, $requestUri); $data = array_map('urldecode', $data); + //обнуляем модуль - если нас вызвали повторно + $this->module = ''; + $MCA = $this->loadMCA($data, $type); if (isset($MCA['Error'])) { ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Router.php | 3 +++ 1 files changed, 3 insertions(+), 0 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-09-10 18:28:27
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via f8b5340c3633dd292a5aeec43a82da1130cf2801 (commit) from eac6e05b69f52a1d68416862d63cdf4d6069c6d6 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit f8b5340c3633dd292a5aeec43a82da1130cf2801 Author: Ivan Borzenkov <iva...@li...> Date: Fri Sep 10 22:27:39 2010 +0400 Опция - верстка в html или в xml - пока для addCSS diff --git a/QFW/QuickFW/Plugs.php b/QFW/QuickFW/Plugs.php index 1e16692..371d893 100644 --- a/QFW/QuickFW/Plugs.php +++ b/QFW/QuickFW/Plugs.php @@ -119,14 +119,15 @@ class QuickFW_Plugs public function HeaderFilter($text) { $head=''; + $endSlash = QFW::$config['QFW']['addCSSXml'] ? '/' : ''; $this->IncFiles['css'] = array_merge($this->IncFiles['css_main'], $this->IncFiles['css']); $this->IncFiles['js'] = array_merge($this->IncFiles['js_main'], $this->IncFiles['js']); $this->IncFiles['css'] = array_unique($this->IncFiles['css']); if (count($this->IncFiles['css'])>0) $head.='<link rel="stylesheet" href="'. - join('" type="text/css" />'."\n".'<link rel="stylesheet" href="', $this->IncFiles['css']). - '" type="text/css" />'."\n"; + join('" type="text/css" '.$endSlash.'>'."\n".'<link rel="stylesheet" href="', $this->IncFiles['css']). + '" type="text/css" '.$endSlash.'>'."\n"; $this->IncFiles['js'] = array_unique($this->IncFiles['js']); if (count($this->IncFiles['js'])>0) diff --git a/QFW/config.php b/QFW/config.php index 4cf48f2..8e29a95 100644 --- a/QFW/config.php +++ b/QFW/config.php @@ -37,6 +37,7 @@ $config['QFW'] = array( 'cacheSessions' => false, /* Хранить сессии в кеше, не использовать стандартный механизм */ 'autoload' => false, /* включить автолоад false|true|string */ 'auto404' => false, /* не перенаправлять на дефолтовый контроллер все запросы */ + 'addCSSXml' => false, /* addJS и addCSS выводят теги в XML */ ); /** diff --git a/application/default.php b/application/default.php index 0cecf94..b1d1c19 100644 --- a/application/default.php +++ b/application/default.php @@ -85,6 +85,7 @@ $config['QFW'] = array( 'cacheSessions' => false, /* Хранить сессии в кеше, не использовать стандартный механизм */ 'autoload' => true, /* включить автолоад false|true|string */ 'auto404' => false, /* не перенаправлять на дефолтовый контроллер все запросы */ + 'addCSSXml' => false, /* addJS и addCSS выводят теги в XML */ ); /* Шаблонизатор - имя класса + дефолтовый шаблон */ ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Plugs.php | 5 +++-- QFW/config.php | 1 + application/default.php | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-09-04 12:47:50
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via eac6e05b69f52a1d68416862d63cdf4d6069c6d6 (commit) from f447a56ecf5a9d5f13d98512771b6f74904d2f36 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit eac6e05b69f52a1d68416862d63cdf4d6069c6d6 Author: Ivan Borzenkov <iva...@li...> Date: Sat Sep 4 16:46:54 2010 +0400 js_main аналогично css_main diff --git a/QFW/QuickFW/Plugs.php b/QFW/QuickFW/Plugs.php index daf570e..1e16692 100644 --- a/QFW/QuickFW/Plugs.php +++ b/QFW/QuickFW/Plugs.php @@ -43,6 +43,7 @@ class QuickFW_Plugs protected $HeadData = array(); protected $IncFiles = array( + 'js_main'=>array(), 'js'=>array(), 'css_main'=>array(), 'css'=>array(), @@ -53,7 +54,7 @@ class QuickFW_Plugs public function addJS($file, $noBase=false) { - $this->IncFiles['js'][]=($noBase?'':QFW::$config['redirection']['baseUrl']).$file; + $this->IncFiles['js'.($this->isMain?'_main':'')][]=($noBase?'':QFW::$config['redirection']['baseUrl']).$file; return ""; } @@ -119,6 +120,7 @@ class QuickFW_Plugs { $head=''; $this->IncFiles['css'] = array_merge($this->IncFiles['css_main'], $this->IncFiles['css']); + $this->IncFiles['js'] = array_merge($this->IncFiles['js_main'], $this->IncFiles['js']); $this->IncFiles['css'] = array_unique($this->IncFiles['css']); if (count($this->IncFiles['css'])>0) ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Plugs.php | 4 +++- 1 files changed, 3 insertions(+), 1 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-31 13:28:28
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via f447a56ecf5a9d5f13d98512771b6f74904d2f36 (commit) via 6aa48d54cd8f07d6e79952c49aeed5caa890ac46 (commit) via 1e079494db28d6403c6b8fdaed22e02026b4ab2f (commit) from 25b39c23eeb4f1884e7adb119b7cac1f99ac2a9f (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit f447a56ecf5a9d5f13d98512771b6f74904d2f36 Author: Ivan1986 <iva...@li...> Date: Tue Aug 31 17:26:54 2010 +0400 Выполнение php в js и scss diff --git a/application/_common/css/.emptydir b/application/_common/css/.emptydir new file mode 100644 index 0000000..2d80147 --- /dev/null +++ b/application/_common/css/.emptydir @@ -0,0 +1 @@ +css dir \ No newline at end of file diff --git a/application/_common/js/.emptydir b/application/_common/js/.emptydir new file mode 100644 index 0000000..a103c49 --- /dev/null +++ b/application/_common/js/.emptydir @@ -0,0 +1 @@ +js dir \ No newline at end of file diff --git a/application/default/controllers/CssController.php b/application/default/controllers/CssController.php index 9dbf2ca..d05eed9 100644 --- a/application/default/controllers/CssController.php +++ b/application/default/controllers/CssController.php @@ -1,6 +1,7 @@ <?php /** * Преобразование scss в css + * Выполнение php в css * * <br>Необходимо установить sass версии не ниже 3.0 * @@ -9,7 +10,15 @@ class CssController { /** Путь к sass */ - const SASS = 'sass -C'; + const SASS = 'sass --scss -C'; + /** Путь к папке с scss - проецируется на DOC_ROOT/css */ + private $path; + + public function __construct() + { + //$this->path = DOC_ROOT.'/css'; + $this->path = APPPATH.'/_common/css'; + } /** * Генерирует несуществующую css по scss если он есть @@ -22,14 +31,16 @@ class CssController $args = func_get_args(); $css = implode('/', $args); $scss = str_replace('.css', '.scss', $css); - if (!is_file(DOC_ROOT.'/css/'.$scss)) + if (!is_file($this->path.'/'.$scss)) QFW::$router->show404(); header('Content-Type: text/css'); $out = array(); $ret = false; + QFW::$view->setScriptPath($this->path); + $text = QFW::$view->fetch($scss); //запускаем преобразования - по умолчанию без кеша и выводим ошибки в основной поток - exec(self::SASS.' 2>&1 '.DOC_ROOT.'/css/'.$scss, $out, $ret); + exec('echo '.escapeshellarg($text).' | '.self::SASS.' 2>&1 ', $out, $ret); $out = implode("\n", $out); if ($ret) @@ -48,13 +59,16 @@ class CssController { $out = array(); $ret = false; - exec('find '.DOC_ROOT.'/css -name \'*.scss\'', $out, $ret); + chdir($this->path); + QFW::$view->setScriptPath($this->path); + exec('find . -name \'*.scss\'', $out, $ret); if ($ret) return; foreach ($out as $file) { $css = str_replace('.scss', '.css', $file); - exec(self::SASS.' 2>&1 '.$file.' | unexpand -t2 --first-only >'.$css, $out, $ret); + $text = QFW::$view->fetch($file); + exec('echo '.escapeshellarg($text).' | '.self::SASS.' 2>&1 | unexpand -t2 --first-only > '.DOC_ROOT.'/css/'.$css, $out, $ret); } } @@ -65,12 +79,16 @@ class CssController { $out = array(); $ret = false; - exec('find '.DOC_ROOT.'/css -name \'*.scss\'', $out, $ret); + chdir($this->path); + exec('find . -name \'*.scss\'', $out, $ret); if ($ret) return; foreach ($out as $file) { - $css = str_replace('.scss', '.css', $file); + $css = str_replace( + array('.scss', './'), + array('.css', DOC_ROOT.'/css/'), + $file); if (is_file($css)) unlink($css); } diff --git a/application/default/controllers/JsController.php b/application/default/controllers/JsController.php new file mode 100644 index 0000000..4da4df7 --- /dev/null +++ b/application/default/controllers/JsController.php @@ -0,0 +1,77 @@ +<?php +/** + * Выполнение php в js + * + * @author ivan1986 + */ +class JsController +{ + /** Путь к папке с js - проецируется на DOC_ROOT/js */ + private $path; + + public function __construct() + { + //$this->path = DOC_ROOT.'/js'; + $this->path = APPPATH.'/_common/js'; + } + + /** + * Генерирует несуществующую js из php шаблона + * + * @return string сгенерированная js + */ + public function indexAction() + { + QFW::$view->mainTemplate = ''; + $args = func_get_args(); + $js = implode('/', $args); + if (!is_file($this->path.'/'.$js)) + QFW::$router->show404(); + + header('Content-Type: application/javascript'); + $out = array(); + $ret = false; + QFW::$view->setScriptPath($this->path); + $text = QFW::$view->fetch($js); + + return $text; + } + + /** + * Генерирует все файлы js + */ + public function genCli() + { + $out = array(); + $ret = false; + chdir($this->path); + QFW::$view->setScriptPath($this->path); + exec('find . -name \'*.js\'', $out, $ret); + if ($ret) + return; + foreach ($out as $file) + file_put_contents(DOC_ROOT.'/js/'.$file, QFW::$view->fetch($file)); + } + + /** + * Удаляет автоматически сгенерированные js + */ + public function cleanCli() + { + $out = array(); + $ret = false; + chdir($this->path); + exec('find . -name \'*.js\'', $out, $ret); + if ($ret) + return; + foreach ($out as $file) + { + $js = str_replace('./', DOC_ROOT.'/js/', $file); + if (is_file($js)) + unlink($js); + } + } + +} + +?> commit 6aa48d54cd8f07d6e79952c49aeed5caa890ac46 Author: Ivan1986 <iva...@li...> Date: Tue Aug 31 16:58:18 2010 +0400 Ошибка в проксирующем шаблонизаторе - шаблонизатор по умолчанию diff --git a/QFW/Templater/Proxy.php b/QFW/Templater/Proxy.php index 27f9bca..d804b78 100644 --- a/QFW/Templater/Proxy.php +++ b/QFW/Templater/Proxy.php @@ -55,9 +55,8 @@ class Templater_Proxy extends Templater public function fetch($name) { $key=substr($name,strrpos($name,'.')+1); - if (!array_key_exists($key, QFW::$config['templater']['exts'])) - return ''; - $T = QFW::$config['templater']['exts'][$key]; + $T = isset(QFW::$config['templater']['exts'][$key]) ? + QFW::$config['templater']['exts'][$key] : 'PlainView'; if (!array_key_exists($T,$this->templates)) { commit 1e079494db28d6403c6b8fdaed22e02026b4ab2f Author: Ivan1986 <iva...@li...> Date: Mon Aug 30 18:14:08 2010 +0400 Обновление plainPHP подсветки diff --git a/doc/plainPHP.xml b/doc/plainPHP.xml index d8ae24d..1886186 100644 --- a/doc/plainPHP.xml +++ b/doc/plainPHP.xml @@ -5,7 +5,7 @@ <!ENTITY entref "&(#[0-9]+|#[xX][0-9A-Fa-f]+|&name;);"> ]> -<language name="PlainPHP" version="1.98" kateversion="2.4" section="Scripts" extensions="*.qtp;*.html;*.phtm;" mimetype="text/x-php4-src;text/x-php3-src;application/x-php" author="Ivan Borzenkov (iva...@li...)" license="LGPL" priority="10"> +<language name="PlainPHP" version="1.99" kateversion="2.4" section="Scripts" extensions="*.qtp;*.html;*.phtm;" mimetype="text/x-php4-src;text/x-php3-src;application/x-php" author="Ivan Borzenkov (iva...@li...)" license="LGPL" priority="10"> <highlighting> <contexts> @@ -27,10 +27,16 @@ <RegExpr attribute="Element" context="El Open" String="<pre\b" insensitive="TRUE" beginRegion="pre" /> <RegExpr attribute="Element" context="El Open" String="<div\b" insensitive="TRUE" beginRegion="div" /> <RegExpr attribute="Element" context="El Open" String="<table\b" insensitive="TRUE" beginRegion="table" /> + <RegExpr attribute="Element" context="El Open" String="<ul\b" insensitive="TRUE" beginRegion="ul" /> + <RegExpr attribute="Element" context="El Open" String="<ol\b" insensitive="TRUE" beginRegion="ol" /> + <RegExpr attribute="Element" context="El Open" String="<dl\b" insensitive="TRUE" beginRegion="dl" /> <RegExpr attribute="Element" context="El Open" String="<&name;" /> <RegExpr attribute="Element" context="El Close" String="</pre\b" insensitive="TRUE" endRegion="pre" /> <RegExpr attribute="Element" context="El Close" String="</div\b" insensitive="TRUE" endRegion="div" /> <RegExpr attribute="Element" context="El Close" String="</table\b" insensitive="TRUE" endRegion="table" /> + <RegExpr attribute="Element" context="El Close" String="</ul\b" insensitive="TRUE" endRegion="ul" /> + <RegExpr attribute="Element" context="El Close" String="</ol\b" insensitive="TRUE" endRegion="ol" /> + <RegExpr attribute="Element" context="El Close" String="</dl\b" insensitive="TRUE" endRegion="dl" /> <RegExpr attribute="Element" context="El Close" String="</&name;" /> <!-- as long as kde gives DTDs the text/html mimetype--><IncludeRules context="FindDTDRules" /> <IncludeRules context="FindEntityRefs" /> @@ -212,7 +218,6 @@ <RegExpr attribute="Element" context="CSS content" String="<\?(?:=|php)?.*\$P-\>sCSS\(.*\).*\?>" insensitive="TRUE" beginRegion="script" lookAhead="true"/> <RegExpr context="##PHP/PHP" String="<\?(?:=|php)?" lookAhead="true" /> </context> - </contexts> <itemDatas> <itemData name="Normal Text" defStyleNum="dsNormal" /> ----------------------------------------------------------------------- Summary of changes: QFW/Templater/Proxy.php | 5 +- {www => application/_common}/css/.emptydir | 0 application/_common/js/.emptydir | 1 + application/default/controllers/CssController.php | 32 +++++++-- application/default/controllers/JsController.php | 77 +++++++++++++++++++++ doc/plainPHP.xml | 9 ++- 6 files changed, 112 insertions(+), 12 deletions(-) copy {www => application/_common}/css/.emptydir (100%) create mode 100644 application/_common/js/.emptydir create mode 100644 application/default/controllers/JsController.php hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-28 19:19:25
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 25b39c23eeb4f1884e7adb119b7cac1f99ac2a9f (commit) via a1bd27ac269de99aceaecebbb1aabbd7112779b1 (commit) via 9b89af82040662b4b66ed59ecef563b09bdf24a3 (commit) from e38332209fb0516ed4b399386641e66f7c848cfd (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 25b39c23eeb4f1884e7adb119b7cac1f99ac2a9f Author: Ivan Borzenkov <iva...@li...> Date: Sat Aug 28 23:18:59 2010 +0400 Тест двойного запуска diff --git a/tests/app/050_double_run.phpt b/tests/app/050_double_run.phpt new file mode 100644 index 0000000..a796dc9 --- /dev/null +++ b/tests/app/050_double_run.phpt @@ -0,0 +1,15 @@ +--TEST-- +QFW: double run route +--FILE-- +<?php +require dirname(__FILE__).'/init.php'; + +QFW::$router->route(''); +echo "\n"; +QFW::$router->route(''); + +--EXPECT-- +Основной шаблон +Корневое действие сайта +Основной шаблон +Корневое действие сайта commit a1bd27ac269de99aceaecebbb1aabbd7112779b1 Author: Ivan Borzenkov <iva...@li...> Date: Sat Aug 28 23:18:43 2010 +0400 В базовый урл добавил параметр diff --git a/QFW/QuickFW/Url.php b/QFW/QuickFW/Url.php index 280d1d0..63c22d5 100644 --- a/QFW/QuickFW/Url.php +++ b/QFW/QuickFW/Url.php @@ -8,13 +8,14 @@ class Url { /** - * Возвращает базовый урл + * Добавляет в начале базовый урл * + * @param string|self $url url * @return self базовый url */ - public static function base() + public static function base($url='') { - return new self(''); + return new self('').$url; } /** commit 9b89af82040662b4b66ed59ecef563b09bdf24a3 Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 25 21:12:47 2010 +0400 Перетасовка тестов diff --git a/tests/QFW/FrameworkTests.php b/tests/QFW/FrameworkTests.php deleted file mode 100644 index bf0ed60..0000000 --- a/tests/QFW/FrameworkTests.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php - -require_once ('PHPUnit/Framework/TestSuite.php'); - -class FrameworkTests -{ - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite(); - - $base = dirname(__FILE__); - - $suite->addTestFile($base.'/QFWTest.php'); - - return $suite; - } - -} - -?> \ No newline at end of file diff --git a/tests/QFW/QFWTest.php b/tests/QFW/QFWTest.php deleted file mode 100644 index 5e8b459..0000000 --- a/tests/QFW/QFWTest.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php - -class QFWTest extends PHPUnit_Framework_TestCase -{ - public function testInitTime() - { - global $InitTime; - $this->assertLessThanOrEqual(0.01, $InitTime); - unset($GLOBALS['InitTime']); - } - - /** - * Соответствия урлам и дефолтным урлам - * - * @return array - */ - public function testDdefProvider() - { - return array( - array('aaa/bbb/ccc', ''), - array('aaa/bbb/fff', 'bbb/fff'), - array('aaa/eee/ccc', 'eee'), - array('aaa/eee/fff', 'eee/fff'), - array('ddd/bbb/ccc', 'ddd/bbb'), - array('ddd/bbb/fff', 'ddd/bbb/fff'), - array('ddd/eee/ccc', 'ddd/eee'), - array('ddd/eee/fff', 'ddd/eee/fff'), - array('aaa/bbb', ''), - array('aaa/eee', 'eee'), - array('ddd/bbb', 'ddd/bbb'), - array('ddd/eee', 'ddd/eee'), - array('aaa/ccc', ''), - array('aaa/fff', 'fff'), - array('ddd/ccc', 'ddd'), - array('ddd/fff', 'ddd/fff'), - array('bbb/ccc', ''), - array('bbb/fff', 'bbb/fff'), - array('eee/ccc', 'eee'), - array('eee/fff', 'eee/fff'), - array('aaa', ''), - array('ddd', 'ddd'), - array('bbb', ''), - array('eee', 'eee'), - array('ccc', ''), - array('fff', 'fff'), - ); - } - - /** - * @dataProvider testDdefProvider - * - * Тестирование delDef - */ - public function testDdef($in, $out) - { - QFW::Init(); - QFW::$config['default']['module'] = 'aaa'; - QFW::$config['default']['controller'] = 'bbb'; - QFW::$config['default']['action'] = 'ccc'; - QFW::$router->__construct(APPPATH); - $this->assertEquals(QFW::$router->delDef($in),$out); - } - -} - -?> \ No newline at end of file diff --git a/tests/QFWTests.php b/tests/QFWTests.php index 2a355af..5b1a6b1 100644 --- a/tests/QFWTests.php +++ b/tests/QFWTests.php @@ -23,8 +23,6 @@ $suite->addTestFile('DbSimple/DbSimpleTests.php'); $suite->addTestFile('Cache/CacheTest.php'); - //$suite->addTestFile('Smarty/SmartyTest.php'); - $suite->addTestFile('QFW/FrameworkTests.php'); return $suite; } diff --git a/tests/Smarty/README b/tests/Smarty/README deleted file mode 100644 index d4d9731..0000000 --- a/tests/Smarty/README +++ /dev/null @@ -1,32 +0,0 @@ -Smarty Unit Testing -------------------- - -Smarty unit tests require the PEAR PHPUnit -package to be installed. See if you have that -installed with the following command: - -$> pear list - -If you don't see PHPUnit, install with this: - -$> pear install PHPUnit - -Edit the config.php file, -be sure everything is defined correctly. - -Be sure the following directories are present: - -templates -configs -templates_c (writable) -cache (writable) - -Then run from the command line: -php -q smarty_unit_test.php - -Or from the web browser: -http://www.your_domain.com/path/to/smarty_unit_test_gui.php - -This will run a unit test for every component -of Smarty and dump the results. All should pass -with flying colors. :) diff --git a/tests/Smarty/SmartyTest.php b/tests/Smarty/SmartyTest.php deleted file mode 100644 index d34a99f..0000000 --- a/tests/Smarty/SmartyTest.php +++ /dev/null @@ -1,449 +0,0 @@ -<?php - - -class SmartyObj { - var $val = 'val'; - var $arr = array('one' => 'one', 'two' => 2); - var $ten = 10; - - function meth($a="a", $b="b") { - return "$a:$b"; - } - - function six() { - return 6; - } -} - -require_once LIBPATH . '/Smarty/Smarty.class.php'; - -class SmartyTest extends PHPUnit_Framework_TestCase -{ - // contains the SmartyObject handle of the string class - var $abc; - // contains the last triggered error's errorlevel - var $errorlevel; - - // called before the test functions will be executed - // this function is defined in PHPUnit_TestCase and overwritten - // here - function setUp() { - // create a new instance of String with the - // string 'abc' - $this->smarty = new Smarty; - $this->smarty->template_dir = dirname(__FILE__).'/templates'; - $this->smarty->config_dir = dirname(__FILE__).'/configs'; - $this->smarty->compile_dir = dirname(__FILE__).'/templates_c'; - $this->smarty->cache_dir = dirname(__FILE__).'/cache'; - $this->smarty->plugins_dir = array(LIBPATH . '/Smarty/plugins'); - } - // called after the test functions are executed - // this function is defined in PHPUnit_TestCase and overwritten - // here - function tearDown() { - // delete your instance - unset($this->smarty); - } - - // dummy errorhandler for functions that are supposed to call trigger_error() - function error_handler($errorlevel) { - if ($errorlevel) $this->errorlevel = $errorlevel; - } - - /* DIRECTORY TESTS */ - - // test that template_dir exists - function test_template_dir_exists() { - $this->assertTrue(file_exists($this->smarty->template_dir)); - } - // test that template_dir is a directory - function test_template_dir_is_dir() { - $this->assertTrue(is_dir($this->smarty->template_dir)); - } - // test that template_dir is readable - function test_template_dir_is_readable() { - $this->assertTrue(is_readable($this->smarty->template_dir)); - } - // test that config_dir exists - function test_config_dir_exists() { - $this->assertTrue(file_exists($this->smarty->config_dir)); - } - // test that config_dir is a directory - function test_config_dir_is_dir() { - $this->assertTrue(is_dir($this->smarty->config_dir)); - } - // test that config_dir is readable - function test_config_dir_is_readable() { - $this->assertTrue(is_readable($this->smarty->config_dir)); - } - // test that compile_dir exists - function test_compile_dir_exists() { - $this->assertTrue(file_exists($this->smarty->compile_dir)); - } - // test that compile_dir is a directory - function test_compile_dir_is_dir() { - $this->assertTrue(is_dir($this->smarty->compile_dir)); - } - // test that compile_dir is readable - function test_compile_dir_is_readable() { - $this->assertTrue(is_readable($this->smarty->compile_dir)); - } - // test that compile_dir is writable - function test_compile_dir_is_writable() { - $this->assertTrue(is_writable($this->smarty->compile_dir)); - } - // test that cache_dir exists - function test_cache_dir_exists() { - $this->assertTrue(file_exists($this->smarty->cache_dir)); - } - // test that cache_dir is a directory - function test_cache_dir_is_dir() { - $this->assertTrue(is_dir($this->smarty->cache_dir)); - } - // test that cache_dir is readable - function test_cache_dir_is_readable() { - $this->assertTrue(is_readable($this->smarty->cache_dir)); - } - // test that cache_dir is writable - function test_cache_dir_is_writable() { - $this->assertTrue(is_writable($this->smarty->cache_dir)); - } - - /* METHOD EXISTS TESTS */ - function test_assign_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'assign')); - } - function test_assign_by_ref_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'assign_by_ref')); - } - function test_append_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'append')); - } - function test_append_by_ref_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'append_by_ref')); - } - function test_clear_assign_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'clear_assign')); - } - function test_register_function_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_function')); - } - function test_unregister_function_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_function')); - } - function test_register_object_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_object')); - } - function test_unregister_object_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_object')); - } - function test_register_block_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_block')); - } - function test_unregister_block_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_block')); - } - function test_register_compiler_function_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_compiler_function')); - } - function test_unregister_compiler_function_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_compiler_function')); - } - function test_register_modifier_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_modifier')); - } - function test_unregister_modifier_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_modifier')); - } - function test_register_resource_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_resource')); - } - function test_unregister_resource_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_resource')); - } - function test_register_prefilter_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_prefilter')); - } - function test_unregister_prefilter_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_prefilter')); - } - function test_register_postfilter_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_postfilter')); - } - function test_unregister_postfilter_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_postfilter')); - } - function test_register_outputfilter_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'register_outputfilter')); - } - function test_unregister_outputfilter_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'unregister_outputfilter')); - } - function test_load_filter_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'load_filter')); - } - function test_clear_cache_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'clear_cache')); - } - function test_clear_all_cache_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'clear_all_cache')); - } - function test_is_cached_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'is_cached')); - } - function test_clear_all_assign_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'clear_all_assign')); - } - function test_clear_compiled_tpl_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'clear_compiled_tpl')); - } - function test_template_exists_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'template_exists')); - } - function test_get_template_vars_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'get_template_vars')); - } - function test_get_config_vars_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'get_config_vars')); - } - function test_trigger_error_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'trigger_error')); - } - function test_display_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'display')); - } - function test_fetch_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'fetch')); - } - function test_config_load_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'config_load')); - } - function test_get_registered_object_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'get_registered_object')); - } - function test_clear_config_method_exists() { - $this->assertTrue(method_exists($this->smarty, 'clear_config')); - } - function test_get_plugin_filepath() { - $this->assertTrue(method_exists($this->smarty, '_get_plugin_filepath')); - } - - - /* DISPLAY TESTS */ - - // test that display() executes properly - function test_call_to_display() { - ob_start(); - $this->smarty->display('index.tpl'); - $output = ob_get_contents(); - ob_end_clean(); - $this->assertEquals($output, 'TEST STRING'); - } - - /* FETCH TESTS */ - - // test that fetch() executes properly - function test_call_to_fetch() { - $this->assertEquals($this->smarty->fetch('index.tpl'), 'TEST STRING'); - } - - /* ASSIGN TESTS */ - - // test assigning a simple template variable - function test_assign_var() { - $this->smarty->assign('foo', 'bar'); - $this->assertEquals($this->smarty->fetch('assign_var.tpl'), 'bar'); - } - - /* PARSING TESTS */ - - // test assigning and calling an SmartyObject - function test_parse_obj_meth() { - $obj = new SmartyObj(); - $this->smarty->assign('obj', $obj); - $this->smarty->assign('foo', 'foo'); - $this->assertEquals('foo:2.5 -2.5:foo -2.5:b -val:foo -foo:val -foo:foo -one:2 -foo:foo:b', $this->smarty->fetch('parse_obj_meth.tpl')); - } - - // test assigning and calling an SmartyObject - function test_parse_math() { - $obj = new SmartyObj(); - $this->smarty->assign('obj', $obj); - $this->smarty->assign('flt', 2.5); - $this->smarty->assign('items', array(1, 2)); - $this->assertEquals('3 -3.5 -7 -11 -4 -4.5 -8 -12 -12.5 -25 -16 -20 -8.5 -7', $this->smarty->fetch('parse_math.tpl')); - } - - /* CONFIG FILE TESTS */ - - // test assigning a double quoted global variable - function test_config_load_globals_double_quotes() { - // load the global var - $this->smarty->config_load('globals_double_quotes.conf'); - // test that it is assigned - $this->assertEquals($this->smarty->_config[0]['vars']['foo'], 'bar'); - } - - // test assigning a single quoted global variable - function test_config_load_globals_single_quotes() { - // load the global var - $this->smarty->config_load('globals_single_quotes.conf'); - // test that it is assigned - $this->assertEquals($this->smarty->_config[0]['vars']['foo'], 'bar'); - } - - // test loading and running modifier.escape.php - function test_escape_modifier_get_plugins_filepath() { - $filepath = $this->smarty->_get_plugin_filepath('modifier', 'escape'); - $this->assertTrue(!!$filepath); - } - - function test_escape_modifier_include_file() { - $filepath = $this->smarty->_get_plugin_filepath('modifier', 'escape'); - $this->assertTrue(!!include($filepath)); - } - - function test_escape_modifier_function_exists() { - $this->assertTrue(function_exists('smarty_modifier_escape')); - } - - function test_escape_modifier_escape_default() { - $string = smarty_modifier_escape("<html><body></body></html>"); - $this->assertEquals('<html><body></body></html>', - $string); - } - - function test_escape_modifier_escape_html() { - $string = smarty_modifier_escape("<html><body></body></html>", 'html'); - $this->assertEquals('<html><body></body></html>', - $string); - } - - function test_escape_modifier_escape_htmlall() { - $string = smarty_modifier_escape("<html><body></body></html>", 'htmlall'); - $this->assertEquals('<html><body></body></html>', - $string); - } - - function test_escape_modifier_escape_url() { - $string = smarty_modifier_escape("http://test.com?foo=bar", 'url'); - $this->assertEquals('http%3A%2F%2Ftest.com%3Ffoo%3Dbar', $string); - } - - function test_escape_modifier_escape_quotes() { - $string = smarty_modifier_escape("'\\'\\''", 'quotes'); - $this->assertEquals("\\'\\'\\'\\'", $string); - } - - function test_escape_modifier_escape_hex() { - $string = smarty_modifier_escape("abcd", 'hex'); - $this->assertEquals('%61%62%63%64', $string); - } - - function test_escape_modifier_escape_hexentity() { - $string = smarty_modifier_escape("ABCD", 'hexentity'); - $this->assertEquals('ABCD', $string); - } - - function test_escape_modifier_escape_javascript() { - $string = smarty_modifier_escape("\r\n\\", 'javascript'); - $this->assertEquals('\\r\\n\\\\', $string); - } - - - function test_core_is_secure_file_exists() { - $file = SMARTY_CORE_DIR . 'core.is_secure.php'; - $this->assertTrue(file_exists($file)); - } - - function test_core_is_secure_file_include() { - $file = SMARTY_CORE_DIR . 'core.is_secure.php'; - $this->assertTrue(!!include($file)); - } - - function test_core_is_secure_function_exists() { - $this->assertTrue(function_exists('smarty_core_is_secure')); - } - - function test_core_is_secure_function_is_secure_true() { - $security = $this->smarty->security; - $this->smarty->security = true; - - /* check if index.tpl is secure (should be true) */ - $params = array('resource_type' => 'file', - 'resource_base_path' => dirname(__FILE__) . '/templates', - 'resource_name' => dirname(__FILE__) . '/templates/index.tpl'); - $this->assertTrue(smarty_core_is_secure($params, $this->smarty)); - $this->smarty->security = $security; - } - - function test_core_is_secure_function_is_secure_false() { - $security = $this->smarty->security; - $this->smarty->security = true; - /* check if test_cases.php is secure (should be false) */ - $params = array('resource_type' => 'file', - 'resource_base_path' => dirname(__FILE__) . '/templates', - 'resource_name' => __FILE__); - $this->assertFalse(smarty_core_is_secure($params, $this->smarty)); - $this->smarty->security = $security; - - } - - // test constants and security - function test_core_is_secure_function_smarty_var_const() { - define('TEST_CONSTANT', 'test constant'); - $this->assertEquals('test constant', $this->smarty->fetch('constant.tpl', - null, 'var_const')); - } - - function test_core_is_secure_function_smarty_var_const_allowed() { - $security = $this->smarty->security; - $security_settings = $this->smarty->security_settings; - $this->smarty->security_settings['ALLOW_CONSTANTS'] = true; - $this->smarty->security = true; - $this->assertEquals('test constant', $this->smarty->fetch('constant.tpl', - null, 'var_const_allowed')); - $this->smarty->security_settings = $security_settings; - $this->smarty->security = $security; - } - - function test_core_is_secure_function_smarty_var_const_not_allowed() { - $security = $this->smarty->security; - $this->smarty->security = true; - /* catch errors: */ - $this->errorlevel = null; - set_error_handler(array(&$this, 'error_handler')); - $this->smarty->fetch('constant.tpl', null, 'var_const_not_allowed'); - restore_error_handler(); - - $this->assertEquals( $this->errorlevel, E_USER_WARNING); - $this->smarty->security = $security; - } - - function test_clear_compiled_tpl() { - $this->smarty->clear_compiled_tpl(); - } - -} - -?> diff --git a/tests/Smarty/configs/globals_double_quotes.conf b/tests/Smarty/configs/globals_double_quotes.conf deleted file mode 100644 index 5abc475..0000000 --- a/tests/Smarty/configs/globals_double_quotes.conf +++ /dev/null @@ -1 +0,0 @@ -foo = "bar" diff --git a/tests/Smarty/configs/globals_single_quotes.conf b/tests/Smarty/configs/globals_single_quotes.conf deleted file mode 100644 index 4517b7b..0000000 --- a/tests/Smarty/configs/globals_single_quotes.conf +++ /dev/null @@ -1 +0,0 @@ -foo = 'bar' diff --git a/tests/Smarty/templates/assign_var.tpl b/tests/Smarty/templates/assign_var.tpl deleted file mode 100644 index acc4b66..0000000 --- a/tests/Smarty/templates/assign_var.tpl +++ /dev/null @@ -1 +0,0 @@ -{$foo} diff --git a/tests/Smarty/templates/constant.tpl b/tests/Smarty/templates/constant.tpl deleted file mode 100644 index 7ae11f1..0000000 --- a/tests/Smarty/templates/constant.tpl +++ /dev/null @@ -1 +0,0 @@ -{$smarty.const.TEST_CONSTANT} diff --git a/tests/Smarty/templates/index.tpl b/tests/Smarty/templates/index.tpl deleted file mode 100644 index fb6aad2..0000000 --- a/tests/Smarty/templates/index.tpl +++ /dev/null @@ -1 +0,0 @@ -TEST STRING diff --git a/tests/Smarty/templates/parse_math.tpl b/tests/Smarty/templates/parse_math.tpl deleted file mode 100644 index 0b787d3..0000000 --- a/tests/Smarty/templates/parse_math.tpl +++ /dev/null @@ -1,12 +0,0 @@ -{foreach name=loop from=$items item=i} -{$smarty.foreach.loop.iteration+2} -{$smarty.foreach.loop.iteration+$flt} -{$smarty.foreach.loop.iteration+$obj->six()} -{$smarty.foreach.loop.iteration+$obj->ten} -{/foreach} -{$obj->ten+$flt} -{$obj->ten*$flt} -{$obj->six()+$obj->ten} -{$obj->ten+$obj->ten} -{$obj->six()+$flt} -{$obj->six()+$items.0} diff --git a/tests/Smarty/templates/parse_obj_meth.tpl b/tests/Smarty/templates/parse_obj_meth.tpl deleted file mode 100644 index ab19832..0000000 --- a/tests/Smarty/templates/parse_obj_meth.tpl +++ /dev/null @@ -1,8 +0,0 @@ -{$obj->meth($foo, 2.5)} -{$obj->meth(2.5, $foo)} -{$obj->meth(2.5)} -{$obj->meth($obj->val, "foo")} -{$obj->meth("foo", $obj->val)} -{$obj->meth("foo", $foo)} -{$obj->meth($obj->arr.one, 2)} -{$obj->meth($obj->meth("foo", $foo))} diff --git a/tests/app/030_init_time.phpt_ b/tests/app/030_init_time.phpt_ new file mode 100644 index 0000000..199940c --- /dev/null +++ b/tests/app/030_init_time.phpt_ @@ -0,0 +1,23 @@ +--TEST-- +QFW: init time (may faild - rerun) +--FILE-- +<?php + +define ('DOC_ROOT', dirname(__FILE__)); +define ('ROOTPATH', dirname(dirname(dirname(__FILE__)))); +define ('APPPATH', ROOTPATH . '/application'); +define ('TMPPATH', ROOTPATH . '/tmp'); +define ('QFWPATH', ROOTPATH . '/QFW'); +define ('LIBPATH', ROOTPATH . '/lib'); +define ('MODPATH', APPPATH . '/_common/models'); + +$_SERVER['HTTP_HOST'] = 'test'; + +$InitTime = microtime(true); +require_once (QFWPATH.'/Init.php'); +$InitTime = microtime(true) - $InitTime; + +var_dump($InitTime < 0.01); + +--EXPECT-- +bool(true) diff --git a/tests/app/040_del_def.phpt b/tests/app/040_del_def.phpt new file mode 100644 index 0000000..0933749 --- /dev/null +++ b/tests/app/040_del_def.phpt @@ -0,0 +1,48 @@ +--TEST-- +QFW: test delDef +--FILE-- +<?php +require dirname(__FILE__).'/init.php'; + +QFW::Init(); +QFW::$config['default']['module'] = 'aaa'; +QFW::$config['default']['controller'] = 'bbb'; +QFW::$config['default']['action'] = 'ccc'; + +$test = array( + 'aaa/bbb/ccc' => '', + 'aaa/bbb/fff' => 'bbb/fff', + 'aaa/eee/ccc' => 'eee', + 'aaa/eee/fff' => 'eee/fff', + 'ddd/bbb/ccc' => 'ddd/bbb', + 'ddd/bbb/fff' => 'ddd/bbb/fff', + 'ddd/eee/ccc' => 'ddd/eee', + 'ddd/eee/fff' => 'ddd/eee/fff', + 'aaa/bbb' => '', + 'aaa/eee' => 'eee', + 'ddd/bbb' => 'ddd/bbb', + 'ddd/eee' => 'ddd/eee', + 'aaa/ccc' => '', + 'aaa/fff' => 'fff', + 'ddd/ccc' => 'ddd', + 'ddd/fff' => 'ddd/fff', + 'bbb/ccc' => '', + 'bbb/fff' => 'bbb/fff', + 'eee/ccc' => 'eee', + 'eee/fff' => 'eee/fff', + 'aaa' => '', + 'ddd' => 'ddd', + 'bbb' => '', + 'eee' => 'eee', + 'ccc' => '', + 'fff' => 'fff', +); + +QFW::$router->__construct(APPPATH); + +foreach($test as $in=>$out) + if (QFW::$router->delDef($in) != $out) + echo $in.' != '.$out."\n"; + + +--EXPECT-- ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Url.php | 7 +- tests/QFW/FrameworkTests.php | 20 - tests/QFW/QFWTest.php | 66 --- tests/QFWTests.php | 2 - tests/Smarty/README | 32 -- tests/Smarty/SmartyTest.php | 449 -------------------- tests/Smarty/configs/globals_double_quotes.conf | 1 - tests/Smarty/configs/globals_single_quotes.conf | 1 - tests/Smarty/templates/assign_var.tpl | 1 - tests/Smarty/templates/constant.tpl | 1 - tests/Smarty/templates/index.tpl | 1 - tests/Smarty/templates/parse_math.tpl | 12 - tests/Smarty/templates/parse_obj_meth.tpl | 8 - .../{010_http_host.phpt => 030_init_time.phpt_} | 12 +- tests/app/040_del_def.phpt | 48 ++ .../{020_main_page.phpt => 050_double_run.phpt} | 6 +- 16 files changed, 65 insertions(+), 602 deletions(-) delete mode 100644 tests/QFW/FrameworkTests.php delete mode 100644 tests/QFW/QFWTest.php delete mode 100644 tests/Smarty/README delete mode 100644 tests/Smarty/SmartyTest.php delete mode 100644 tests/Smarty/configs/globals_double_quotes.conf delete mode 100644 tests/Smarty/configs/globals_single_quotes.conf delete mode 100644 tests/Smarty/templates/assign_var.tpl delete mode 100644 tests/Smarty/templates/constant.tpl delete mode 100644 tests/Smarty/templates/index.tpl delete mode 100644 tests/Smarty/templates/parse_math.tpl delete mode 100644 tests/Smarty/templates/parse_obj_meth.tpl copy tests/app/{010_http_host.phpt => 030_init_time.phpt_} (62%) create mode 100644 tests/app/040_del_def.phpt copy tests/app/{020_main_page.phpt => 050_double_run.phpt} (56%) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-25 14:40:43
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via e38332209fb0516ed4b399386641e66f7c848cfd (commit) from 4ac579b1f96ddeb51d8925ffaef275d260918cf5 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit e38332209fb0516ed4b399386641e66f7c848cfd Author: Ivan1986 <iva...@li...> Date: Wed Aug 25 18:39:23 2010 +0400 add test app diff --git a/QFW/config.php b/QFW/config.php index a6aa01a..4cf48f2 100644 --- a/QFW/config.php +++ b/QFW/config.php @@ -76,11 +76,11 @@ $config['cache'] = array( 'namespace' => '', 'tags' => false, ), - 'MCA' => array( + /*'MCA' => array( 'module' => 'Xcache', 'namespace' => '', 'tags' => false, - ), + ),*/ ); $config['templater'] = array( diff --git a/tests/app/010_http_host.phpt b/tests/app/010_http_host.phpt new file mode 100644 index 0000000..372ea73 --- /dev/null +++ b/tests/app/010_http_host.phpt @@ -0,0 +1,19 @@ +--TEST-- +QFW: test _SERVER HTTP_HOST +--FILE-- +<?php + +define ('DOC_ROOT', dirname(__FILE__)); +define ('ROOTPATH', dirname(dirname(dirname(__FILE__)))); +define ('APPPATH', ROOTPATH . '/application'); +define ('TMPPATH', ROOTPATH . '/tmp'); +define ('QFWPATH', ROOTPATH . '/QFW'); +define ('LIBPATH', ROOTPATH . '/lib'); +define ('MODPATH', APPPATH . '/_common/models'); + +require (QFWPATH.'/Init.php'); + +QFW::$router->route(); + +--EXPECT-- +$_SERVER['HTTP_HOST'] NOT SET diff --git a/tests/app/020_main_page.phpt b/tests/app/020_main_page.phpt new file mode 100644 index 0000000..b72436d --- /dev/null +++ b/tests/app/020_main_page.phpt @@ -0,0 +1,11 @@ +--TEST-- +QFW: main page test - default MCA +--FILE-- +<?php +require dirname(__FILE__).'/init.php'; + +QFW::$router->route(''); + +--EXPECT-- +Основной шаблон +Корневое действие сайта diff --git a/tests/app/init.php b/tests/app/init.php new file mode 100644 index 0000000..a0c53bc --- /dev/null +++ b/tests/app/init.php @@ -0,0 +1,15 @@ +<?php + define ('DOC_ROOT', dirname(__FILE__)); + define ('ROOTPATH', dirname(dirname(dirname(__FILE__)))); + define ('APPPATH', dirname(dirname(__FILE__)).'/testapp'); + define ('TMPPATH', ROOTPATH . '/tmp'); + define ('QFWPATH', ROOTPATH . '/QFW'); + define ('LIBPATH', ROOTPATH . '/lib'); + define ('MODPATH', APPPATH . '/_common/models'); + + $_SERVER['HTTP_HOST'] = 'test'; + + require (QFWPATH.'/Init.php'); + + +?> \ No newline at end of file diff --git a/tests/testapp/_common/models/.emptydir b/tests/testapp/_common/models/.emptydir new file mode 100644 index 0000000..625cb36 --- /dev/null +++ b/tests/testapp/_common/models/.emptydir @@ -0,0 +1 @@ +models dir \ No newline at end of file diff --git a/tests/testapp/_common/slots/.emptydir b/tests/testapp/_common/slots/.emptydir new file mode 100644 index 0000000..e89abae --- /dev/null +++ b/tests/testapp/_common/slots/.emptydir @@ -0,0 +1 @@ +slots dir \ No newline at end of file diff --git a/tests/testapp/_common/tags/.emptydir b/tests/testapp/_common/tags/.emptydir new file mode 100644 index 0000000..aef7fb2 --- /dev/null +++ b/tests/testapp/_common/tags/.emptydir @@ -0,0 +1 @@ +tags dir \ No newline at end of file diff --git a/tests/testapp/default/controllers/IndexController.php b/tests/testapp/default/controllers/IndexController.php new file mode 100644 index 0000000..810f04d --- /dev/null +++ b/tests/testapp/default/controllers/IndexController.php @@ -0,0 +1,18 @@ +<?php + +require_once(QFWPATH.'/QuickFW/Auth.php'); + +class IndexController extends QuickFW_Auth +{ + public function __construct() + { + } + + public function indexAction() + { + return 'Корневое действие сайта'; + } + +} + +?> \ No newline at end of file diff --git a/tests/testapp/default/templates/main.html b/tests/testapp/default/templates/main.html new file mode 100644 index 0000000..e0a9b74 --- /dev/null +++ b/tests/testapp/default/templates/main.html @@ -0,0 +1,2 @@ +Основной шаблон +<?php echo $content; ?> diff --git a/tests/testapp/helper b/tests/testapp/helper new file mode 120000 index 0000000..102313d --- /dev/null +++ b/tests/testapp/helper @@ -0,0 +1 @@ +../../application/helper \ No newline at end of file diff --git a/tests/testapp/rewrite.php b/tests/testapp/rewrite.php new file mode 100644 index 0000000..5a8b367 --- /dev/null +++ b/tests/testapp/rewrite.php @@ -0,0 +1,8 @@ +<?php + +$rewrite = array( +); +$backrewrite = array( +); + +?> \ No newline at end of file ----------------------------------------------------------------------- Summary of changes: QFW/config.php | 4 ++-- tests/app/010_http_host.phpt | 19 +++++++++++++++++++ tests/app/020_main_page.phpt | 11 +++++++++++ www/index.php => tests/app/init.php | 14 ++++++-------- .../testapp}/_common/models/.emptydir | 0 .../testapp}/_common/slots/.emptydir | 0 .../testapp}/_common/tags/.emptydir | 0 .../default/controllers/IndexController.php | 18 ++++++++++++++++++ tests/testapp/default/templates/main.html | 2 ++ tests/testapp/helper | 1 + {application => tests/testapp}/rewrite.php | 0 11 files changed, 59 insertions(+), 10 deletions(-) create mode 100644 tests/app/010_http_host.phpt create mode 100644 tests/app/020_main_page.phpt copy www/index.php => tests/app/init.php (61%) copy {application => tests/testapp}/_common/models/.emptydir (100%) copy {application => tests/testapp}/_common/slots/.emptydir (100%) copy {application => tests/testapp}/_common/tags/.emptydir (100%) create mode 100644 tests/testapp/default/controllers/IndexController.php create mode 100644 tests/testapp/default/templates/main.html create mode 120000 tests/testapp/helper copy {application => tests/testapp}/rewrite.php (100%) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-24 13:42:25
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 4ac579b1f96ddeb51d8925ffaef275d260918cf5 (commit) from 936d9fccedd497c7283587ebc88c6758252a06f7 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 4ac579b1f96ddeb51d8925ffaef275d260918cf5 Author: Ivan1986 <iva...@li...> Date: Tue Aug 24 17:41:58 2010 +0400 Сжатие в memcache diff --git a/QFW/Cacher/Memcache.php b/QFW/Cacher/Memcache.php index a7ace9d..4e375ea 100644 --- a/QFW/Cacher/Memcache.php +++ b/QFW/Cacher/Memcache.php @@ -3,6 +3,7 @@ class Cacher_Memcache implements Zend_Cache_Backend_Interface { protected $mc; + protected $compress; public function __construct() { @@ -18,6 +19,7 @@ class Cacher_Memcache implements Zend_Cache_Backend_Interface isset($directives['port']) ? $directives['port'] : '11211'); return; } + $this->compress = !empty($directives['compress']) ? MEMCACHE_COMPRESSED : 0; foreach($directives['servers'] as $server) $this->mc->addServer($server['host'], $server['port']); @@ -30,7 +32,7 @@ class Cacher_Memcache implements Zend_Cache_Backend_Interface public function save($data, $id, $tags = array(), $specificLifetime = 3600) { - return $this->mc->set($id, $data, 0, $specificLifetime); + return $this->mc->set($id, $data, $this->compress, $specificLifetime); } public function load($id, $doNotTest = false) ----------------------------------------------------------------------- Summary of changes: QFW/Cacher/Memcache.php | 4 +++- 1 files changed, 3 insertions(+), 1 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-24 11:34:33
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 936d9fccedd497c7283587ebc88c6758252a06f7 (commit) via faa3d7492d8b959f6d57b1865e177765c64b9fb9 (commit) from 60693af34d92bea06925807c109a096a5b16895d (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 936d9fccedd497c7283587ebc88c6758252a06f7 Author: Ivan1986 <iva...@li...> Date: Tue Aug 24 15:33:45 2010 +0400 remove ErrorStack diff --git a/QFW/config.php b/QFW/config.php index 6b10fe4..a6aa01a 100644 --- a/QFW/config.php +++ b/QFW/config.php @@ -34,7 +34,6 @@ $config['redirection']=array( */ $config['QFW'] = array( 'release' => false, /* статус проекта на данном хосте - отладка и всякие быстрые компиляции */ - 'ErrorStack' => false, /* вывод стека вызовов в сообщении об ошибке в БД */ 'cacheSessions' => false, /* Хранить сессии в кеше, не использовать стандартный механизм */ 'autoload' => false, /* включить автолоад false|true|string */ 'auto404' => false, /* не перенаправлять на дефолтовый контроллер все запросы */ diff --git a/application/default.php b/application/default.php index 19f25b9..0cecf94 100644 --- a/application/default.php +++ b/application/default.php @@ -82,7 +82,6 @@ $config['cache'] = array( */ $config['QFW'] = array( 'release' => false, /* статус проекта на данном хосте - отладка и всякие быстрые компиляции */ - 'ErrorStack' => false, /* вывод стека вызовов в сообщении об ошибке в БД */ 'cacheSessions' => false, /* Хранить сессии в кеше, не использовать стандартный механизм */ 'autoload' => true, /* включить автолоад false|true|string */ 'auto404' => false, /* не перенаправлять на дефолтовый контроллер все запросы */ commit faa3d7492d8b959f6d57b1865e177765c64b9fb9 Author: Ivan1986 <iva...@li...> Date: Tue Aug 24 15:32:32 2010 +0400 update Dbsimple diff --git a/lib/DbSimple/Connect.php b/lib/DbSimple/Connect.php index 0552859..b3dec28 100644 --- a/lib/DbSimple/Connect.php +++ b/lib/DbSimple/Connect.php @@ -120,20 +120,13 @@ class DbSimple_Connect } /** - * Функция обработки ошибок - выводит сообщение об ошибке на тестовом - * на продакшене показывает 404 и пишит в sql.log + * Функция обработки ошибок - стандартный обработчик * Все вызовы без @ прекращают выполнение скрипта */ public function errorHandler($msg, $info) { // Если использовалась @, ничего не делать. if (!error_reporting()) return; - if (QFW::$config['QFW']['release']) - { - require_once LIBPATH.'/Log.php'; - Log::log('SQL Error - '.$msg,'sql'); - QFW::$router->show404(); - } // Выводим подробную информацию об ошибке. echo "SQL Error: $msg<br><pre>"; print_r($info); @@ -156,15 +149,17 @@ class DbSimple_Connect $prev = $this->errorHandler; $this->errorHandler = $handler; if ($this->DbSimple) - return $this->DbSimple->setErrorHandler($handler); + $this->DbSimple->setErrorHandler($handler); + return $prev; } /** @var callback обработчик ошибок */ private $errorHandler = null; /** - * array parseDSN(string $dsn) * Разбирает строку DSN в массив параметров подключения к базе + * + * @param array parseDSN(string $dsn) */ protected function parseDSN($dsn) { diff --git a/lib/DbSimple/Generic.php b/lib/DbSimple/Database.php similarity index 91% copy from lib/DbSimple/Generic.php copy to lib/DbSimple/Database.php index 532746c..112b444 100644 --- a/lib/DbSimple/Generic.php +++ b/lib/DbSimple/Database.php @@ -1,6 +1,7 @@ <?php + /** - * DbSimple_Generic: universal database connected by DSN. + * DbSimple_Database: Base class for all databases. * (C) Dk Lab, http://en.dklab.ru * * This library is free software; you can redistribute it and/or @@ -9,7 +10,7 @@ * version 2.1 of the License, or (at your option) any later version. * See http://www.gnu.org/copyleft/lesser.html * - * Use class DbSimple_Connect if you don't know + * Use static DbSimple_Generic::connect($dsn) call if you don't know * database type and parameters, but have its DSN. * * Additional keys can be added by appending a URI query string to the @@ -32,10 +33,9 @@ * initial author: Tomas V.V.Cox <co...@id...>. * * Contains 3 classes: - * - DbSimple_Generic: database factory class - * - DbSimple_Generic_Database: common database methods - * - DbSimple_Generic_Blob: common BLOB support - * - DbSimple_Generic_LastError: error reporting and tracking + * - DbSimple_Database: common database methods + * - DbSimple_Blob: common BLOB support + * - DbSimple_LastError: error reporting and tracking * * Special result-set fields: * - ARRAY_KEY* ("*" means "anything") @@ -55,17 +55,34 @@ * @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/ * @author Ivan Borzenkov, http://forum.dklab.ru/users/Ivan1986/ * - * @version 2.x $Id: Generic.php 226 2007-09-17 21:00:15Z dk $ + * @version 2.x $Id$ + */ + +/** + * Use this constant as placeholder value to skip optional SQL block [...]. */ +if (!defined('DBSIMPLE_SKIP')) + define('DBSIMPLE_SKIP', log(0)); /** + * Names of special columns in result-set which is used + * as array key (or karent key in forest-based resultsets) in + * resulting hash. + */ +if (!defined('DBSIMPLE_ARRAY_KEY')) + define('DBSIMPLE_ARRAY_KEY', 'ARRAY_KEY'); // hash-based resultset support +if (!defined('DBSIMPLE_PARENT_KEY')) + define('DBSIMPLE_PARENT_KEY', 'PARENT_KEY'); // forrest-based resultset support + +/** + * * Base class for all databases. * Can create transactions and new BLOBs, parse DSNs. * * Logger is COMMON for multiple transactions. * Error handler is private for each transaction and database. */ -abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError +abstract class DbSimple_Database extends DbSimple_LastError { /** * Public methods. @@ -213,6 +230,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError return $this->_performEscape($s, $isIdent); } + /** * DbSimple_SubQuery subquery(string $query [, $arg1] [,$arg2] ...) * Выполняет разворачивание плейсхолдеров без коннекта к базе @@ -226,6 +244,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError return new DbSimple_SubQuery($args); } + /** * callback setLogger(callback $logger) * Set query logger called before each query is executed. @@ -388,6 +407,26 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError /** + * array parseDSN(mixed $dsn) + * Parse a data source name. + * See parse_url() for details. + */ + protected function parseDSN($dsn) + { + if (is_array($dsn)) return $dsn; + $parsed = @parse_url($dsn); + if (!$parsed) return null; + $params = null; + if (!empty($parsed['query'])) { + parse_str($parsed['query'], $params); + $parsed += $params; + } + $parsed['dsn'] = $dsn; + return $parsed; + } + + + /** * array _query($query, &$total) * See _performQuery(). */ @@ -419,6 +458,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $result = isset($cacheData['result']) ? $cacheData['result'] : null; $rows = isset($cacheData['rows']) ? $cacheData['rows'] : null; + $cache_params = $this->attributes['CACHE']; // Calculating cache time to live @@ -436,8 +476,8 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $m = null; preg_match($re, $cache_params, $m); $ttl = (isset($m[3])?$m[3]:0) - + (isset($m[2])?$m[2]:0) * 60 - + (isset($m[1])?$m[1]:0) * 3600; + + (isset($m[2])?$m[2]:0) * 60 + + (isset($m[1])?$m[1]:0) * 3600; // Cutting out time param - now there are just fields for uniqKey or nothing $cache_params = trim(preg_replace($re, '', $cache_params, 1)); @@ -448,7 +488,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $dummy = null; // There is no need in query, cos' needle in $this->attributes['CACHE'] $this->_transformQuery($dummy, 'UNIQ_KEY'); - $uniq_key = call_user_func_array(array(&$this, 'select'), array($dummy)); + $uniq_key = call_user_func(array(&$this, 'select'), $dummy); $uniq_key = md5(serialize($uniq_key)); } // Check TTL? @@ -463,14 +503,14 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError else $cache_it = true; } - if (false === $rows || true === $cache_it) - { + if (false === $rows || true === $cache_it) { $this->_logQuery($query); // Run the query (counting time). $qStart = microtime(true); $result = $this->_performQuery($query); $fetchTime = $firstFetchTime = 0; + if (is_resource($result)) { $rows = array(); // Fetch result row by row. @@ -493,10 +533,14 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $this->_logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows); // Prepare BLOB objects if needed. - if (is_array($rows) && !empty($this->attributes['BLOB_OBJ'])) - foreach ($this->_performGetBlobFieldNames($result) as $name) - foreach ($rows as $r=>$v) - $rows[$r][$name] = $this->_performNewBlob($v[$name]); + if (is_array($rows) && !empty($this->attributes['BLOB_OBJ'])) { + $blobFieldNames = $this->_performGetBlobFieldNames($result); + foreach ($blobFieldNames as $name) { + for ($r = count($rows)-1; $r>=0; $r--) { + $rows[$r][$name] =& $this->_performNewBlob($rows[$r][$name]); + } + } + } // Transform resulting rows. $result = $this->_transformResult($rows); @@ -559,14 +603,13 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError return $options; case 'UNIQ_KEY': $q = $this->attributes['CACHE']; - $i = 0; - $query = " -- UNIQ_KEY\n"; + $query = array(); while(preg_match('/(\w+)\.\w+/sx', $q, $m)) { - if($i > 0)$query .= "\nUNION\n"; - $query .= 'SELECT MAX('.$m[0].') AS M, COUNT(*) AS C FROM '.$m[1]; + $query[] = 'SELECT MAX('.$m[0].') AS M, COUNT(*) AS C FROM '.$m[1]; $q = substr($q, strlen($m[0])); - $i++; } + $query = " -- UNIQ_KEY\n". + join("\nUNION\n", $query); return true; } // No such transform. @@ -631,13 +674,13 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError # Comment. -- [^\r\n]* ) - | + | (?> # DB-specifics. ' . trim($this->_performGetPlaceholderIgnoreRe()) . ' ) ) - | + | (?> # Optional blocks \{ @@ -645,7 +688,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError ( (?> (?>(\??)[^{}]+) | (?R) )* ) #1 \} ) - | + | (?> # Placeholder (\?) ( [_dsafn&|\#]? ) #2 #3 @@ -658,7 +701,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError ); return $query; } - + static $join = array( '|' => array('inner' => ' AND ', 'outer' => ') OR (',), '&' => array('inner' => ' OR ', 'outer' => ') AND (',), @@ -720,7 +763,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError if ($v instanceof DbSimple_SubQuery) $v = $v->get($this->_placeholderNativeArgs); else - $v = $v === null? 'NULL' : $this->escape($v); + $v = $v === null? 'NULL' : $this->escape($v); if (!is_int($k)) { $k = $this->escape($k, true); $parts[] = "$prefix$k=$v"; @@ -741,17 +784,16 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError { if ($value instanceof DbSimple_SubQuery) return $value->get($this->_placeholderNativeArgs); - $value = $this->_addPrefix2Table($value); - return $this->escape($value, true); + return $this->escape($this->_addPrefix2Table($value), true); } $parts = array(); - foreach ($value as $table => $identifiers) { - if (!is_array($identifiers)) $identifiers = array($identifiers); + foreach ($value as $table => $identifiers) + { + if (!is_array($identifiers)) + $identifiers = array($identifiers); $prefix = ''; - if (!is_int($table)) { - $table = $this->_addPrefix2Table($table); - $prefix = $this->escape($table, true) . '.'; - } + if (!is_int($table)) + $prefix = $this->escape($this->_addPrefix2Table($table), true) . '.'; foreach ($identifiers as $identifier) if ($identifier instanceof DbSimple_SubQuery) $parts[] = $identifier->get($this->_placeholderNativeArgs); @@ -767,26 +809,23 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError return empty($value)? 'NULL' : intval($value); } + // Native arguments are not processed. + if ($this->_placeholderNativeArgs !== null) { + $this->_placeholderNativeArgs[] = $value; + return $this->_performGetNativePlaceholderMarker(count($this->_placeholderNativeArgs) - 1); + } + // In non-native mode arguments are quoted. if ($value === null) return 'NULL'; - switch ($type) { + case '': + if (!is_scalar($value)) return 'DBSIMPLE_ERROR_VALUE_NOT_SCALAR'; + return $this->escape($value); case 'd': return intval($value); case 'f': return str_replace(',', '.', floatval($value)); } - - // нативные плейсхолдеры необходимо обработать после числовых из-за бага в PDO - // Native arguments are not processed. - if ($this->_placeholderNativeArgs !== null) { - $this->_placeholderNativeArgs[] = $value; - return $this->_performGetNativePlaceholderMarker(count($this->_placeholderNativeArgs) - 1); - } - - if (!is_scalar($value)) - return 'DBSIMPLE_ERROR_VALUE_NOT_SCALAR'; - // By default - escape as string. return $this->escape($value); } @@ -797,7 +836,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $prev = $this->_placeholderNoValueFound; if ($this->_placeholderNativeArgs !== null) $prevPh = $this->_placeholderNativeArgs; - + // Проверка на {? } - условный блок $skip = false; if ($m[2]=='?') @@ -805,12 +844,12 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $skip = array_pop($this->_placeholderArgs) === DBSIMPLE_SKIP; $block[0] = ' '; } - + $block = $this->_expandOptionalBlock($block); - + if ($skip) $block = ''; - + if ($this->_placeholderNativeArgs !== null) if ($this->_placeholderNoValueFound) $this->_placeholderNativeArgs = $prevPh; @@ -822,6 +861,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError return $m[0]; } + /** * Заменяет ?_ на текущий префикс * @@ -835,6 +875,13 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError return $table; } + + /** + * Разбирает опциональный блок - условие | + * + * @param string $block блок, который нужно разобрать + * @return string что получается в результате разбора блока + */ private function _expandOptionalBlock($block) { $alts = array(); @@ -871,7 +918,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError } return $r; } - + /** * void _setLastError($code, $msg, $query) @@ -911,7 +958,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError */ private function _transformResult($rows) { - // Результат не массив - выходим + // is not array if (!is_array($rows) || !$rows) return $rows; @@ -1059,8 +1106,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $this->_statistics['count']++; // If no logger, economize CPU resources and actually log nothing. - if (!$this->_logger) - return; + if (!$this->_logger) return; $dt = round($queryTime * 1000); $firstFetchTime = round($firstFetchTime*1000); @@ -1101,6 +1147,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $this->_logQuery($log, true); } + // Identifiers prefix (used for ?_ placeholder). private $_identPrefix = ''; @@ -1121,16 +1168,16 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError /** * When string representation of row (in characters) is greater than this, * row data will not be logged. - */ + */ private $MAX_LOG_ROW_LEN = 128; } /** - * Интерфейс BLOB. - * Описывает функции обекта типа BLOB - ему должны соответствовать классы, возвращаемые в качестве BLOB полей. + * Database BLOB. + * Can read blob chunk by chunk, write data to BLOB. */ -interface DbSimple_Generic_Blob +interface DbSimple_Blob { /** * string read(int $length) @@ -1155,9 +1202,9 @@ interface DbSimple_Generic_Blob * Closes the blob. Return its ID. No other way to obtain this ID! */ public function close(); - } + /** * Класс для хранения подзапроса - результата выполнения функции * DbSimple_Generic_Database::subquery @@ -1166,8 +1213,7 @@ interface DbSimple_Generic_Blob class DbSimple_SubQuery { private $query=array(); - - + public function __construct(array $q) { $this->query = $q; @@ -1185,18 +1231,17 @@ class DbSimple_SubQuery $ph = array_merge($ph, array_slice($this->query,1,null,true)); return $this->query[0]; } - } + /** * Support for error tracking. * Can hold error messages, error queries and build proper stacktraces. */ -abstract class DbSimple_Generic_LastError +abstract class DbSimple_LastError { public $error = null; public $errmsg = null; - private $showStack = false; private $errorHandler = null; private $ignoresInTraceRe = 'DbSimple_.*::.* | call_user_func.*'; @@ -1204,7 +1249,7 @@ abstract class DbSimple_Generic_LastError * abstract void _logQuery($query) * Must be overriden in derived class. */ - protected abstract function _logQuery($query); + abstract protected function _logQuery($query); /** * void _resetLastError() @@ -1223,29 +1268,16 @@ abstract class DbSimple_Generic_LastError protected function _setLastError($code, $msg, $query) { $context = "unknown"; + if ($t = $this->findLibraryCaller()) { + $context = (isset($t['file'])? $t['file'] : '?') . ' line ' . (isset($t['line'])? $t['line'] : '?'); + } $this->error = array( 'code' => $code, 'message' => rtrim($msg), 'query' => $query, - 'context' => '', + 'context' => $context, ); - if ($t = $this->findLibraryCaller($this->showStack)) - { - if (!$this->showStack) - $this->error['context'] = (isset($t['file'])? $t['file'] : '?') . - ' line ' . (isset($t['line'])? $t['line'] : '?'); - else - { - $this->error['context'] = (isset($t[0]['file'])? $t[0]['file'] : '?') . - ' line ' . (isset($t[0]['line'])? $t[0]['line'] : '?'); - $this->error['stack'] = array(); - foreach($t as $f) - $this->error['stack'][] = (isset($f['class']) ? $f['class'].$f['type'] : ''). - (isset($f['function']) ? $f['function'] : '?').'() '. - (isset($f['file'])? $f['file'] : '?') . ':' . (isset($f['line'])? $f['line'] : '?'); - } - } - $this->errmsg = rtrim($msg) . ($this->error['context']? ' at '.$this->error['context'] : ''); + $this->errmsg = rtrim($msg) . ($context? " at $context" : ""); $this->_logQuery(" -- error #".$code.": ".preg_replace('/(\r?\n)+/s', ' ', $this->errmsg)); @@ -1258,21 +1290,21 @@ abstract class DbSimple_Generic_LastError /** - * callback setErrorHandler(callback $handler, bool $stack) + * callback setErrorHandler(callback $handler) * Set new error handler called on database errors. * Handler gets 3 arguments: * - error message * - full error context information (last query etc.) */ - public function setErrorHandler($handler, $stack=false) + public function setErrorHandler($handler) { $prev = $this->errorHandler; $this->errorHandler = $handler; - $this->showStack = $stack; // In case of setting first error handler for already existed // error - call the handler now (usual after connect()). - if (!$prev && $this->error) + if (!$prev && $this->error) { call_user_func($this->errorHandler, $this->errmsg, $this->error); + } return $prev; } @@ -1291,12 +1323,12 @@ abstract class DbSimple_Generic_LastError * Return part of stacktrace before calling first library method. * Used in debug purposes (query logging etc.). */ - protected function findLibraryCaller($all = false) + protected function findLibraryCaller() { $caller = call_user_func( array(&$this, 'debug_backtrace_smart'), $this->ignoresInTraceRe, - !$all + true ); return $caller; } @@ -1355,4 +1387,4 @@ abstract class DbSimple_Generic_LastError } } -?> \ No newline at end of file +?> diff --git a/lib/DbSimple/Generic.php b/lib/DbSimple/Generic.php index 532746c..43dbe14 100644 --- a/lib/DbSimple/Generic.php +++ b/lib/DbSimple/Generic.php @@ -9,7 +9,7 @@ * version 2.1 of the License, or (at your option) any later version. * See http://www.gnu.org/copyleft/lesser.html * - * Use class DbSimple_Connect if you don't know + * Use static DbSimple_Generic::connect($dsn) call if you don't know * database type and parameters, but have its DSN. * * Additional keys can be added by appending a URI query string to the @@ -53,1306 +53,93 @@ * * @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/ * @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/ - * @author Ivan Borzenkov, http://forum.dklab.ru/users/Ivan1986/ * - * @version 2.x $Id: Generic.php 226 2007-09-17 21:00:15Z dk $ + * @version 2.x $Id$ */ /** - * Base class for all databases. - * Can create transactions and new BLOBs, parse DSNs. - * - * Logger is COMMON for multiple transactions. - * Error handler is private for each transaction and database. + * Use this constant as placeholder value to skip optional SQL block [...]. */ -abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError -{ - /** - * Public methods. - */ - - /** - * object blob($blob_id) - * Create new blob - */ - public function blob($blob_id = null) - { - $this->_resetLastError(); - return $this->_performNewBlob($blob_id); - } - - /** - * void transaction($mode) - * Create new transaction. - */ - public function transaction($mode=null) - { - $this->_resetLastError(); - $this->_logQuery('-- START TRANSACTION '.$mode); - return $this->_performTransaction($mode); - } - - /** - * mixed commit() - * Commit the transaction. - */ - public function commit() - { - $this->_resetLastError(); - $this->_logQuery('-- COMMIT'); - return $this->_performCommit(); - } - - /** - * mixed rollback() - * Rollback the transaction. - */ - public function rollback() - { - $this->_resetLastError(); - $this->_logQuery('-- ROLLBACK'); - return $this->_performRollback(); - } - - /** - * mixed select(string $query [, $arg1] [,$arg2] ...) - * Execute query and return the result. - */ - public function select($query) - { - $args = func_get_args(); - $total = false; - return $this->_query($args, $total); - } - - /** - * mixed selectPage(int &$total, string $query [, $arg1] [,$arg2] ...) - * Execute query and return the result. - * Total number of found rows (independent to LIMIT) is returned in $total - * (in most cases second query is performed to calculate $total). - */ - public function selectPage(&$total, $query) - { - $args = func_get_args(); - array_shift($args); - $total = true; - return $this->_query($args, $total); - } - - /** - * hash selectRow(string $query [, $arg1] [,$arg2] ...) - * Return the first row of query result. - * On errors return false and set last error. - * If no one row found, return array()! It is useful while debugging, - * because PHP DOES NOT generates notice on $row['abc'] if $row === null - * or $row === false (but, if $row is empty array, notice is generated). - */ - public function selectRow() - { - $args = func_get_args(); - $total = false; - $rows = $this->_query($args, $total); - if (!is_array($rows)) return $rows; - if (!count($rows)) return array(); - reset($rows); - return current($rows); - } - - /** - * array selectCol(string $query [, $arg1] [,$arg2] ...) - * Return the first column of query result as array. - */ - public function selectCol() - { - $args = func_get_args(); - $total = false; - $rows = $this->_query($args, $total); - if (!is_array($rows)) return $rows; - $this->_shrinkLastArrayDimensionCallback($rows); - return $rows; - } - - /** - * scalar selectCell(string $query [, $arg1] [,$arg2] ...) - * Return the first cell of the first column of query result. - * If no one row selected, return null. - */ - public function selectCell() - { - $args = func_get_args(); - $total = false; - $rows = $this->_query($args, $total); - if (!is_array($rows)) return $rows; - if (!count($rows)) return null; - reset($rows); - $row = current($rows); - if (!is_array($row)) return $row; - reset($row); - return current($row); - } - - /** - * mixed query(string $query [, $arg1] [,$arg2] ...) - * Alias for select(). May be used for INSERT or UPDATE queries. - */ - public function query() - { - $args = func_get_args(); - $total = false; - return $this->_query($args, $total); - } - - /** - * string escape(mixed $s, bool $isIdent=false) - * Enclose the string into database quotes correctly escaping - * special characters. If $isIdent is true, value quoted as identifier - * (e.g.: `value` in MySQL, "value" in Firebird, [value] in MSSQL). - */ - public function escape($s, $isIdent=false) - { - return $this->_performEscape($s, $isIdent); - } - - /** - * DbSimple_SubQuery subquery(string $query [, $arg1] [,$arg2] ...) - * Выполняет разворачивание плейсхолдеров без коннекта к базе - * Нужно для сложных запросов, состоящих из кусков, которые полезно сохранить - * - */ - public function subquery() - { - $args = func_get_args(); - $this->_expandPlaceholders($args,$this->_placeholderNativeArgs !== null); - return new DbSimple_SubQuery($args); - } - - /** - * callback setLogger(callback $logger) - * Set query logger called before each query is executed. - * Returns previous logger. - */ - public function setLogger($logger) - { - $prev = $this->_logger; - $this->_logger = $logger; - return $prev; - } - - /** - * callback setCacher(callback $cacher) - * Set cache mechanism called during each query if specified. - * Returns previous handler. - */ - public function setCacher(Zend_Cache_Backend_Interface $cacher=null) - { - $prev = $this->_cacher; - $this->_cacher = $cacher; - return $prev; - } - - /** - * string setIdentPrefix($prx) - * Set identifier prefix used for $_ placeholder. - */ - public function setIdentPrefix($prx) - { - $old = $this->_identPrefix; - if ($prx !== null) $this->_identPrefix = $prx; - return $old; - } - - /** - * string setCachePrefix($prx) - * Set cache prefix used in key caclulation. - */ - public function setCachePrefix($prx) - { - $old = $this->_cachePrefix; - if ($prx !== null) $this->_cachePrefix = $prx; - return $old; - } - - /** - * Задает имя класса строки - * - * <br>для следующего запроса каждая строка будет - * заменена классом, конструктору которого передается - * массив поле=>значение для этой строки - * - * @param string $name имя класса - * @return DbSimple_Generic_Database указатель на себя - */ - public function setClassName($name) - { - $this->_className = $name; - return $this; - } - - /** - * array getStatistics() - * Returns various statistical information. - */ - public function getStatistics() - { - return $this->_statistics; - } - - - /** - * string _performEscape(mixed $s, bool $isIdent=false) - */ - abstract protected function _performEscape($s, $isIdent=false); - - /** - * object _performNewBlob($id) - * - * Returns new blob object. - */ - abstract protected function _performNewBlob($id=null); - - /** - * list _performGetBlobFieldNames($resultResource) - * Get list of all BLOB field names in result-set. - */ - abstract protected function _performGetBlobFieldNames($result); - - /** - * mixed _performTransformQuery(array &$query, string $how) - * - * Transform query different way specified by $how. - * May return some information about performed transform. - */ - abstract protected function _performTransformQuery(&$queryMain, $how); - - - /** - * resource _performQuery($arrayQuery) - * Must return: - * - For SELECT queries: ID of result-set (PHP resource). - * - For other queries: query status (scalar). - * - For error queries: false (and call _setLastError()). - */ - abstract protected function _performQuery($arrayQuery); - - /** - * mixed _performFetch($resultResource) - * Fetch ONE NEXT row from result-set. - * Must return: - * - For SELECT queries: all the rows of the query (2d arrray). - * - For INSERT queries: ID of inserted row. - * - For UPDATE queries: number of updated rows. - * - For other queries: query status (scalar). - * - For error queries: false (and call _setLastError()). - */ - abstract protected function _performFetch($result); - - /** - * mixed _performTransaction($mode) - * Start new transaction. - */ - abstract protected function _performTransaction($mode=null); - - /** - * mixed _performCommit() - * Commit the transaction. - */ - abstract protected function _performCommit(); - - /** - * mixed _performRollback() - * Rollback the transaction. - */ - abstract protected function _performRollback(); - - /** - * string _performGetPlaceholderIgnoreRe() - * Return regular expression which matches ignored query parts. - * This is needed to skip placeholder replacement inside comments, constants etc. - */ - protected function _performGetPlaceholderIgnoreRe() - { - return ''; - } - - /** - * Returns marker for native database placeholder. E.g. in FireBird it is '?', - * in PostgreSQL - '$1', '$2' etc. - * - * @param int $n Number of native placeholder from the beginning of the query (begins from 0!). - * @return string String representation of native placeholder marker (by default - '?'). - */ - protected function _performGetNativePlaceholderMarker($n) - { - return '?'; - } - - - /** - * array _query($query, &$total) - * See _performQuery(). - */ - private function _query($query, &$total) - { - $this->_resetLastError(); - - // Fetch query attributes. - $this->attributes = $this->_transformQuery($query, 'GET_ATTRIBUTES'); - - // Modify query if needed for total counting. - if ($total) - $this->_transformQuery($query, 'CALC_TOTAL'); - - $rows = false; - $cache_it = false; - // Кешер у нас либо null либо соответствует Zend интерфейсу - if (!empty($this->attributes['CACHE']) && $this->_cacher) - { - - $hash = $this->_cachePrefix . md5(serialize($query)); - // Getting data from cache if possible - $fetchTime = $firstFetchTime = 0; - $qStart = microtime(true); - $cacheData = unserialize($this->_cacher->load($hash)); - $queryTime = microtime(true) - $qStart; - - $invalCache = isset($cacheData['invalCache']) ? $cacheData['invalCache'] : null; - $result = isset($cacheData['result']) ? $cacheData['result'] : null; - $rows = isset($cacheData['rows']) ? $cacheData['rows'] : null; - - $cache_params = $this->attributes['CACHE']; - - // Calculating cache time to live - $re = '/ - (?> - ([0-9]+) #1 - hours - h)? [ \t]* - (?> - ([0-9]+) #2 - minutes - m)? [ \t]* - (?> - ([0-9]+) #3 - seconds - s?)? (,)? - /sx'; - $m = null; - preg_match($re, $cache_params, $m); - $ttl = (isset($m[3])?$m[3]:0) - + (isset($m[2])?$m[2]:0) * 60 - + (isset($m[1])?$m[1]:0) * 3600; - // Cutting out time param - now there are just fields for uniqKey or nothing - $cache_params = trim(preg_replace($re, '', $cache_params, 1)); - - $uniq_key = null; - - // UNIQ_KEY calculation - if (!empty($cache_params)) { - $dummy = null; - // There is no need in query, cos' needle in $this->attributes['CACHE'] - $this->_transformQuery($dummy, 'UNIQ_KEY'); - $uniq_key = call_user_func_array(array(&$this, 'select'), array($dummy)); - $uniq_key = md5(serialize($uniq_key)); - } - // Check TTL? - $ok = empty($ttl) || $cacheData; - - // Invalidate cache? - if ($ok && $uniq_key == $invalCache) { - $this->_logQuery($query); - $this->_logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows); - - } - else $cache_it = true; - } - - if (false === $rows || true === $cache_it) - { - $this->_logQuery($query); - - // Run the query (counting time). - $qStart = microtime(true); - $result = $this->_performQuery($query); - $fetchTime = $firstFetchTime = 0; - if (is_resource($result)) { - $rows = array(); - // Fetch result row by row. - $fStart = microtime(true); - $row = $this->_performFetch($result); - $firstFetchTime = microtime(true) - $fStart; - if ($row !== false) { - $rows[] = $row; - while ($row=$this->_performFetch($result)) { - $rows[] = $row; - } - } - $fetchTime = microtime(true) - $fStart; - } else { - $rows = $result; - } - $queryTime = microtime(true) - $qStart; - - // Log query statistics. - $this->_logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows); - - // Prepare BLOB objects if needed. - if (is_array($rows) && !empty($this->attributes['BLOB_OBJ'])) - foreach ($this->_performGetBlobFieldNames($result) as $name) - foreach ($rows as $r=>$v) - $rows[$r][$name] = $this->_performNewBlob($v[$name]); - - // Transform resulting rows. - $result = $this->_transformResult($rows); - - // Storing data in cache - if ($cache_it && $this->_cacher) - { - $this->_cacher->save( - serialize(array( - 'invalCache' => $uniq_key, - 'result' => $result, - 'rows' => $rows - )), - $hash, - array(), - $ttl==0?false:$ttl - ); - } - - } - // Count total number of rows if needed. - if (is_array($result) && $total) { - $this->_transformQuery($query, 'GET_TOTAL'); - $total = call_user_func_array(array(&$this, 'selectCell'), $query); - } - - if ($this->_className) - { - foreach($result as $k=>$v) - $result[$k] = new $this->_className($v); - $this->_className = ''; - } - - return $result; - } - - - /** - * mixed _transformQuery(array &$query, string $how) - * - * Transform query different way specified by $how. - * May return some information about performed transform. - */ - private function _transformQuery(&$query, $how) - { - // Do overriden transformation. - $result = $this->_performTransformQuery($query, $how); - if ($result === true) return $result; - // Common transformations. - switch ($how) { - case 'GET_ATTRIBUTES': - // Extract query attributes. - $options = array(); - $q = $query[0]; - $m = null; - while (preg_match('/^ \s* -- [ \t]+ (\w+): ([^\r\n]+) [\r\n]* /sx', $q, $m)) { - $options[$m[1]] = trim($m[2]); - $q = substr($q, strlen($m[0])); - } - return $options; - case 'UNIQ_KEY': - $q = $this->attributes['CACHE']; - $i = 0; - $query = " -- UNIQ_KEY\n"; - while(preg_match('/(\w+)\.\w+/sx', $q, $m)) { - if($i > 0)$query .= "\nUNION\n"; - $query .= 'SELECT MAX('.$m[0].') AS M, COUNT(*) AS C FROM '.$m[1]; - $q = substr($q, strlen($m[0])); - $i++; - } - return true; - } - // No such transform. - $this->_setLastError(-1, "No such transform type: $how", $query); - } - - - /** - * void _expandPlaceholders(array &$queryAndArgs, bool $useNative=false) - * Replace placeholders by quoted values. - * Modify $queryAndArgs. - */ - protected function _expandPlaceholders(&$queryAndArgs, $useNative=false) - { - $cacheCode = null; - if ($this->_logger) { - // Serialize is much faster than placeholder expansion. So use caching. - $cacheCode = md5(serialize($queryAndArgs) . '|' . $useNative . '|' . $this->_identPrefix); - if (isset($this->_placeholderCache[$cacheCode])) { - $queryAndArgs = $this->_placeholderCache[$cacheCode]; - return; - } - } - - if (!is_array($queryAndArgs)) { - $queryAndArgs = array($queryAndArgs); - } - - $this->_placeholderNativeArgs = $useNative? array() : null; - $this->_placeholderArgs = array_reverse($queryAndArgs); - - $query = array_pop($this->_placeholderArgs); // array_pop is faster than array_shift - - // Do all the work. - $this->_placeholderNoValueFound = false; - $query = $this->_expandPlaceholdersFlow($query); - - if ($useNative) { - array_unshift($this->_placeholderNativeArgs, $query); - $queryAndArgs = $this->_placeholderNativeArgs; - } else { - $queryAndArgs = array($query); - } - - if ($cacheCode) { - $this->_placeholderCache[$cacheCode] = $queryAndArgs; - } - } - - - /** - * Do real placeholder processing. - * Imply that all interval variables (_placeholder_*) already prepared. - * May be called recurrent! - */ - private function _expandPlaceholdersFlow($query) - { - $re = '{ - (?> - # Ignored chunks. - (?> - # Comment. - -- [^\r\n]* - ) - | - (?> - # DB-specifics. - ' . trim($this->_performGetPlaceholderIgnoreRe()) . ' - ) - ) - | - (?> - # Optional blocks - \{ - # Use "+" here, not "*"! Else nested blocks are not processed well. - ( (?> (?>(\??)[^{}]+) | (?R) )* ) #1 - \} - ) - | - (?> - # Placeholder - (\?) ( [_dsafn&|\#]? ) #2 #3 - ) - }sx'; - $query = preg_replace_callback( - $re, - array(&$this, '_expandPlaceholdersCallback'), - $query - ); - return $query; - } - - static $join = array( - '|' => array('inner' => ' AND ', 'outer' => ') OR (',), - '&' => array('inner' => ' OR ', 'outer' => ') AND (',), - 'a' => array('inner' => ', ', 'outer' => '), (',), - ); - - /** - * string _expandPlaceholdersCallback(list $m) - * Internal function to replace placeholders (see preg_replace_callback). - */ - private function _expandPlaceholdersCallback($m) - { - // Placeholder. - if (!empty($m[3])) { - $type = $m[4]; - - // Idenifier prefix. - if ($type == '_') { - return $this->_identPrefix; - } - - // Value-based placeholder. - if (!$this->_placeholderArgs) return 'DBSIMPLE_ERROR_NO_VALUE'; - $value = array_pop($this->_placeholderArgs); - - // Skip this value? - if ($value === DBSIMPLE_SKIP) { - $this->_placeholderNoValueFound = true; - return ''; - } - - // First process guaranteed non-native placeholders. - switch ($type) { - case 's': - if (!($value instanceof DbSimple_SubQuery)) - return 'DBSIMPLE_ERROR_VALUE_NOT_SUBQUERY'; - return $value->get($this->_placeholderNativeArgs); - case '|': - case '&': - case 'a': - if (!$value) $this->_placeholderNoValueFound = true; - if (!is_array($value)) return 'DBSIMPLE_ERROR_VALUE_NOT_ARRAY'; - $parts = array(); - $multi = array(); //массив для двойной вложенности - $mult = $type!='a' || is_int(key($value)) && is_array(current($value)); - foreach ($value as $prefix => $field) { - //превращаем $value в двумерный нуменованный массив - if (!is_array($field)) { - $field = array($prefix => $field); - $prefix = 0; - } - $prefix = is_int($prefix) ? '' : - $this->escape($this->_addPrefix2Table($prefix), true) . '.'; - //для мультиинсерта очищаем ключи - их быть не может по синтаксису - if ($mult && $type=='a') - $field = array_values($field); - foreach ($field as $k => $v) - { - if ($v instanceof DbSimple_SubQuery) - $v = $v->get($this->_placeholderNativeArgs); - else - $v = $v === null? 'NULL' : $this->escape($v); - if (!is_int($k)) { - $k = $this->escape($k, true); - $parts[] = "$prefix$k=$v"; - } else { - $parts[] = $v; - } - } - if ($mult) - { - $multi[] = join(self::$join[$type]['inner'], $parts); - $parts = array(); - } - } - return $mult ? join(self::$join[$type]['outer'], $multi) : join(', ', $parts); - case '#': - // Identifier. - if (!is_array($value)) - { - if ($value instanceof DbSimple_SubQuery) - return $value->get($this->_placeholderNativeArgs); - $value = $this->_addPrefix2Table($value); - return $this->escape($value, true); - } - $parts = array(); - foreach ($value as $table => $identifiers) { - if (!is_array($identifiers)) $identifiers = array($identifiers); - $prefix = ''; - if (!is_int($table)) { - $table = $this->_addPrefix2Table($table); - $prefix = $this->escape($table, true) . '.'; - } - foreach ($identifiers as $identifier) - if ($identifier instanceof DbSimple_SubQuery) - $parts[] = $identifier->get($this->_placeholderNativeArgs); - elseif (!is_string($identifier)) - return 'DBSIMPLE_ERROR_ARRAY_VALUE_NOT_STRING'; - else - $parts[] = $prefix . ($identifier=='*' ? '*' : - $this->escape($this->_addPrefix2Table($identifier), true)); - } - return join(', ', $parts); - case 'n': - // NULL-based placeholder. - return empty($value)? 'NULL' : intval($value); - } - - // In non-native mode arguments are quoted. - if ($value === null) return 'NULL'; - - switch ($type) { - case 'd': - return intval($value); - case 'f': - return str_replace(',', '.', floatval($value)); - } - - // нативные плейсхолдеры необходимо обработать после числовых из-за бага в PDO - // Native arguments are not processed. - if ($this->_placeholderNativeArgs !== null) { - $this->_placeholderNativeArgs[] = $value; - return $this->_performGetNativePlaceholderMarker(count($this->_placeholderNativeArgs) - 1); - } - - if (!is_scalar($value)) - return 'DBSIMPLE_ERROR_VALUE_NOT_SCALAR'; - - // By default - escape as string. - return $this->escape($value); - } - - // Optional block. - if (isset($m[1]) && strlen($block=$m[1])) - { - $prev = $this->_placeholderNoValueFound; - if ($this->_placeholderNativeArgs !== null) - $prevPh = $this->_placeholderNativeArgs; - - // Проверка на {? } - условный блок - $skip = false; - if ($m[2]=='?') - { - $skip = array_pop($this->_placeholderArgs) === DBSIMPLE_SKIP; - $block[0] = ' '; - } - - $block = $this->_expandOptionalBlock($block); - - if ($skip) - $block = ''; - - if ($this->_placeholderNativeArgs !== null) - if ($this->_placeholderNoValueFound) - $this->_placeholderNativeArgs = $prevPh; - $this->_placeholderNoValueFound = $prev; // recurrent-safe - return $block; - } - - // Default: skipped part of the string. - return $m[0]; - } - - /** - * Заменяет ?_ на текущий префикс - * - * @param string $table имя таблицы - * @return string имя таблицы - */ - private function _addPrefix2Table($table) - { - if (substr($table, 0, 2) == '?_') - $table = $this->_identPrefix . substr($table, 2); - return $table; - } - - private function _expandOptionalBlock($block) - { - $alts = array(); - $alt = ''; - $sub=0; - $exp = explode('|',$block); - // Оптимизация, так как в большинстве случаев | не используется - if (count($exp)==1) - $alts=$exp; - else - foreach ($exp as $v) - { - // Реализуем автоматный магазин для нахождения нужной скобки - // На суммарную парность скобок проверять нет необходимости - об этом заботится регулярка - $sub+=substr_count($v,'{'); - $sub-=substr_count($v,'}'); - if ($sub>0) - $alt.=$v.'|'; - else - { - $alts[]=$alt.$v; - $alt=''; - } - } - $r=''; - foreach ($alts as $block) - { - $this->_placeholderNoValueFound = false; - $block = $this->_expandPlaceholdersFlow($block); - // Необходимо пройти все блоки, так как если пропустить оставшиесь, - // то это нарушит порядок подставляемых значений - if ($this->_placeholderNoValueFound == false && $r=='') - $r = ' '.$block.' '; - } - return $r; - } - - - /** - * void _setLastError($code, $msg, $query) - * Set last database error context. - * Aditionally expand placeholders. - */ - protected function _setLastError($code, $msg, $query) - { - if (is_array($query)) { - $this->_expandPlaceholders($query, false); - $query = $query[0]; - } - return parent::_setLastError($code, $msg, $query); - } - - - /** - * Convert SQL field-list to COUNT(...) clause - * (e.g. 'DISTINCT a AS aa, b AS bb' -> 'COUNT(DISTINCT a, b)'). - */ - private function _fieldList2Count($fields) - { - $m = null; - if (preg_match('/^\s* DISTINCT \s* (.*)/sx', $fields, $m)) { - $fields = $m[1]; - $fields = preg_replace('/\s+ AS \s+ .*? (?=,|$)/sx', '', $fields); - return "COUNT(DISTINCT $fields)"; - } else { - return 'COUNT(*)'; - } - } - - - /** - * array _transformResult(list $rows) - * Transform resulting rows to various formats. - */ - private function _transformResult($rows) - { - // Результат не массив - выходим - if (!is_array($rows) || !$rows) - return $rows; - - // Find ARRAY_KEY* AND PARENT_KEY fields in field list. - $pk = null; - $ak = array(); - foreach (array_keys(current($rows)) as $fieldName) - if (0 == strncasecmp($fieldName, DBSIMPLE_ARRAY_KEY, strlen(DBSIMPLE_ARRAY_KEY))) - $ak[] = $fieldName; - elseif (0 == strncasecmp($fieldName, DBSIMPLE_PARENT_KEY, strlen(DBSIMPLE_PARENT_KEY))) - $pk = $fieldName; - - if (!$ak) - return $rows; - - natsort($ak); // sort ARRAY_KEY* using natural comparision - // Tree-based array? Fields: ARRAY_KEY, PARENT_KEY - if ($pk !== null) - return $this->_transformResultToForest($rows, $ak[0], $pk); - // Key-based array? Fields: ARRAY_KEY. - return $this->_transformResultToHash($rows, $ak); - } - - - /** - * Converts rowset to key-based array. - * - * @param array $rows Two-dimensional array of resulting rows. - * @param array $ak List of ARRAY_KEY* field names. - * @return array Transformed array. - */ - private function _transformResultToHash(array $rows, array $arrayKeys) - { - $result = array(); - foreach ($rows as $row) { - // Iterate over all of ARRAY_KEY* fields and build array dimensions. - $current =& $result; - foreach ($arrayKeys as $ak) { - $key = $row[$ak]; - unset($row[$ak]); // remove ARRAY_KEY* field from result row - if ($key !== null) { - $current =& $current[$key]; - } else { - // IF ARRAY_KEY field === null, use array auto-indices. - $tmp = array(); - $current[] =& $tmp; - $current =& $tmp; - unset($tmp); // we use $tmp, because don't know the value of auto-index - } - } - $current = $row; // save the row in last dimension - } - return $result; - } - - - /** - * Converts rowset to the forest. - * - * @param array $rows Two-dimensional array of resulting rows. - * @param string $idName Name of ID field. - * @param string $pidName Name of PARENT_ID field. - * @return array Transformed array (tree). - */ - private function _transformResultToForest(array $rows, $idName, $pidName) - { - $children = array(); // children of each ID - $ids = array(); - // Collect who are children of whom. - foreach ($rows as $i=>$r) { - $row =& $rows[$i]; - $id = $row[$idName]; - if ($id === null) { - // Rows without an ID are totally invalid and makes the result tree to - // be empty (because PARENT_ID = null means "a root of the tree"). So - // skip them totally. - continue; - } - $pid = $row[$pidName]; - if ($id == $pid) $pid = null; - $children[$pid][$id] =& $row; - if (!isset($children[$id])) $children[$id] = array(); - $row['childNodes'] =& $children[$id]; - $ids[$id] = true; - } - // Root elements are elements with non-found PIDs. - $forest = array(); - foreach ($rows as $i=>$r) { - $row =& $rows[$i]; - $id = $row[$idName]; - $pid = $row[$pidName]; - if ($pid == $id) $pid = null; - if (!isset($ids[$pid])) { - $forest[$row[$idName]] =& $row; - } - unset($row[$idName]); - unset($row[$pidName]); - } - return $forest; - } - - - /** - * Replaces the last array in a multi-dimensional array $V by its first value. - * Used for selectCol(), when we need to transform (N+1)d resulting array - * to Nd array (column). - */ - private function _shrinkLastArrayDimensionCallback(&$v) - { - if (!$v) return; - reset($v); - if (!is_array($firstCell = current($v))) { - $v = $firstCell; - } else { - array_walk($v, array(&$this, '_shrinkLastArrayDimensionCallback')); - } - } - - - /** - * void _logQuery($query, $noTrace=false) - * Must be called on each query. - * If $noTrace is true, library caller is not solved (speed improvement). - */ - protected function _logQuery($query, $noTrace=false) - { - if (!$this->_logger) return; - $this->_expandPlaceholders($query, false); - $args = array(); - $args[] =& $this; - $args[] = $query[0]; - $args[] = $noTrace? null : $this->findLibraryCaller(); - return call_user_func_array($this->_logger, $args); - } - - - /** - * void _logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows) - * Log information about performed query statistics. - */ - private function _logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows) - { - // Always increment counters. - $this->_statistics['time'] += $queryTime; - $this->_statistics['count']++; - - // If no logger, economize CPU resources and actually log nothing. - if (!$this->_logger) - return; - - $dt = round($queryTime * 1000); - $firstFetchTime = round($firstFetchTime*1000); - $tailFetchTime = round($fetchTime * 1000) - $firstFetchTime; - $log = " -- "; - if ($firstFetchTime + $tailFetchTime) { - $log = sprintf(" -- %d ms = %d+%d".($tailFetchTime? "+%d" : ""), $dt, $dt-$firstFetchTime-$tailFetchTime, $firstFetchTime, $tailFetchTime); - } else { - $log = sprintf(" -- %d ms", $dt); - } - $log .= "; returned "; - - if (!is_array($rows)) { - $log .= $this->escape($rows); - } else { - $detailed = null; - if (count($rows) == 1) { - $len = 0; - $values = array(); - foreach ($rows[0] as $k=>$v) { - $len += strlen($v); - if ($len > $this->MAX_LOG_ROW_LEN) { - break; - } - $values[] = $v === null? 'NULL' : $this->escape($v); - } - if ($len <= $this->MAX_LOG_ROW_LEN) { - $detailed = "(" . preg_replace("/\r?\n/", "\\n", join(', ', $values)) . ")"; - } - } - if ($detailed) { - $log .= $detailed; - } else { - $log .= count($rows). " row(s)"; - } - } - - $this->_logQuery($log, true); - } - - // Identifiers prefix (used for ?_ placeholder). - private $_identPrefix = ''; - - // Queries statistics. - private $_statistics = array( - 'time' => 0, - 'count' => 0, - ); - - private $_cachePrefix = ''; - private $_className = ''; - - private $_logger = null; - private $_cacher = null; - private $_placeholderArgs, $_placeholderNativeArgs, $_placeholderCache=array(); - private $_placeholderNoValueFound; - - /** - * When string representation of row (in characters) is greater than this, - * row data will not be logged. - */ - private $MAX_LOG_ROW_LEN = 128; -} - +if (!defined('DBSIMPLE_SKIP')) + define('DBSIMPLE_SKIP', log(0)); /** - * Интерфейс BLOB. - * Описывает функции обекта типа BLOB - ему должны соответствовать классы, возвращаемые в качестве BLOB полей. + * Names of special columns in result-set which is used + * as array key (or karent key in forest-based resultsets) in + * resulting hash. */ -interface DbSimple_Generic_Blob -{ - /** - * string read(int $length) - * Returns following $length bytes from the blob. - */ - public function read($len); - - /** - * string write($data) - * Appends data to blob. - */ - public function write($data); - - /** - * int length() - * Returns length of the blob. - */ - public function length(); +if (!defined('DBSIMPLE_ARRAY_KEY')) + define('DBSIMPLE_ARRAY_KEY', 'ARRAY_KEY'); // hash-based resultset support +if (!defined('DBSIMPLE_PARENT_KEY')) + define('DBSIMPLE_PARENT_KEY', 'PARENT_KEY'); // forrest-based resultset support - /** - * blobid close() - * Closes the blob. Return its ID. No other way to obtain this ID! - */ - public function close(); - -} /** - * Класс для хранения подзапроса - результата выполнения функции - * DbSimple_Generic_Database::subquery - * + * DbSimple factory. */ -class DbSimple_SubQuery +class DbSimple_Generic { - private $query=array(); - - - public function __construct(array $q) - { - $this->query = $q; - } - /** - * Возвращает сам запрос и добавляет плейсхолдеры в массив переданный по ссылке + * DbSimple_Generic connect(mixed $dsn) * - * @param &array|null - ссылка на массив плейсхолдеров - * @return string - */ - public function get(&$ph) - { - if ($ph !== null) - $ph = array_merge($ph, array_slice($this->query,1,null,true)); - return $this->query[0]; - } - -} - -/** - * Support for error tracking. - * Can hold error messages, error queries and build proper stacktraces. - */ -abstract class DbSimple_Generic_LastError -{ - public $error = null; - public $errmsg = null; - private $showStack = false; - private $errorHandler = null; - private $ignoresInTraceRe = 'DbSimple_.*::.* | call_user_func.*'; - - /** - * abstract void _logQuery($query) - * Must be overriden in derived class. - */ - protected abstract function _logQuery($query); - - /** - * void _resetLastError() - * Reset the last error. Must be called on correct queries. - */ - protected function _resetLastError() - { - $this->error = $this->errmsg = null; - } - - /** - * void _setLastError(int $code, string $message, string $query) - * Fill $this->error property with error information. Error context - * (code initiated the query outside DbSimple) is assigned automatically. - */ - protected function _setLastError($code, $msg, $query) - { - $context = "unknown"; - $this->error = array( - 'code' => $code, - 'message' => rtrim($msg), - 'query' => $query, - 'context' => '', - ); - if ($t = $this->findLibraryCaller($this->showStack)) - { - if (!$this->showStack) - $this->error['context'] = (isset($t['file'])? $t['file'] : '?') . - ' line ' . (isset($t['line'])? $t['line'] : '?'); - else - { - $this->error['context'] = (isset($t[0]['file'])? $t[0]['file'] : '?') . - ' line ' . (isset($t[0]['line'])? $t[0]['line'] : '?'); - $this->error['stack'] = array(); - foreach($t as $f) - $this->error['stack'][] = (isset($f['class']) ? $f['class'].$f['type'] : ''). - (isset($f['function']) ? $f['function'] : '?').'() '. - (isset($f['file'])? $f['file'] : '?') . ':' . (isset($f['line'])? $f['line'] : '?'); + * Universal static function to connect ANY database using DSN syntax. + * Choose database driver according to DSN. Return new instance + * of this driver. + */ + function& connect($dsn) + { + // Load database driver and create its instance. + $parsed = DbSimple_Generic::parseDSN($dsn); + if (!$parsed) { + $dummy = null; + return $dummy; + } + $class = 'DbSimple_'.ucfirst($parsed['scheme']); + if (!class_exists($class)) { + $file = str_replace('_', '/', $class) . ".php"; + // Try to load library file from standard include_path. + if ($f = @fopen($file, "r", true)) { + fclose($f); + require_once($file); + } else { + // Wrong include_path; try to load from current directory. + $base = basename($file); + $dir = dirname(__FILE__); + if (@is_file($path = "$dir/$base")) { + require_once($path); + } else { + trigger_error("Error loading database driver: no file $file in include_path; no file $base in $dir", E_USER_ERROR); + return null; + } } } - $this->errmsg = rtrim($msg) . ($this->error['context']? ' at '.$this->error['context'] : ''); - - $this->_logQuery(" -- error #".$code.": ".preg_replace('/(\r?\n)+/s', ' ', $this->errmsg)); - - if (is_callable($this->errorHandler)) { - call_user_func($this->errorHandler, $this->errmsg, $this->error); + $object =& new $class($parsed); + if (isset($parsed['ident_prefix'])) { + $object->setIdentPrefix($parsed['ident_prefix']); } - - return false; + $object->setCachePrefix(md5(serialize($parsed['dsn']))); + return $object; } /** - * callback setErrorHandler(callback $handler, bool $stack) - * Set new error handler called on database errors. - * Handler gets 3 arguments: - * - error message - * - full error context information (last query etc.) + * array parseDSN(mixed $dsn) + * Parse a data source name. + * See parse_url() for details. */ - public function setErrorHandler($handler, $stack=false) + function parseDSN($dsn) { - $prev = $this->errorHandler; - $this->errorHandler = $handler; - $this->showStack = $stack; - // In case of setting first error handler for already existed - // error - call the handler now (usual after connect()). - if (!$prev && $this->error) - call_user_func($this->errorHandler, $this->errmsg, $this->error); - return $prev; - } - - /** - * void addIgnoreInTrace($reName) - * Add regular expression matching ClassName::functionName or functionName. - * Matched stack frames will be ignored in stack traces passed to query logger. - */ - public function addIgnoreInTrace($name) - { - $this->ignoresInTraceRe .= "|" . $name; - } - - /** - * array of array findLibraryCaller() - * Return part of stacktrace before calling first library method. - * Used in debug purposes (query logging etc.). - */ - protected function findLibraryCaller($all = false) - { - $caller = call_user_func( - array(&$this, 'debug_backtrace_smart'), - $this->ignoresInTraceRe, - !$all - ); - return $caller; - } - - /** - * array debug_backtrace_smart($ignoresRe=null, $returnCaller=false) - * - * Return stacktrace. Correctly work with call_user_func* - * (totally skip them correcting caller references). - * If $returnCaller is true, return only first matched caller, - * not all stacktrace. - * - * @version 2.03 - */ - private function debug_backtrace_smart($ignoresRe=null, $returnCaller=false) - { - $trace = debug_backtrace(); - - if ($ignoresRe !== null) - $ignoresRe = "/^(?>{$ignoresRe})$/six"; - $smart = array(); - $framesSeen = 0; - for ($i=0, $n=count($trace); $i<$n; $i++) { - $t = $trace[$i]; - if (!$t) continue; - - // Next frame. - $next = isset($trace[$i+1])? $trace[$i+1] : null; - - // Dummy frame before call_user_func* frames. - if (!isset($t['file'])) { - $t['over_function'] = $trace[$i+1]['function']; - $t = $t + $trace[$i+1]; - $trace[$i+1] = null; // skip call_user_func on next iteration - $next = isset($trace[$i+2])? $trace[$i+2] : null; // Correct Next frame. - } - - // Skip myself frame. - if (++$framesSeen < 2) continue; - - // 'class' and 'function' field of next frame define where - // this frame function situated. Skip frames for functions - // situated in ignored places. - if ($ignoresRe && $next) { - // Name of function "inside which" frame was generated. - $frameCaller = (isset($next['class'])? $next['class'].'::' : '') . (isset($next['function'])? $next['function'] : ''); - if (preg_match($ignoresRe, $frameCaller)) continue; - } - - // On each iteration we consider ability to add PREVIOUS frame - // to $smart stack. - if ($returnCaller) return $t; - $smart[] = $t; + if (is_array($dsn)) return $dsn; + $parsed = @parse_url($dsn); + if (!$parsed) return null; + $params = null; + if (!empty($parsed['query'])) { + parse_str($parsed['query'], $params); + $parsed += $params; } - return $smart; + $parsed['dsn'] = $dsn; + return $parsed; } - } -?> \ No newline at end of file + +?> diff --git a/lib/DbSimple/Ibase.php b/lib/DbSimple/Ibase.php index 2dc45fd..8fe15a0 100644 --- a/lib/DbSimple/Ibase.php +++ b/lib/DbSimple/Ibase.php @@ -14,9 +14,9 @@ * @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/ * @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/ * - * @version 2.x $Id: Ibase.php 221 2007-07-27 23:24:35Z dk $ + * @version 2.x $Id$ */ -require_once dirname(__FILE__).'/Generic.php'; +require_once... [truncated message content] |
From: Ivan1986 <iva...@us...> - 2010-08-23 13:28:46
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 60693af34d92bea06925807c109a096a5b16895d (commit) via abfd1426ad56b6393afe0371eaecbcba9afb7a5a (commit) from 10085ec50ec624a84b40207c63bee123da08eee5 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 60693af34d92bea06925807c109a096a5b16895d Author: Ivan1986 <iva...@li...> Date: Fri Aug 20 15:47:42 2010 +0400 Правка плейсхолдера ?# diff --git a/lib/DbSimple/Generic.php b/lib/DbSimple/Generic.php index 5345d55..532746c 100644 --- a/lib/DbSimple/Generic.php +++ b/lib/DbSimple/Generic.php @@ -664,7 +664,7 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError '&' => array('inner' => ' OR ', 'outer' => ') AND (',), 'a' => array('inner' => ', ', 'outer' => '), (',), ); - + /** * string _expandPlaceholdersCallback(list $m) * Internal function to replace placeholders (see preg_replace_callback). @@ -710,9 +710,8 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError $field = array($prefix => $field); $prefix = 0; } - $prefix = is_int($prefix) ? '' : $this->escape($prefix, true) . '.'; - if (substr($prefix, 0, 2) == '?_') - $prefix = $this->_identPrefix . substr($prefix, 2); + $prefix = is_int($prefix) ? '' : + $this->escape($this->_addPrefix2Table($prefix), true) . '.'; //для мультиинсерта очищаем ключи - их быть не может по синтаксису if ($mult && $type=='a') $field = array_values($field); @@ -736,14 +735,13 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError } } return $mult ? join(self::$join[$type]['outer'], $multi) : join(', ', $parts); - case "#": + case '#': // Identifier. if (!is_array($value)) { if ($value instanceof DbSimple_SubQuery) return $value->get($this->_placeholderNativeArgs); - if (substr($value, 0, 2) == '?_') - $value = $this->_identPrefix . substr($value, 2); + $value = $this->_addPrefix2Table($value); return $this->escape($value, true); } $parts = array(); @@ -751,18 +749,17 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError if (!is_array($identifiers)) $identifiers = array($identifiers); $prefix = ''; if (!is_int($table)) { - if (substr($table, 0, 2) == '?_') $table = $this->_identPrefix . substr($table, 2); - $prefix = $this->escape($table, true) . '.'; + $table = $this->_addPrefix2Table($table); + $prefix = $this->escape($table, true) . '.'; } foreach ($identifiers as $identifier) if ($identifier instanceof DbSimple_SubQuery) $parts[] = $identifier->get($this->_placeholderNativeArgs); + elseif (!is_string($identifier)) + return 'DBSIMPLE_ERROR_ARRAY_VALUE_NOT_STRING'; else - { - if (!is_string($identifier)) - return 'DBSIMPLE_ERROR_ARRAY_VALUE_NOT_STRING'; - $parts[] = $prefix . ($identifier!='*'?$this->escape($identifier, true):'*'); - } + $parts[] = $prefix . ($identifier=='*' ? '*' : + $this->escape($this->_addPrefix2Table($identifier), true)); } return join(', ', $parts); case 'n': @@ -825,6 +822,19 @@ abstract class DbSimple_Generic_Database extends DbSimple_Generic_LastError return $m[0]; } + /** + * Заменяет ?_ на текущий префикс + * + * @param string $table имя таблицы + * @return string имя таблицы + */ + private function _addPrefix2Table($table) + { + if (substr($table, 0, 2) == '?_') + $table = $this->_identPrefix . substr($table, 2); + return $table; + } + private function _expandOptionalBlock($block) { $alts = array(); diff --git a/tests/DbSimple/DbSimpleTest.php b/tests/DbSimple/DbSimpleTest.php index 9b37f8b..1ade998 100644 --- a/tests/DbSimple/DbSimpleTest.php +++ b/tests/DbSimple/DbSimpleTest.php @@ -96,7 +96,7 @@ class DbSimpleTest extends PHPUnit_Framework_TestCase $this->db->query('SELECT ?# FROM ?_t1', array('t1'=>array('aaa','bbb'))); $this->db->query('SELECT ?# FROM ?_t1', array('?_t1'=>'*','?_t2'=>'ccc')); $this->db->query('SELECT ?# FROM ?#', array('t1'=>'*','t2'=>'ccc'),array('base'=>'t1')); - $this->db->query('SELECT ?# FROM ?#', array('?_t1'=>'*','?_t2'=>'ccc'),array('base'=>'t1')); + $this->db->query('SELECT ?# FROM ?#', array('?_t1'=>'*','?_t2'=>'ccc'),array('base'=>'?_t1')); $R = array ( 'SELECT `aaa` FROM pre_t1', 'SELECT `aaa` FROM pre_t1', @@ -105,7 +105,7 @@ class DbSimpleTest extends PHPUnit_Framework_TestCase 'SELECT `t1`.`aaa`, `t1`.`bbb` FROM pre_t1', 'SELECT `pre_t1`.*, `pre_t2`.`ccc` FROM pre_t1', 'SELECT `t1`.*, `t2`.`ccc` FROM `base`.`t1`', - 'SELECT `pre_t1`.*, `pre_t2`.`ccc` FROM `base`.`t1`', + 'SELECT `pre_t1`.*, `pre_t2`.`ccc` FROM `base`.`pre_t1`', ); $this->assertEquals($this->Qlog, $R, 'Ошибка обработки ?#'); @@ -123,7 +123,7 @@ class DbSimpleTest extends PHPUnit_Framework_TestCase $this->db->query('UPDATE ?_t1 SET ?a WHERE a IN (?a)', array('a'=>'1'), array('1','2','3')); $this->db->query('UPDATE ?_t1 SET ?a WHERE a IN (?a)', array('a'=>'1', 'b'=>2), array('1','2','3')); $this->db->query('UPDATE ?_t1 SET ?a WHERE a IN (?a)', array( - 't' => array('a' => 1, 'b' => 2), + '?_t' => array('a' => 1, 'b' => 2), 't2' => array('a' => 3) ), array('1','2','3')); $this->db->query('INSERT INTO t1(a,b,c) VALUES (?a)',array( @@ -147,7 +147,7 @@ class DbSimpleTest extends PHPUnit_Framework_TestCase 'SELECT * FROM pre_t1 WHERE a IN (\'1\', \'2\', \'3\')', 'UPDATE pre_t1 SET `a`=\'1\' WHERE a IN (\'1\', \'2\', \'3\')', 'UPDATE pre_t1 SET `a`=\'1\', `b`=\'2\' WHERE a IN (\'1\', \'2\', \'3\')', - 'UPDATE pre_t1 SET `t`.`a`=\'1\', `t`.`b`=\'2\', `t2`.`a`=\'3\' WHERE a IN (\'1\', \'2\', \'3\')', + 'UPDATE pre_t1 SET `pre_t`.`a`=\'1\', `pre_t`.`b`=\'2\', `t2`.`a`=\'3\' WHERE a IN (\'1\', \'2\', \'3\')', 'INSERT INTO t1(a,b,c) VALUES (\'1\', \'2\', \'3\'), (\'4\', \'5\', \'6\'), (\'7\', \'8\', \'9\')', 'SELECT * FROM t1 WHERE (`a`=\'1\' OR `b`=\'2\') AND (`c`=\'3\' OR `d`=\'4\')', 'SELECT * FROM t1 WHERE (`a`=\'1\') OR (`a`=\'1\' AND `b`=\'2\') OR (`c`=\'3\' AND `d`=\'4\')', commit abfd1426ad56b6393afe0371eaecbcba9afb7a5a Author: Ivan1986 <iva...@li...> Date: Fri Aug 20 11:34:31 2010 +0400 Фикс обработчика ошибок diff --git a/lib/DbSimple/Connect.php b/lib/DbSimple/Connect.php index d6720ff..0552859 100644 --- a/lib/DbSimple/Connect.php +++ b/lib/DbSimple/Connect.php @@ -116,7 +116,7 @@ class DbSimple_Connect if (isset($parsed['prefix'])) $this->DbSimple->setIdentPrefix($parsed['prefix']); $this->DbSimple->setCachePrefix('db_'.md5($parsed['dsn']).'_'); - $this->DbSimple->setErrorHandler($this->errorHandler ? $this->errorHandler : array(&$this, 'errorHandler'), false); + $this->DbSimple->setErrorHandler($this->errorHandler!==null ? $this->errorHandler : array(&$this, 'errorHandler')); } /** @@ -147,7 +147,9 @@ class DbSimple_Connect * - сообщение об ошибке * - массив (код, сообщение, запрос, контекст) * - * @param callback setErrorHandler(callback $handler) + * @param callback|null|false $handler обработчик ошибок + * <br> null - по умолчанию + * <br> false - отключен */ public function setErrorHandler($handler) { ----------------------------------------------------------------------- Summary of changes: lib/DbSimple/Connect.php | 6 ++++-- lib/DbSimple/Generic.php | 38 ++++++++++++++++++++++++-------------- tests/DbSimple/DbSimpleTest.php | 8 ++++---- 3 files changed, 32 insertions(+), 20 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-21 13:07:45
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 10085ec50ec624a84b40207c63bee123da08eee5 (commit) from 07e385c27f06e54d6091567d8dc8743861727777 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 10085ec50ec624a84b40207c63bee123da08eee5 Author: Ivan Borzenkov <iva...@li...> Date: Sat Aug 21 17:07:12 2010 +0400 Функция nocache diff --git a/lib/utils.php b/lib/utils.php index 3ee2f25..c6cc6c4 100644 --- a/lib/utils.php +++ b/lib/utils.php @@ -314,6 +314,17 @@ function preg($pattern, $subject, $all = true) } /** + * Устанавливает заголовки запрещающие кешировать + */ +function nocache() +{ + header ("Expires: Mon, 26 Jul 1990 05:00:00 GMT"); + header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header ("Cache-Control: no-cache, must-revalidate"); + header ("Pragma: no-cache"); +} + +/** * Функции ескейпинга в нужной кодировке * * @param string $s Исходная строка ----------------------------------------------------------------------- Summary of changes: lib/utils.php | 11 +++++++++++ 1 files changed, 11 insertions(+), 0 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-19 13:19:33
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 07e385c27f06e54d6091567d8dc8743861727777 (commit) from b3cff61f428e85c615718d8c7188428e4aa63a7d (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 07e385c27f06e54d6091567d8dc8743861727777 Author: Ivan1986 <iva...@li...> Date: Thu Aug 19 17:18:54 2010 +0400 errorHandler в DbSimple diff --git a/lib/DbSimple/Connect.php b/lib/DbSimple/Connect.php index 738f195..d6720ff 100644 --- a/lib/DbSimple/Connect.php +++ b/lib/DbSimple/Connect.php @@ -116,7 +116,7 @@ class DbSimple_Connect if (isset($parsed['prefix'])) $this->DbSimple->setIdentPrefix($parsed['prefix']); $this->DbSimple->setCachePrefix('db_'.md5($parsed['dsn']).'_'); - $this->DbSimple->setErrorHandler(array(&$this, 'errorHandler'), false); + $this->DbSimple->setErrorHandler($this->errorHandler ? $this->errorHandler : array(&$this, 'errorHandler'), false); } /** @@ -142,6 +142,25 @@ class DbSimple_Connect } /** + * Устанавливает новый обработчик ошибок + * Обработчик получает 2 аргумента: + * - сообщение об ошибке + * - массив (код, сообщение, запрос, контекст) + * + * @param callback setErrorHandler(callback $handler) + */ + public function setErrorHandler($handler) + { + $prev = $this->errorHandler; + $this->errorHandler = $handler; + if ($this->DbSimple) + return $this->DbSimple->setErrorHandler($handler); + } + + /** @var callback обработчик ошибок */ + private $errorHandler = null; + + /** * array parseDSN(string $dsn) * Разбирает строку DSN в массив параметров подключения к базе */ ----------------------------------------------------------------------- Summary of changes: lib/DbSimple/Connect.php | 21 ++++++++++++++++++++- 1 files changed, 20 insertions(+), 1 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-12 07:37:51
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via b3cff61f428e85c615718d8c7188428e4aa63a7d (commit) from 04f1cd3bfec49c7b3c4d8aa2503ed70aeb0e0de2 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit b3cff61f428e85c615718d8c7188428e4aa63a7d Author: Ivan1986 <iva...@li...> Date: Thu Aug 12 11:36:48 2010 +0400 Добавлена функция logout в QuickFW_Auth diff --git a/QFW/QuickFW/Auth.php b/QFW/QuickFW/Auth.php index 0790576..1d65a17 100644 --- a/QFW/QuickFW/Auth.php +++ b/QFW/QuickFW/Auth.php @@ -55,7 +55,20 @@ class QuickFW_Auth return false; QFW::$router->redirect($redir); } - + + /** + * Удаляет данные пользователя из сесии + * + * <br>Если пользователь залогинен, то его сессия удаляется + * <br>Если не залогинен, то ничего не делается + * + */ + public function logout() + { + if (isset($_SESSION[$this->name])) + unset($_SESSION[$this->name]); + } + /** * Старт сессии * @@ -71,7 +84,7 @@ class QuickFW_Auth require (QFWPATH.'/QuickFW/Session.php'); self::$session = new QuickFW_Session($sid); } - + /** * Рестарт сессии * @@ -88,7 +101,7 @@ class QuickFW_Auth self::$session = new QuickFW_Session($sid); return null; } - + /** * Уничтожение сессии * @@ -100,7 +113,7 @@ class QuickFW_Auth return; self::$session->destroy(session_id()); } - + /** * Проверка авторизации и сохранение данных в сессии * @@ -126,7 +139,7 @@ class QuickFW_Auth $this->userdata = & $_SESSION[$this->name]; QFW::$userdata = & $_SESSION[$this->name]; } - + /** * Простейшая проверка авторизации - имя и пароль в конфиге * @@ -153,6 +166,6 @@ class QuickFW_Auth else return false; } - + } ?> \ No newline at end of file ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Auth.php | 25 +++++++++++++++++++------ 1 files changed, 19 insertions(+), 6 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-10 08:37:59
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 04f1cd3bfec49c7b3c4d8aa2503ed70aeb0e0de2 (commit) from 8a3d41547344f9dd14c1b56587e3fa3b1aedb1d1 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 04f1cd3bfec49c7b3c4d8aa2503ed70aeb0e0de2 Author: TeXHaPb <te...@te...> Date: Tue Aug 10 12:30:50 2010 +0400 Исправлена ошибка в библиотеке Language.php и орфографические ошибки diff --git a/QFW/QuickFW/Autoload.php b/QFW/QuickFW/Autoload.php index 1f43302..ad3c73f 100644 --- a/QFW/QuickFW/Autoload.php +++ b/QFW/QuickFW/Autoload.php @@ -56,7 +56,7 @@ class Autoload { if (empty(self::$classes)) self::$classes = array( - 'ScafoldController' => LIBPATH.'/Modules/Scafold/ScafoldController.php', + 'ScaffoldController' => LIBPATH.'/Modules/Scaffold/ScaffoldController.php', 'QuickFW_Auth' => QFWPATH.'/QuickFW/Auth.php', ); if (empty(self::$classes[$class])) diff --git a/application/default/controllers/TableController.php b/application/default/controllers/TableController.php index 26350c2..0c2d11d 100644 --- a/application/default/controllers/TableController.php +++ b/application/default/controllers/TableController.php @@ -1,13 +1,13 @@ <?php require 'Controller.php'; -require LIBPATH.'/Modules/Scafold/ScafoldController.php'; +require LIBPATH.'/Modules/Scaffold/ScaffoldController.php'; /** * Description of TableController * * @author ivan */ -class TableController extends ScafoldController +class TableController extends ScaffoldController { public function __construct() { diff --git a/doc/nginx.conf b/doc/nginx.conf index f1e202a..dbfd64a 100644 --- a/doc/nginx.conf +++ b/doc/nginx.conf @@ -1,4 +1,4 @@ -server { +server { <...> @@ -12,20 +12,20 @@ server { #For apache backend location @fallback { - proxy_pass http://127.0.0.1:8080;#Apache must have its own rewrite + proxy_pass http://127.0.0.1:8080;#Apache must have it's own rewrite proxy_set_header Host $host; } - location ~ \.php$ { #To deny get php files like text + location ~ \.php$ { # To deny get php files as text try_files $uri @fastcgi; #For apache backend - proxy_pass http://127.0.0.1:8080;#Apache must have its own rewrite + proxy_pass http://127.0.0.1:8080;#Apache must have it's own rewrite proxy_set_header Host $host; #For FastCGI - #fastcgi_pass unix:/var/run/php-fpm/defailt.socket; + #fastcgi_pass unix:/var/run/php-fpm/default.socket; #include fastcgi_params; #standart file in nginx #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; @@ -33,7 +33,7 @@ server { #For FastCGI location @fastcgi { - fastcgi_pass unix:/var/run/php-fpm/defailt.socket; + fastcgi_pass unix:/var/run/php-fpm/default.socket; fastcgi_index index.php; include fastcgi_params; #standart file in nginx diff --git a/lib/Language.php b/lib/Language.php index e2aaf43..1180379 100644 --- a/lib/Language.php +++ b/lib/Language.php @@ -51,7 +51,6 @@ class Language { */ function load($langfile = '', $idiom = '', $return = FALSE) { - global $config; $langfile = $langfile.'_lang.php'; if (in_array($langfile, $this->is_loaded, TRUE)) @@ -61,7 +60,7 @@ class Language { if ($idiom == '') { - $deft_lang = $config['host']['lang']; + $deft_lang = QFW::$config['host']['lang']; $idiom = is_null($deft_lang) ? 'en_EN' : $deft_lang; } diff --git a/lib/Modules/Scafold/Fields.php b/lib/Modules/Scaffold/Fields.php similarity index 92% rename from lib/Modules/Scafold/Fields.php rename to lib/Modules/Scaffold/Fields.php index fd7a874..c2ac617 100644 --- a/lib/Modules/Scafold/Fields.php +++ b/lib/Modules/Scaffold/Fields.php @@ -7,7 +7,7 @@ require_once LIBPATH.'/utils.php'; * Содержит набор полей для заполнения пользователем * */ -class Scafold_Field_Info +class Scaffold_Field_Info { /** @var boolean скрытое поле */ public $hide = null; @@ -44,17 +44,17 @@ class Scafold_Field_Info * Не содержит никаких проверок, оформлений, преобразований * */ -class Scafold_Field extends Scafold_Field_Info +class Scaffold_Field extends Scaffold_Field_Info { /** * Создает полноценное поле из данных о пользователе * - * @param Scafold_Field_Info $info Информация о поле + * @param Scaffold_Field_Info $info Информация о поле */ public function __construct($info) { - $vars = get_class_vars('Scafold_Field_Info'); + $vars = get_class_vars('Scaffold_Field_Info'); foreach ($vars as $k=>$v) $this->$k = $info->$k; $this->name = $info->fiendInfo['Field']; @@ -185,17 +185,17 @@ class Scafold_Field extends Scafold_Field_Info /** * Класс для главного поля */ -class Scafold_Parent extends Scafold_Field +class Scaffold_Parent extends Scaffold_Field { public function proccess($id, $value) { - return $_SESSION['scafold'][$this->table]['parent']; + return $_SESSION['scaffold'][$this->table]['parent']; } public function validator($id, $value) { //если у нас будет потеря сессии, то случится фигня - return isset($_SESSION['scafold'][$this->table]['parent']); + return isset($_SESSION['scaffold'][$this->table]['parent']); } public function filterForm($session) @@ -208,7 +208,7 @@ class Scafold_Parent extends Scafold_Field * Класс для зависимых полей * формирует select со значениями из другой таблицы */ -class Scafold_Foreign extends Scafold_Field +class Scaffold_Foreign extends Scaffold_Field { /** @var array Зависимые поля */ protected $lookup; @@ -242,7 +242,7 @@ class Scafold_Foreign extends Scafold_Field * Сервисный классс для полей, вводимых пользователем * <br>пока только обрезка при выводе, так как обязательно нагадят :) */ -abstract class Scafold_UserInput extends Scafold_Field +abstract class Scaffold_UserInput extends Scaffold_Field { /** @var integer До скольки обрезать */ private $trim; @@ -260,13 +260,13 @@ abstract class Scafold_UserInput extends Scafold_Field } //Классы для различных типов полей из базы данных -//Соответствие в функции ScafoldController::getFieldClass +//Соответствие в функции ScaffoldController::getFieldClass /** * Пока тестовый класс для типа TEXT */ -class Scafold_Text extends Scafold_UserInput +class Scaffold_Text extends Scaffold_UserInput { /** @var integer Сколько строк */ private $rows; @@ -291,7 +291,7 @@ class Scafold_Text extends Scafold_UserInput /** * Класс для типа Int */ -class Scafold_Int extends Scafold_Field +class Scaffold_Int extends Scaffold_Field { public function validator($id, $value) { @@ -302,7 +302,7 @@ class Scafold_Int extends Scafold_Field /** * Класс для типа Varchar */ -class Scafold_Varchar extends Scafold_Field +class Scaffold_Varchar extends Scaffold_Field { /** @var integer размер поля в базе */ private $size; @@ -324,12 +324,12 @@ class Scafold_Varchar extends Scafold_Field /** * Класс для типа Char - полностью аналогичен Varchar */ -class Scafold_Char extends Scafold_Varchar {} +class Scaffold_Char extends Scaffold_Varchar {} /** * Класс для типа ENUM */ -class Scafold_Enum extends Scafold_Field +class Scaffold_Enum extends Scaffold_Field { /** @var array что в перечислении */ private $items; @@ -350,7 +350,7 @@ class Scafold_Enum extends Scafold_Field //Классы для других типов полей, указываемых пользователем -class Scafold_Checkbox extends Scafold_Field +class Scaffold_Checkbox extends Scaffold_Field { public function display($id, $value) @@ -371,7 +371,7 @@ class Scafold_Checkbox extends Scafold_Field * Класс для поля, в котором хранится имя файла, * загружаемого на сервер */ -class Scafold_File extends Scafold_Field +class Scaffold_File extends Scaffold_Field { /** @var string Путь к директории, где хранятся файлы */ private $path; @@ -383,7 +383,7 @@ class Scafold_File extends Scafold_Field /** * Проверяет параметры для файлового поля * - * @param Scafold_Field_Info $info Информация о поле + * @param Scaffold_Field_Info $info Информация о поле */ public function __construct($info) { diff --git a/lib/Modules/Scafold/ScafoldController.php b/lib/Modules/Scaffold/ScaffoldController.php similarity index 94% rename from lib/Modules/Scafold/ScafoldController.php rename to lib/Modules/Scaffold/ScaffoldController.php index 6c31f06..8a7f65b 100644 --- a/lib/Modules/Scafold/ScafoldController.php +++ b/lib/Modules/Scaffold/ScaffoldController.php @@ -1,6 +1,6 @@ <?php -require_once LIBPATH.'/Modules/Scafold/Fields.php'; +require_once LIBPATH.'/Modules/Scaffold/Fields.php'; /** * Класс для быстрого создания CRUD интерфейса к таблице @@ -13,13 +13,13 @@ require_once LIBPATH.'/Modules/Scafold/Fields.php'; * подобных им таблиц * <br><br>Пример подключения: * <br><br>require 'Controller.php'; - * <br>require LIBPATH.'/Modules/Scafold/ScafoldController.php'; + * <br>require LIBPATH.'/Modules/Scaffold/ScaffoldController.php'; * <br>..... - * <br>class TableController extends ScafoldController + * <br>class TableController extends ScaffoldController * * @author Ivan1986 */ -abstract class ScafoldController extends Controller +abstract class ScaffoldController extends Controller { /** @var string Имя таблицы */ protected $table = ''; @@ -101,12 +101,12 @@ abstract class ScafoldController extends Controller */ public function __construct() { - QFW::$view->P->addCSS('buildin/scafold.css'); + QFW::$view->P->addCSS('built-in/scaffold.css'); $this->session(); //Создаем сессию для таблицы и ссылаемся на нее - if (!isset($_SESSION['scafold'][$this->table])) - $_SESSION['scafold'][$this->table] = array(); - $this->sess = &$_SESSION['scafold'][$this->table]; + if (!isset($_SESSION['scaffold'][$this->table])) + $_SESSION['scaffold'][$this->table] = array(); + $this->sess = &$_SESSION['scaffold'][$this->table]; $this->setup = true; parent::__construct(); @@ -115,7 +115,7 @@ abstract class ScafoldController extends Controller //Получаем данные о полях $this->fields = $this->fields(); foreach($this->fields as $k=>$field) - if (get_class($field) == 'Scafold_Field_Info') + if (get_class($field) == 'Scaffold_Field_Info') unset($this->fields[$k]); //порядок сортировки полей @@ -180,7 +180,7 @@ abstract class ScafoldController extends Controller QFW::$view->assign('parent', QFW::$view->assign('parent', array( 'list' => $parent, 'current' => $this->sess['parent'], - ))->fetch('scafold/parent.html')); + ))->fetch('scaffold/parent.html')); $parentWhere = QFW::$db->subquery('AND ?#=?', array($this->table => $this->parentData['colum']), $this->sess['parent']); @@ -212,7 +212,7 @@ abstract class ScafoldController extends Controller return QFW::$view->assign(array( 'data' => $data, 'pager' => $pager, - ))->fetch('scafold/index.html'); + ))->fetch('scaffold/index.html'); } /** @@ -299,7 +299,7 @@ abstract class ScafoldController extends Controller 'id' => $id, 'data' => $data, 'errors' => $errors, - ))->fetch('scafold/edit.html'); + ))->fetch('scaffold/edit.html'); } /** @@ -373,7 +373,7 @@ abstract class ScafoldController extends Controller * <br><br> Вызывается только в конструкторе * * @param array $fieldList массив с именами полей - * @return ScafoldController + * @return ScaffoldController */ protected function order($fieldList) { @@ -392,7 +392,7 @@ abstract class ScafoldController extends Controller * @param string|DbSimple_SubQuery $id Ключ в главной таблице * @param string|DbSimple_SubQuery $name Заголовок в главной таблице * @param DbSimple_SubQuery $other Дополнительные условия - * @return ScafoldController + * @return ScaffoldController */ protected function parent($colum, $table, $id, $name, $other=DBSIMPLE_SKIP) { @@ -418,7 +418,7 @@ abstract class ScafoldController extends Controller * @param string $id Ссылочный ключ * @param string $name Значение связанного поля * @param bool $notNull Не допускать пустого значения - * @return ScafoldController + * @return ScaffoldController */ protected function foreign($colum, $table, $id, $name, $notNull=false) { @@ -444,7 +444,7 @@ abstract class ScafoldController extends Controller * @param string|array $colum Колонка или массив колонок, которые нужно скрыть * @param boolean $hide true - скрыть<br>false - показать<br> * по умолчанию показываются все кромя первичного ключа при редактировании - * @return ScafoldController + * @return ScaffoldController */ protected function hide($colum, $hide=true) { @@ -462,7 +462,7 @@ abstract class ScafoldController extends Controller * false - выключен<br> * true - включен по умолчанию<br> * mixed - произвольный параметр - * @return ScafoldController + * @return ScaffoldController */ protected function filter($colum, $filter='') { @@ -477,7 +477,7 @@ abstract class ScafoldController extends Controller * @param string|array $colum Колонка<br> * Или массив ключи - колонки, значения описания * @param string $desc описание - * @return ScafoldController + * @return ScaffoldController */ protected function desc($colum, $desc='') { @@ -492,7 +492,7 @@ abstract class ScafoldController extends Controller * @param string|array $colum Колонка<br> * Или массив ключи - колонки, значения заголовки * @param string $title Заголовок - * @return ScafoldController + * @return ScaffoldController */ protected function title($colum, $title='') { @@ -507,7 +507,7 @@ abstract class ScafoldController extends Controller * @param string $colum Колонка * @param string $className Имя класса без префикса * @param mixed $param Второй параметр конструктора класса - * @return ScafoldController + * @return ScaffoldController */ protected function type($colum, $className='', $param=false) { @@ -530,7 +530,7 @@ abstract class ScafoldController extends Controller * @param string|array $colum Колонка<br> * Или массив ключи - колонки => значения * @param string $value значение - * @return ScafoldController + * @return ScaffoldController */ private function setColumOpt($name, $colum, $value='') { @@ -546,12 +546,12 @@ abstract class ScafoldController extends Controller * Возвращает ссылку на класс заданного поля * * @param string $name имя поля - * @return Scafold_Field_Info инфо о классе + * @return Scaffold_Field_Info инфо о классе */ private function getInfoClass($name) { if (empty($this->fields[$name])) - $this->fields[$name] = new Scafold_Field_Info(); + $this->fields[$name] = new Scaffold_Field_Info(); return $this->fields[$name]; } @@ -678,9 +678,9 @@ abstract class ScafoldController extends Controller /** * Фабрика объектов полей * - * @param Scafold_Field_Info $infoClass Информация указанная пользователем + * @param Scaffold_Field_Info $infoClass Информация указанная пользователем * @param array $fieldInfo Информация о поле из базы данных - * @return Scafold_Field Класс поля + * @return Scaffold_Field Класс поля */ private function getFieldClass($infoClass, $fieldInfo) { @@ -690,20 +690,20 @@ abstract class ScafoldController extends Controller if ($infoClass->type) { - $class = 'Scafold_'.ucfirst($infoClass->type); + $class = 'Scaffold_'.ucfirst($infoClass->type); return new $class($infoClass); } //определяем по типам и прочей известной информации if ($infoClass->foreign) - return new Scafold_Foreign($infoClass); + return new Scaffold_Foreign($infoClass); $match = array(); if (preg_match('#(.*?)(?:\((.+?)\)|$)#', $fieldInfo['Type'], $match)) - if (class_exists($class = 'Scafold_'.ucfirst($match[1]))) + if (class_exists($class = 'Scaffold_'.ucfirst($match[1]))) return new $class($infoClass, isset($match[2]) ? $match[2] : false ); - return new Scafold_Field($infoClass); + return new Scaffold_Field($infoClass); } private function endTest() diff --git a/lib/Modules/Scafold/scafold/edit.html b/lib/Modules/Scaffold/scaffold/edit.html similarity index 93% rename from lib/Modules/Scafold/scafold/edit.html rename to lib/Modules/Scaffold/scaffold/edit.html index 5877e6b..85079d8 100644 --- a/lib/Modules/Scafold/scafold/edit.html +++ b/lib/Modules/Scaffold/scaffold/edit.html @@ -3,7 +3,7 @@ Поле <?php echo $fields[$k]->title ?> имеет некорректное значение<br /> <?php } ?> <?php } ?> -<form action="<?php echo Url::C('edit/'.$id) ?>" class="scafoldEdit" +<form action="<?php echo Url::C('edit/'.$id) ?>" class="scaffoldEdit" method="post" id="form_<?php echo $table ?>" enctype="multipart/form-data"> <dl> <?php foreach($data as $k=>$v) { diff --git a/lib/Modules/Scafold/scafold/filterForm.html b/lib/Modules/Scaffold/scaffold/filterForm.html similarity index 75% rename from lib/Modules/Scafold/scafold/filterForm.html rename to lib/Modules/Scaffold/scaffold/filterForm.html index 59b0d90..74e8e37 100644 --- a/lib/Modules/Scafold/scafold/filterForm.html +++ b/lib/Modules/Scaffold/scaffold/filterForm.html @@ -1,5 +1,5 @@ <form action="<?php echo Url::C('filter') ?>" - method="post" id="filter_<?php echo $table ?>" class="scafoldFilter"> + method="post" id="filter_<?php echo $table ?>" class="scaffoldFilter"> <?php foreach ($filter as $v) {?> <?php echo $v; ?> <?php } ?> diff --git a/lib/Modules/Scafold/scafold/index.html b/lib/Modules/Scaffold/scaffold/index.html similarity index 90% rename from lib/Modules/Scafold/scafold/index.html rename to lib/Modules/Scaffold/scaffold/index.html index 75b31ca..ec3650f 100644 --- a/lib/Modules/Scafold/scafold/index.html +++ b/lib/Modules/Scaffold/scaffold/index.html @@ -7,7 +7,7 @@ <?php echo $pager; ?> <?php if (count($data)>0) { ?> -<table id="table_<?php echo $table ?>" class="scafoldTable"> +<table id="table_<?php echo $table ?>" class="scaffoldTable"> <tr> <?php foreach($data[0] as $key=>$v) { $i = $fields[$key]; @@ -15,9 +15,9 @@ continue; ?> <th><a href="<?php echo Url::C('sort/'.$key) ?>"><?php echo $i->title ?></a> - <?php if (isset($order) && $order['field'] == $key) { ?><span class="scafoldSort"> + <?php if (isset($order) && $order['field'] == $key) { ?><span class="scaffoldSort"> <?php if ($options['sortImages']) {?> - <img src="/buildin/<?php echo $order['direction']=='ASC' ? 'az' : 'za' ?>.png" + <img src="/built-in/<?php echo $order['direction']=='ASC' ? 'az' : 'za' ?>.png" alt="<?php echo $order['direction']=='ASC' ? '↓' : '↑' ?>" /> <?php } else { ?> <span><?php echo $order['direction']=='ASC' ? '↓' : '↑' ?></span> diff --git a/lib/Modules/Scafold/scafold/parent.html b/lib/Modules/Scaffold/scaffold/parent.html similarity index 100% rename from lib/Modules/Scafold/scafold/parent.html rename to lib/Modules/Scaffold/scaffold/parent.html diff --git a/www/buildin/scafold.css b/www/buildin/scafold.css deleted file mode 100644 index 24bc8bb..0000000 --- a/www/buildin/scafold.css +++ /dev/null @@ -1,64 +0,0 @@ -div.pageslist {text-align:center;} - -table.scafoldTable -{ - border:2px solid black; - width: 100%; -} - -.scafoldTable th, .scafoldTable td -{ - border:1px dashed black; - padding: 5px; - margin: 0; -} - -.scafoldTable td:last-child, .scafoldTable td:nth-last-child(2) -{ - width: 25px; -} - -.scafoldTable tr {vertical-align:top;} -.scafoldTable th { background-color:#eec0c0; } -.scafoldTable tr td { background-color:#ddd; text-align:left;} -.scafoldTable tr:nth-child(odd) td { background-color:#c0ffc0; } - -.scafoldTable table.tnone {border: 1px solid black;} -.scafoldTable table.tnone td {background-color:#FFF; border: none; padding: 0; margin: 0;} - -.scafoldTable .scafoldSort { - position: relative; -} - -.scafoldTable .scafoldSort * { - position: absolute; -} - -form.scafoldEdit .err {color: red;} - -form.scafoldEdit textarea:focus, input:focus, select:focus { - border: 2px solid #900; -} - -form.scafoldEdit dt { - padding: 0; - margin: 0.7em 1em 0.5em 0; - width: 25%; - float: left; - clear: left; - text-align: right; -} - -form.scafoldEdit dd { - margin: 0; - padding: 0.5em 0; - width: 70%; - float: left; -} - -form.scafoldEdit small -{ - display: block; - margin-left: 20px; - color: #999; -} diff --git a/www/buildin/az.png b/www/built-in/az.png similarity index 100% rename from www/buildin/az.png rename to www/built-in/az.png diff --git a/www/built-in/scaffold.css b/www/built-in/scaffold.css new file mode 100644 index 0000000..db373b6 --- /dev/null +++ b/www/built-in/scaffold.css @@ -0,0 +1,64 @@ +div.pageslist {text-align:center;} + +table.scaffoldTable +{ + border:2px solid black; + width: 100%; +} + +.scaffoldTable th, .scaffoldTable td +{ + border:1px dashed black; + padding: 5px; + margin: 0; +} + +.scaffoldTable td:last-child, .scaffoldTable td:nth-last-child(2) +{ + width: 25px; +} + +.scaffoldTable tr {vertical-align:top;} +.scaffoldTable th { background-color:#eec0c0; } +.scaffoldTable tr td { background-color:#ddd; text-align:left;} +.scaffoldTable tr:nth-child(odd) td { background-color:#c0ffc0; } + +.scaffoldTable table.tnone {border: 1px solid black;} +.scaffoldTable table.tnone td {background-color:#FFF; border: none; padding: 0; margin: 0;} + +.scaffoldTable .scaffoldSort { + position: relative; +} + +.scaffoldTable .scaffoldSort * { + position: absolute; +} + +form.scaffoldEdit .err {color: red;} + +form.scaffoldEdit textarea:focus, input:focus, select:focus { + border: 2px solid #900; +} + +form.scaffoldEdit dt { + padding: 0; + margin: 0.7em 1em 0.5em 0; + width: 25%; + float: left; + clear: left; + text-align: right; +} + +form.scaffoldEdit dd { + margin: 0; + padding: 0.5em 0; + width: 70%; + float: left; +} + +form.scaffoldEdit small +{ + display: block; + margin-left: 20px; + color: #999; +} diff --git a/www/buildin/za.png b/www/built-in/za.png similarity index 100% rename from www/buildin/za.png rename to www/built-in/za.png ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Autoload.php | 2 +- .../default/controllers/TableController.php | 4 +- doc/nginx.conf | 12 ++-- lib/Language.php | 3 +- lib/Modules/{Scafold => Scaffold}/Fields.php | 36 ++++++------ .../ScaffoldController.php} | 58 +++++++++--------- .../scafold => Scaffold/scaffold}/edit.html | 2 +- .../scafold => Scaffold/scaffold}/filterForm.html | 2 +- .../scafold => Scaffold/scaffold}/index.html | 6 +- .../scafold => Scaffold/scaffold}/parent.html | 0 www/buildin/scafold.css | 64 -------------------- www/{buildin => built-in}/az.png | Bin 601 -> 601 bytes www/built-in/scaffold.css | 64 ++++++++++++++++++++ www/{buildin => built-in}/za.png | Bin 613 -> 613 bytes 14 files changed, 126 insertions(+), 127 deletions(-) rename lib/Modules/{Scafold => Scaffold}/Fields.php (92%) rename lib/Modules/{Scafold/ScafoldController.php => Scaffold/ScaffoldController.php} (94%) rename lib/Modules/{Scafold/scafold => Scaffold/scaffold}/edit.html (93%) rename lib/Modules/{Scafold/scafold => Scaffold/scaffold}/filterForm.html (75%) rename lib/Modules/{Scafold/scafold => Scaffold/scaffold}/index.html (90%) rename lib/Modules/{Scafold/scafold => Scaffold/scaffold}/parent.html (100%) delete mode 100644 www/buildin/scafold.css rename www/{buildin => built-in}/az.png (100%) create mode 100644 www/built-in/scaffold.css rename www/{buildin => built-in}/za.png (100%) hooks/post-receive -- quickfw |
From: SeriousDron <ser...@us...> - 2010-08-09 19:00:44
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 8a3d41547344f9dd14c1b56587e3fa3b1aedb1d1 (commit) from 44bf1fc5d50edb27caf449b1c04bf488884cf351 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 8a3d41547344f9dd14c1b56587e3fa3b1aedb1d1 Author: unknown <none)> Date: Mon Aug 9 22:59:16 2010 +0400 * normal config for nginx diff --git a/doc/nginx.conf b/doc/nginx.conf index 6bcc1ce..f1e202a 100644 --- a/doc/nginx.conf +++ b/doc/nginx.conf @@ -1,8 +1,43 @@ +server { + + <...> + + root <...> #must be here for FastCGI + + <...> + location / { - if (!-e $request_filename) { - rewrite ^(.*)$ /index.php$1 break; - proxy_pass http://<...>; - } - proxy_pass http://<...>; - root <...>; + try_files $uri $uri/ @fallback; } + + #For apache backend + location @fallback { + proxy_pass http://127.0.0.1:8080;#Apache must have its own rewrite + proxy_set_header Host $host; + } + + + location ~ \.php$ { #To deny get php files like text + try_files $uri @fastcgi; + + #For apache backend + proxy_pass http://127.0.0.1:8080;#Apache must have its own rewrite + proxy_set_header Host $host; + + #For FastCGI + #fastcgi_pass unix:/var/run/php-fpm/defailt.socket; + #include fastcgi_params; #standart file in nginx + #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + + } + + #For FastCGI + location @fastcgi { + fastcgi_pass unix:/var/run/php-fpm/defailt.socket; + fastcgi_index index.php; + + include fastcgi_params; #standart file in nginx + + fastcgi_param SCRIPT_FILENAME $document_root/index.php; + } +} \ No newline at end of file ----------------------------------------------------------------------- Summary of changes: doc/nginx.conf | 47 +++++++++++++++++++++++++++++++++++++++++------ 1 files changed, 41 insertions(+), 6 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-07 16:53:53
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 44bf1fc5d50edb27caf449b1c04bf488884cf351 (commit) via ec2ccf95487f5571237f2cb671a105436d053fc7 (commit) from c240074d2392b0316ff30a8e19d711053581b676 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 44bf1fc5d50edb27caf449b1c04bf488884cf351 Author: Ivan Borzenkov <iva...@li...> Date: Sat Aug 7 19:47:00 2010 +0400 Удалены *pdo_Blob за ненадобностью diff --git a/lib/DbSimple/Litepdo.php b/lib/DbSimple/Litepdo.php index 36d4a1a..5cc722d 100644 --- a/lib/DbSimple/Litepdo.php +++ b/lib/DbSimple/Litepdo.php @@ -151,39 +151,4 @@ class DbSimple_Litepdo extends DbSimple_Generic_Database } -class DbSimple_Mypdo_Blob implements DbSimple_Generic_Blob -{ - // MySQL does not support separate BLOB fetching. - private $blobdata = null; - private $curSeek = 0; - - public function __construct(&$database, $blobdata=null) - { - $this->blobdata = $blobdata; - $this->curSeek = 0; - } - - public function read($len) - { - $p = $this->curSeek; - $this->curSeek = min($this->curSeek + $len, strlen($this->blobdata)); - return substr($this->blobdata, $this->curSeek, $len); - } - - public function write($data) - { - $this->blobdata .= $data; - } - - public function close() - { - return $this->blobdata; - } - - public function length() - { - return strlen($this->blobdata); - } -} - ?> \ No newline at end of file diff --git a/lib/DbSimple/Mypdo.php b/lib/DbSimple/Mypdo.php index 9c769e5..460aedf 100644 --- a/lib/DbSimple/Mypdo.php +++ b/lib/DbSimple/Mypdo.php @@ -141,39 +141,4 @@ class DbSimple_Mypdo extends DbSimple_Generic_Database } -class DbSimple_Mypdo_Blob implements DbSimple_Generic_Blob -{ - // MySQL does not support separate BLOB fetching. - private $blobdata = null; - private $curSeek = 0; - - public function __construct(&$database, $blobdata=null) - { - $this->blobdata = $blobdata; - $this->curSeek = 0; - } - - public function read($len) - { - $p = $this->curSeek; - $this->curSeek = min($this->curSeek + $len, strlen($this->blobdata)); - return substr($this->blobdata, $this->curSeek, $len); - } - - public function write($data) - { - $this->blobdata .= $data; - } - - public function close() - { - return $this->blobdata; - } - - public function length() - { - return strlen($this->blobdata); - } -} - ?> \ No newline at end of file commit ec2ccf95487f5571237f2cb671a105436d053fc7 Author: Ivan Borzenkov <iva...@li...> Date: Sat Aug 7 19:26:54 2010 +0400 Переименовал все коннекты в link diff --git a/lib/DbSimple/Litepdo.php b/lib/DbSimple/Litepdo.php index 5b3d774..36d4a1a 100644 --- a/lib/DbSimple/Litepdo.php +++ b/lib/DbSimple/Litepdo.php @@ -22,7 +22,7 @@ require_once dirname(__FILE__).'/Generic.php'; */ class DbSimple_Litepdo extends DbSimple_Generic_Database { - private $PDO; + private $link; public function DbSimple_Litepdo($dsn) { @@ -30,17 +30,17 @@ class DbSimple_Litepdo extends DbSimple_Generic_Database return $this->_setLastError("-1", "PDO extension is not loaded", "PDO"); try { - $this->PDO = new PDO('sqlite:'.$dsn['path']); + $this->link = new PDO('sqlite:'.$dsn['path']); } catch (PDOException $e) { $this->_setLastError($e->getCode() , $e->getMessage(), 'new PDO'); } - $this->PDO->exec('SET NAMES '.(isset($dsn['enc'])?$dsn['enc']:'UTF8')); + $this->link->exec('SET NAMES '.(isset($dsn['enc'])?$dsn['enc']:'UTF8')); } public function CreateFunction($function_name, $callback, $num_args) - { return $this->PDO->sqliteCreateFunction($function_name, $callback, $num_args); } + { return $this->link->sqliteCreateFunction($function_name, $callback, $num_args); } public function CreateAggregate($function_name, $step_func, $finalize_func, $num_args) - { return $this->PDO->CreateAggregate($function_name, $step_func, $finalize_func, $num_args); } + { return $this->link->CreateAggregate($function_name, $step_func, $finalize_func, $num_args); } protected function _performGetPlaceholderIgnoreRe() { @@ -55,7 +55,7 @@ class DbSimple_Litepdo extends DbSimple_Generic_Database protected function _performEscape($s, $isIdent=false) { if (!$isIdent) { - return $this->PDO->quote($s); + return $this->link->quote($s); } else { return "`" . str_replace('`', '``', $s) . "`"; } @@ -63,30 +63,30 @@ class DbSimple_Litepdo extends DbSimple_Generic_Database protected function _performTransaction($parameters=null) { - return $this->PDO->beginTransaction(); + return $this->link->beginTransaction(); } protected function _performCommit() { - return $this->PDO->commit(); + return $this->link->commit(); } protected function _performRollback() { - return $this->PDO->rollBack(); + return $this->link->rollBack(); } protected function _performQuery($queryMain) { $this->_lastQuery = $queryMain; $this->_expandPlaceholders($queryMain, false); - $p = $this->PDO->query($queryMain[0]); + $p = $this->link->query($queryMain[0]); if (!$p) return $this->_setDbError($p,$queryMain[0]); if ($p->errorCode()!=0) return $this->_setDbError($p,$queryMain[0]); if (preg_match('/^\s* INSERT \s+/six', $queryMain[0])) - return $this->PDO->lastInsertId(); + return $this->link->lastInsertId(); if ($p->columnCount()==0) return $p->rowCount(); //Если у нас в запросе есть хотя-бы одна колонка - это по любому будет select @@ -131,7 +131,7 @@ class DbSimple_Litepdo extends DbSimple_Generic_Database protected function _setDbError($obj,$q) { - $info=$obj?$obj->errorInfo():$this->PDO->errorInfo(); + $info=$obj?$obj->errorInfo():$this->link->errorInfo(); return $this->_setLastError($info[1], $info[2], $q); } diff --git a/lib/DbSimple/Mypdo.php b/lib/DbSimple/Mypdo.php index b936248..9c769e5 100644 --- a/lib/DbSimple/Mypdo.php +++ b/lib/DbSimple/Mypdo.php @@ -22,7 +22,7 @@ require_once dirname(__FILE__).'/Generic.php'; */ class DbSimple_Mypdo extends DbSimple_Generic_Database { - private $PDO; + private $link; public function DbSimple_Mypdo($dsn) { @@ -31,7 +31,7 @@ class DbSimple_Mypdo extends DbSimple_Generic_Database return $this->_setLastError("-1", "PDO extension is not loaded", "PDO"); try { - $this->PDO = new PDO('mysql:host='.$dsn['host'].(empty($dsn['port'])?'':';port='.$dsn['port']).';dbname='.$base, + $this->link = new PDO('mysql:host='.$dsn['host'].(empty($dsn['port'])?'':';port='.$dsn['port']).';dbname='.$base, $dsn['user'], isset($dsn['pass'])?$dsn['pass']:'', array( PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT, PDO::ATTR_PERSISTENT => isset($dsn['persist']) && $dsn['persist'], @@ -56,7 +56,7 @@ class DbSimple_Mypdo extends DbSimple_Generic_Database protected function _performEscape($s, $isIdent=false) { if (!$isIdent) { - return $this->PDO->quote($s); + return $this->link->quote($s); } else { return "`" . str_replace('`', '``', $s) . "`"; } @@ -64,30 +64,30 @@ class DbSimple_Mypdo extends DbSimple_Generic_Database protected function _performTransaction($parameters=null) { - return $this->PDO->beginTransaction(); + return $this->link->beginTransaction(); } protected function _performCommit() { - return $this->PDO->commit(); + return $this->link->commit(); } protected function _performRollback() { - return $this->PDO->rollBack(); + return $this->link->rollBack(); } protected function _performQuery($queryMain) { $this->_lastQuery = $queryMain; $this->_expandPlaceholders($queryMain, false); - $p = $this->PDO->query($queryMain[0]); + $p = $this->link->query($queryMain[0]); if (!$p) return $this->_setDbError($p,$queryMain[0]); if ($p->errorCode()!=0) return $this->_setDbError($p,$queryMain[0]); if (preg_match('/^\s* INSERT \s+/six', $queryMain[0])) - return $this->PDO->lastInsertId(); + return $this->link->lastInsertId(); if ($p->columnCount()==0) return $p->rowCount(); //Если у нас в запросе есть хотя-бы одна колонка - это по любому будет select @@ -121,7 +121,7 @@ class DbSimple_Mypdo extends DbSimple_Generic_Database protected function _setDbError($obj,$q) { - $info=$obj?$obj->errorInfo():$this->PDO->errorInfo(); + $info=$obj?$obj->errorInfo():$this->link->errorInfo(); return $this->_setLastError($info[1], $info[2], $q); } diff --git a/lib/DbSimple/Sqlite.php b/lib/DbSimple/Sqlite.php index 674e3ab..1190007 100644 --- a/lib/DbSimple/Sqlite.php +++ b/lib/DbSimple/Sqlite.php @@ -21,7 +21,7 @@ require_once dirname(__FILE__).'/Generic.php'; */ class DbSimple_Sqlite extends DbSimple_Generic_Database { - private $db; + private $link; public function __construct($dsn) { $connect = 'sqlite_'.((isset($dsn['persist']) && $dsn['persist'])?'p':'').'open'; @@ -30,7 +30,7 @@ class DbSimple_Sqlite extends DbSimple_Generic_Database $err = ''; try { - $this->db = sqlite_factory($dsn['path'], 0666, &$err); + $this->link = sqlite_factory($dsn['path'], 0666, &$err); } catch (Exception $e) { @@ -39,9 +39,9 @@ class DbSimple_Sqlite extends DbSimple_Generic_Database } public function CreateFunction($function_name, $callback, $num_args) - { return $this->db->createFunction($function_name, $callback, $num_args); } + { return $this->link->createFunction($function_name, $callback, $num_args); } public function CreateAggregate($function_name, $step_func, $finalize_func, $num_args) - { return $this->db->createAggregate($function_name, $step_func, $finalize_func, $num_args); } + { return $this->link->createAggregate($function_name, $step_func, $finalize_func, $num_args); } protected function _performGetPlaceholderIgnoreRe() { @@ -64,17 +64,17 @@ class DbSimple_Sqlite extends DbSimple_Generic_Database protected function _performTransaction($parameters=null) { - return $this->db->query('BEGIN TRANSACTION'); + return $this->link->query('BEGIN TRANSACTION'); } protected function _performCommit() { - return $this->db->query('COMMIT TRANSACTION'); + return $this->link->query('COMMIT TRANSACTION'); } protected function _performRollback() { - return $this->db->query('ROLLBACK TRANSACTION'); + return $this->link->query('ROLLBACK TRANSACTION'); } protected function _performQuery($queryMain) @@ -82,15 +82,15 @@ class DbSimple_Sqlite extends DbSimple_Generic_Database $this->_lastQuery = $queryMain; $this->_expandPlaceholders($queryMain, false); $error_msg = ''; - $p = $this->db->query($queryMain[0], SQLITE_ASSOC, $error_msg); + $p = $this->link->query($queryMain[0], SQLITE_ASSOC, $error_msg); if (!$p) return $this->_setDbError($p->lastError(), $error_msg, $queryMain[0]); if ($error_msg) return $this->_setDbError($p->lastError(), $error_msg, $queryMain[0]); if (preg_match('/^\s* INSERT \s+/six', $queryMain[0])) - return $this->db->lastInsertRowid(); + return $this->link->lastInsertRowid(); if ($p->numFields()==0) - return $this->db->changes(); + return $this->link->changes(); //Если у нас в запросе есть хотя-бы одна колонка - это по любому будет select return $p->fetchAll(SQLITE_ASSOC); } ----------------------------------------------------------------------- Summary of changes: lib/DbSimple/Litepdo.php | 59 +++++++++------------------------------------ lib/DbSimple/Mypdo.php | 53 +++++++---------------------------------- lib/DbSimple/Sqlite.php | 20 +++++++------- 3 files changed, 31 insertions(+), 101 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-04 19:58:57
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via c240074d2392b0316ff30a8e19d711053581b676 (commit) from 1b3a6181e7a334f25212ea60c3ec0a90ee08ea7c (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit c240074d2392b0316ff30a8e19d711053581b676 Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 4 23:58:35 2010 +0400 Исправлена ошибка сохранения путей diff --git a/QFW/QuickFW/Router.php b/QFW/QuickFW/Router.php index 4318313..980e5da 100644 --- a/QFW/QuickFW/Router.php +++ b/QFW/QuickFW/Router.php @@ -136,9 +136,6 @@ class QuickFW_Router //Сохраняем старый путь шаблонов $scriptPath = QFW::$view->getScriptPath(); - //Выставляем новые пути вызова и сохраняем старые - list($lpPath, $this->ParentPath, $this->CurPath) = - array($this->ParentPath, $this->CurPath, $MCA['Path']); //сохраняем прошлый MCA list ($oModule, $oController, $oAction) = array($this->cModule, $this->cController, $this->cAction); @@ -172,9 +169,6 @@ class QuickFW_Router //восстанавливаем MCA list ($this->cModule, $this->cController, $this->cAction) = array($oModule, $oController, $oAction); - //восстанавливаем пути вызова - list($this->CurPath, $this->ParentPath) = - array($this->ParentPath, $lpPath); //Возвращаем путь к шаблонам после вызова QFW::$view->setScriptPath($scriptPath); @@ -189,14 +183,19 @@ class QuickFW_Router if ($Params) $MCA['Params'] = array_merge($MCA['Params'], $Params); + //Выставляем новые пути вызова и сохраняем старые + list($lpPath, $this->ParentPath, $this->CurPath) = + array($this->ParentPath, $this->CurPath, $MCA['Path']); + $result = call_user_func_array(array($MCA['Class'], $MCA['Action'].$MCA['Type']), $MCA['Params']); - //восстанавливаем MCA - list ($this->cModule, $this->cController, $this->cAction) = - array($oModule, $oController, $oAction); //восстанавливаем пути вызова list($this->CurPath, $this->ParentPath) = array($this->ParentPath, $lpPath); + + //восстанавливаем MCA + list ($this->cModule, $this->cController, $this->cAction) = + array($oModule, $oController, $oAction); //Возвращаем путь к шаблонам после вызова QFW::$view->setScriptPath($scriptPath); ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Router.php | 17 ++++++++--------- 1 files changed, 8 insertions(+), 9 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-04 19:52:15
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 1b3a6181e7a334f25212ea60c3ec0a90ee08ea7c (commit) from 89ab550468d7e75a3d965de46661847b59bf6be4 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 1b3a6181e7a334f25212ea60c3ec0a90ee08ea7c Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 4 23:51:55 2010 +0400 Переводы строк diff --git a/lib/utils.php b/lib/utils.php index b6bce92..3ee2f25 100644 --- a/lib/utils.php +++ b/lib/utils.php @@ -1,324 +1,324 @@ -<?php - -/** - * Выполняет HTTP-запрос по заданному URL, - * - * @var string url адрес запроса - * @var array data массив данных - * @return string|array|false|null Возвращает: ответ сервера (без заголовков), false в случае неудачи или null в случае таймаута - */ -function getUrl($url, $data=array()) -{ - $c = curl_init(); - curl_setopt_array($c, array( - CURLOPT_URL => $url, - CURLOPT_RETURNTRANSFER => 1, - CURLOPT_FOLLOWLOCATION => 1, - )); - if (isset($data['post'])) //POST запрос - { - curl_setopt_array($c, array( - CURLOPT_POST => 1, - CURLOPT_POSTFIELDS => is_array($data['post']) ? http_build_query($data['post']) : $data['post'], - )); - } - if (empty($data['file']) && !empty(QFW::$config['consts']['curlTimeOut'])) - curl_setopt($c, CURLOPT_TIMEOUT, QFW::$config['consts']['curlTimeOut']); - if (!empty($data['sid'])) - curl_setopt($c, CURLOPT_COOKIE, 'PHPSESSID='.$data['sid']); - if (!empty($data['user']) && !empty($data['pass'])) - curl_setopt($c, CURLOPT_USERPWD, $data['user'] . ":" . $data['pass']); - if (!empty($data['file'])) - if (false === ($hFile = fopen($data['file'], 'w'))) - return false; - else - curl_setopt_array($c, array( - CURLOPT_FILE => $hFile, - CURLOPT_HEADER => 0, - )); - if (isset(QFW::$config['host']['proxy'])) - curl_setopt($c, CURLOPT_PROXY, QFW::$config['host']['proxy']); - - $content = curl_exec($c); - $code = curl_getinfo($c, CURLINFO_HTTP_CODE); - $errno = curl_errno($c); - curl_close($c); - if ($errno == 28) //CURLE_OPERATION_TIMEDOUT - return false; - if (!empty($data['file'])) - return fclose($hFile); - if (array_key_exists('rcode',$data)) - return array( - 'code'=>$code, - 'content'=>$content, - ); - if ($code >= 300) - return false; - return $content; -} - -/** - * Проверяет урл на корректность - * - * @link http://php.spb.ru/php/regexp.html - * @param string $url Урл, который нужно проверить на корректность - * @return false|null|string Урл или ошибка - */ -function checkUrl($url) -{ - // режем левые символы и крайние пробелы - $url = trim(preg_replace('/[^\x20-\xFF]/', '', strval($url))); - // если пусто - выход - if (strlen($url)==0) - return null; - //проверяем УРЛ на правильность - if (!preg_match('~^(?:(?:https?|ftp)://(?:[a-z0-9_-]{1,32}'. - '(?::[a-z0-9_-]{1,32})?@)?)?(?:(?:[a-z0-9-]{1,128}\.)+(?:com|net|'. - 'org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?'. - '!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:/[a-zа-я0-9.,_@%&'. - '\[\]?+:=\~/"\'\(\)-]*)?(?:#[^ \'"&<>]*)?$~iu',$url,$ok)) - return false; // если не правильно - выход - // если нет протокала - добавить - if (strpos($url, '://') === false) - $url='http://'.$url; - return $url; -} - -/** - * Вывод сообщения с разбивкой длинных слов без повреждения тегов - * - * @param string $msg собщение, в котором нужно разбить слова - * @param integer $n длина, на которой ставить пробел - * @return string сообщение со словами, не превышающими n символов - */ -function msg2html($msg, $n=50) -{ - $marker = " <> "; - - # Сохраняем все тэги чтобы уберечь их от разбивки - preg_match_all("/(<.*?>)/si",$msg,$tags); - - # Заменяем все тэги на маркеры - $msg = preg_replace("/(<.*?>)/si", $marker, $msg); - - $msg = preg_replace('|\S{'.$n.'}|u','\0 ',$msg); - - # Восстанавливаем тэги в места которых были отмечены маркерами - for ($i=0; $i<count($tags[0]); $i++) - $msg = preg_replace("/$marker/si", $tags[1][$i], $msg, 1); - - return $msg; -} - -/** - * Преобразование URL в ссылки - */ -function make_urls($string) -{ - $p = '/((?:(?:ht|f)tps?:\/\/|www\.)[^<\s\n]+)(?<![]\.,:;!\})<-])/msiu'; - $r = '<a href="$1">$1</a>$2'; - - $string = preg_replace($p, $r, $string); - - $p = '/ href="www\./msiu'; - $r = ' href="http://www.'; - - return preg_replace($p, $r, $string); -} - -/** - * Печать размера файла в форматированном виде - */ -function printSize($size) -{ - if ($size>1024*1024*2) - return round($size/1024/1024,2).' Мб'; - if ($size>1024*10) - return round($size/1024,2).' Кб'; - return $size.' байт'; -} - -/** - * Обрезает длинные строки, добавляя в конце многоточие - * - * @param string $str строка, которую нужно обрезать - * @param integer $size до скольки знаков - */ -function my_trim($str, $size) -{ - if (mb_strlen($str)>$size) - $str=mb_substr($str,0,$size-3).'...'; - return $str; -} - -/** - * Обрезает длинные строки, не разрывая последнее слово - * - * @param string $str строка, которую нужно обрезать - * @param integer $size до скольки знаков - */ -function clearCut($str, $size) -{ - if(mb_strlen($str) <= $size) - return $str; - - $words = explode(' ', mb_substr($str, 0, $size)); - return implode(' ', array_slice($words, 0, count($words)-1)).'...'; -} - -/** - * Выдает несколько неповторяющихся случайных значений - */ -function n_rand($min, $max, $count) -{ - if ($max - $min + 1 < $count) - return array(); - $a = array(); - while(count($a)<$count) - if (!in_array($x = mt_rand($min,$max),$a)) - $a[] = $x; - return $a; -} - -/** - * Прообразование xml в массив - */ -function xml2array($xml,$attrName='attr',$arrFlar='array') -{ - $xmlary = array(); - - $reels = '/<(\w+)\s*([^>]*)\s*(?:\/>|>(.*?)<\/\s*\\1\s*>)/s'; - $reattrs = '/(\w+)=(?:"|\')([^"\']*)(?:"|\')/'; - - preg_match_all($reels, $xml, $elements); - - foreach ($elements[1] as $ie => $name) - { - //для получения блока текста - $cdend = strpos($elements[3][$ie], "<"); - if ($cdend > 0) - $xmlary[$name][$ie]["text"] = substr($elements[3][$ie], 0, $cdend); - - $elements[3][$ie] = trim($elements[3][$ie]); - if (preg_match($reels, $elements[3][$ie])) - $xmlary[$name][$ie] = xml2array($elements[3][$ie]); - else if ($elements[3][$ie]) - $xmlary[$name][$ie] = $elements[3][$ie]; - else - $xmlary[$name][$ie] = null; - - if ($attributes = trim($elements[2][$ie])) - { - preg_match_all($reattrs, $attributes, $att); - foreach ($att[1] as $ia => $xx) - $xmlary[$name][$ie][$attrName][$att[1][$ia]] = $att[2][$ia]; - } - - } - foreach ($xmlary as $k => $v) - { - if (count($v)==1) - $xmlary[$k]=current($v); - else - { - $xmlary[$k]=array_values($v); - $xmlary[$k][$arrFlar]=$k; - } - } - - return $xmlary; -} - -/** - * Прообразование массива в xml - */ -function array2xml($array,$attrName='attr',$arrFlar='array') -{ - if(empty($array)) - return ''; - - $xml=array(); - $subattr=''; - $arr=array_key_exists($arrFlar,$array)?$array[$arrFlar]:false; - foreach ($array as $k => $v) - { - if ($k===$arrFlar) - continue; - if ($k===$attrName) - { - foreach ($v as $an => $av) - $v[$an]=$an.'="'.$av.'"'; - $subattr=' '.join($v,' '); - continue; - } - $k=$arr?$arr:$k; - if (is_array($v)) - { - $carr=array_key_exists($arrFlar,$v); - $child=array2xml($v,$attrName); - if (is_array($child) && !$carr) - $xml[]='<'.$k.$child['attr'].'>'.$child['xml'].'</'.$k.'>'; - elseif ($carr) - $xml[]=$child; - else - $xml[]='<'.$k.'>'.$child.'</'.$k.'>'; - } - elseif ($v!=null) - $xml[]='<'.$k.'>'.$v.'</'.$k.'>'; - else - $xml[]='<'.$k.'/>'; - } - $xml=join("\n",$xml); - if ($subattr!='') - return array('xml'=>$xml,'attr'=>$subattr); - return $xml; -} - -/** - * Вывод окончаний русских слов с учетом числительных (например сообщение сообщения сообщений) - * - * @param intereg $n число - * @param string $form1 единственное - * @param string $form2 форма для 2-4 - * @param string $form5 форма для 5 и более - * @return string нужная форма - */ -function pluralForm($n, $form1, $form2, $form5) -{ - $n = abs($n) % 100; - $n1 = $n % 10; - if ($n > 10 && $n < 20) return $form5; - if ($n1 > 1 && $n1 < 5) return $form2; - if ($n1 == 1) return $form1; - return $form5; -} - -/** - * Вызывает preg_match(_all) и - * <br>возвращается данные в удобном формате - * <br>с использованием флага PREG_SET_ORDER - * - * @param string $pattern регулярное выражение - * @param string $subject строка для поиска - * @param bool $all вызывать preg_match_all - * @return array найденные паттерны - */ -function preg($pattern, $subject, $all = true) -{ - $m = array(); - if ($all) - preg_match_all($pattern, $subject, $m, PREG_SET_ORDER); - else - preg_match($pattern, $subject, $m); - return $m; -} - -/** - * Функции ескейпинга в нужной кодировке - * - * @param string $s Исходная строка - * @return string htmlspecialchars($s, ENT_QUOTES, $encoding) - */ -function esc($s) { return htmlspecialchars($s, ENT_QUOTES, QFW::$config['host']['encoding']); } - -?> +<?php + +/** + * Выполняет HTTP-запрос по заданному URL, + * + * @var string url адрес запроса + * @var array data массив данных + * @return string|array|false|null Возвращает: ответ сервера (без заголовков), false в случае неудачи или null в случае таймаута + */ +function getUrl($url, $data=array()) +{ + $c = curl_init(); + curl_setopt_array($c, array( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_FOLLOWLOCATION => 1, + )); + if (isset($data['post'])) //POST запрос + { + curl_setopt_array($c, array( + CURLOPT_POST => 1, + CURLOPT_POSTFIELDS => is_array($data['post']) ? http_build_query($data['post']) : $data['post'], + )); + } + if (empty($data['file']) && !empty(QFW::$config['consts']['curlTimeOut'])) + curl_setopt($c, CURLOPT_TIMEOUT, QFW::$config['consts']['curlTimeOut']); + if (!empty($data['sid'])) + curl_setopt($c, CURLOPT_COOKIE, 'PHPSESSID='.$data['sid']); + if (!empty($data['user']) && !empty($data['pass'])) + curl_setopt($c, CURLOPT_USERPWD, $data['user'] . ":" . $data['pass']); + if (!empty($data['file'])) + if (false === ($hFile = fopen($data['file'], 'w'))) + return false; + else + curl_setopt_array($c, array( + CURLOPT_FILE => $hFile, + CURLOPT_HEADER => 0, + )); + if (isset(QFW::$config['host']['proxy'])) + curl_setopt($c, CURLOPT_PROXY, QFW::$config['host']['proxy']); + + $content = curl_exec($c); + $code = curl_getinfo($c, CURLINFO_HTTP_CODE); + $errno = curl_errno($c); + curl_close($c); + if ($errno == 28) //CURLE_OPERATION_TIMEDOUT + return false; + if (!empty($data['file'])) + return fclose($hFile); + if (array_key_exists('rcode',$data)) + return array( + 'code'=>$code, + 'content'=>$content, + ); + if ($code >= 300) + return false; + return $content; +} + +/** + * Проверяет урл на корректность + * + * @link http://php.spb.ru/php/regexp.html + * @param string $url Урл, который нужно проверить на корректность + * @return false|null|string Урл или ошибка + */ +function checkUrl($url) +{ + // режем левые символы и крайние пробелы + $url = trim(preg_replace('/[^\x20-\xFF]/', '', strval($url))); + // если пусто - выход + if (strlen($url)==0) + return null; + //проверяем УРЛ на правильность + if (!preg_match('~^(?:(?:https?|ftp)://(?:[a-z0-9_-]{1,32}'. + '(?::[a-z0-9_-]{1,32})?@)?)?(?:(?:[a-z0-9-]{1,128}\.)+(?:com|net|'. + 'org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?'. + '!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:/[a-zа-я0-9.,_@%&'. + '\[\]?+:=\~/"\'\(\)-]*)?(?:#[^ \'"&<>]*)?$~iu',$url,$ok)) + return false; // если не правильно - выход + // если нет протокала - добавить + if (strpos($url, '://') === false) + $url='http://'.$url; + return $url; +} + +/** + * Вывод сообщения с разбивкой длинных слов без повреждения тегов + * + * @param string $msg собщение, в котором нужно разбить слова + * @param integer $n длина, на которой ставить пробел + * @return string сообщение со словами, не превышающими n символов + */ +function msg2html($msg, $n=50) +{ + $marker = " <> "; + + # Сохраняем все тэги чтобы уберечь их от разбивки + preg_match_all("/(<.*?>)/si",$msg,$tags); + + # Заменяем все тэги на маркеры + $msg = preg_replace("/(<.*?>)/si", $marker, $msg); + + $msg = preg_replace('|\S{'.$n.'}|u','\0 ',$msg); + + # Восстанавливаем тэги в места которых были отмечены маркерами + for ($i=0; $i<count($tags[0]); $i++) + $msg = preg_replace("/$marker/si", $tags[1][$i], $msg, 1); + + return $msg; +} + +/** + * Преобразование URL в ссылки + */ +function make_urls($string) +{ + $p = '/((?:(?:ht|f)tps?:\/\/|www\.)[^<\s\n]+)(?<![]\.,:;!\})<-])/msiu'; + $r = '<a href="$1">$1</a>$2'; + + $string = preg_replace($p, $r, $string); + + $p = '/ href="www\./msiu'; + $r = ' href="http://www.'; + + return preg_replace($p, $r, $string); +} + +/** + * Печать размера файла в форматированном виде + */ +function printSize($size) +{ + if ($size>1024*1024*2) + return round($size/1024/1024,2).' Мб'; + if ($size>1024*10) + return round($size/1024,2).' Кб'; + return $size.' байт'; +} + +/** + * Обрезает длинные строки, добавляя в конце многоточие + * + * @param string $str строка, которую нужно обрезать + * @param integer $size до скольки знаков + */ +function my_trim($str, $size) +{ + if (mb_strlen($str)>$size) + $str=mb_substr($str,0,$size-3).'...'; + return $str; +} + +/** + * Обрезает длинные строки, не разрывая последнее слово + * + * @param string $str строка, которую нужно обрезать + * @param integer $size до скольки знаков + */ +function clearCut($str, $size) +{ + if(mb_strlen($str) <= $size) + return $str; + + $words = explode(' ', mb_substr($str, 0, $size)); + return implode(' ', array_slice($words, 0, count($words)-1)).'...'; +} + +/** + * Выдает несколько неповторяющихся случайных значений + */ +function n_rand($min, $max, $count) +{ + if ($max - $min + 1 < $count) + return array(); + $a = array(); + while(count($a)<$count) + if (!in_array($x = mt_rand($min,$max),$a)) + $a[] = $x; + return $a; +} + +/** + * Прообразование xml в массив + */ +function xml2array($xml,$attrName='attr',$arrFlar='array') +{ + $xmlary = array(); + + $reels = '/<(\w+)\s*([^>]*)\s*(?:\/>|>(.*?)<\/\s*\\1\s*>)/s'; + $reattrs = '/(\w+)=(?:"|\')([^"\']*)(?:"|\')/'; + + preg_match_all($reels, $xml, $elements); + + foreach ($elements[1] as $ie => $name) + { + //для получения блока текста + $cdend = strpos($elements[3][$ie], "<"); + if ($cdend > 0) + $xmlary[$name][$ie]["text"] = substr($elements[3][$ie], 0, $cdend); + + $elements[3][$ie] = trim($elements[3][$ie]); + if (preg_match($reels, $elements[3][$ie])) + $xmlary[$name][$ie] = xml2array($elements[3][$ie]); + else if ($elements[3][$ie]) + $xmlary[$name][$ie] = $elements[3][$ie]; + else + $xmlary[$name][$ie] = null; + + if ($attributes = trim($elements[2][$ie])) + { + preg_match_all($reattrs, $attributes, $att); + foreach ($att[1] as $ia => $xx) + $xmlary[$name][$ie][$attrName][$att[1][$ia]] = $att[2][$ia]; + } + + } + foreach ($xmlary as $k => $v) + { + if (count($v)==1) + $xmlary[$k]=current($v); + else + { + $xmlary[$k]=array_values($v); + $xmlary[$k][$arrFlar]=$k; + } + } + + return $xmlary; +} + +/** + * Прообразование массива в xml + */ +function array2xml($array,$attrName='attr',$arrFlar='array') +{ + if(empty($array)) + return ''; + + $xml=array(); + $subattr=''; + $arr=array_key_exists($arrFlar,$array)?$array[$arrFlar]:false; + foreach ($array as $k => $v) + { + if ($k===$arrFlar) + continue; + if ($k===$attrName) + { + foreach ($v as $an => $av) + $v[$an]=$an.'="'.$av.'"'; + $subattr=' '.join($v,' '); + continue; + } + $k=$arr?$arr:$k; + if (is_array($v)) + { + $carr=array_key_exists($arrFlar,$v); + $child=array2xml($v,$attrName); + if (is_array($child) && !$carr) + $xml[]='<'.$k.$child['attr'].'>'.$child['xml'].'</'.$k.'>'; + elseif ($carr) + $xml[]=$child; + else + $xml[]='<'.$k.'>'.$child.'</'.$k.'>'; + } + elseif ($v!=null) + $xml[]='<'.$k.'>'.$v.'</'.$k.'>'; + else + $xml[]='<'.$k.'/>'; + } + $xml=join("\n",$xml); + if ($subattr!='') + return array('xml'=>$xml,'attr'=>$subattr); + return $xml; +} + +/** + * Вывод окончаний русских слов с учетом числительных (например сообщение сообщения сообщений) + * + * @param intereg $n число + * @param string $form1 единственное + * @param string $form2 форма для 2-4 + * @param string $form5 форма для 5 и более + * @return string нужная форма + */ +function pluralForm($n, $form1, $form2, $form5) +{ + $n = abs($n) % 100; + $n1 = $n % 10; + if ($n > 10 && $n < 20) return $form5; + if ($n1 > 1 && $n1 < 5) return $form2; + if ($n1 == 1) return $form1; + return $form5; +} + +/** + * Вызывает preg_match(_all) и + * <br>возвращается данные в удобном формате + * <br>с использованием флага PREG_SET_ORDER + * + * @param string $pattern регулярное выражение + * @param string $subject строка для поиска + * @param bool $all вызывать preg_match_all + * @return array найденные паттерны + */ +function preg($pattern, $subject, $all = true) +{ + $m = array(); + if ($all) + preg_match_all($pattern, $subject, $m, PREG_SET_ORDER); + else + preg_match($pattern, $subject, $m); + return $m; +} + +/** + * Функции ескейпинга в нужной кодировке + * + * @param string $s Исходная строка + * @return string htmlspecialchars($s, ENT_QUOTES, $encoding) + */ +function esc($s) { return htmlspecialchars($s, ENT_QUOTES, QFW::$config['host']['encoding']); } + +?> ----------------------------------------------------------------------- Summary of changes: lib/utils.php | 648 ++++++++++++++++++++++++++++---------------------------- 1 files changed, 324 insertions(+), 324 deletions(-) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-04 19:31:08
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 89ab550468d7e75a3d965de46661847b59bf6be4 (commit) via c33041e16b4cd4597fd1626528fdd445d18c94a2 (commit) via 22a4c29cfc27657a4c0023e0146c97d27e9d805b (commit) via 5cd62d380b86a8b5204f89d4b1bed70f5edb07c9 (commit) via a0b3d2823dea0a5a4c2f2ca62e1eba22b3c1819a (commit) from 97d4f68175e4d11ec2cb0204f39cfdabf31ba18a (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 89ab550468d7e75a3d965de46661847b59bf6be4 Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 4 23:30:21 2010 +0400 Автолоад контроллеров diff --git a/QFW/QuickFW/Autoload.php b/QFW/QuickFW/Autoload.php index c6176c6..1f43302 100644 --- a/QFW/QuickFW/Autoload.php +++ b/QFW/QuickFW/Autoload.php @@ -16,11 +16,36 @@ class Autoload { spl_autoload_register(array(__CLASS__, 'Bind')); spl_autoload_register(array(__CLASS__, 'Dirs')); + spl_autoload_register(array(__CLASS__, 'Controller')); if (is_callable($function)) spl_autoload_register($function); } /** + * Автолоад контроллеров (при наследовании) + * + * @param string $class искомый класс контроллера + */ + static public function Controller($class) + { + if (mb_strpos($class, 'Controller') === false) + return false; + $class = strtr($class,'_','/'); + //пространство имен + if ($pos = mb_strpos($class, '\\')) + { + $file = + strtolower(mb_substr($class, 0, $pos)). + '/controllers/'. + ucfirst(mb_substr($class, $pos+1)); + } + else + $file = QFW::$router->cModule.'/controllers/'.$class; + require APPPATH.'/'.$file.'.php'; + return true; + } + + /** * Автолоад некоторых стандартных классов * * <br>Так получилось, что эти классы находятся тут commit c33041e16b4cd4597fd1626528fdd445d18c94a2 Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 4 23:25:05 2010 +0400 Более ранее выставление cMCA - теперь до включения файла с классом diff --git a/QFW/QuickFW/Router.php b/QFW/QuickFW/Router.php index 18bd1f4..4318313 100644 --- a/QFW/QuickFW/Router.php +++ b/QFW/QuickFW/Router.php @@ -399,19 +399,24 @@ SREG; if ($cached) { $MCA = $cached['MCA']; + //устанавливаем переменные роутера + if ($this->module == '') + { + $this->module = $MCA['Module']; + $this->controller = $MCA['Controller']; + $this->action = $MCA['Action']; + $this->type = $MCA['Type']; + } + $this->cModule = $MCA['Module']; + $this->cController = $MCA['Controller']; + $this->cAction = $MCA['Action']; + //составляем путь и загружаем $path = $this->baseDir.'/'.$MCA['Module']; QFW::$view->setScriptPath($path.'/templates'); $class = ucfirst($MCA['Controller']).'Controller'; $fullname = $path . '/controllers/' . strtr($class,'_','/') . '.php'; require_once($fullname); $class_key=$MCA['Module'].'|'.$MCA['Controller']; - if ($this->module == '') - { - $this->cModule = $this->module = $MCA['Module']; - $this->cController = $this->controller = $MCA['Controller']; - $this->cAction = $this->action = $MCA['Action']; - $this->type = $MCA['Type']; - } if (!isset($this->classes[$class_key])) $this->classes[$class_key] = array( 'i' => $MCA['Class'] = new $class, @@ -455,6 +460,9 @@ SREG; $MCA['Controller'] = $cname; $class_key=$MCA['Module'].'|'.$MCA['Controller']; + $this->cModule = $MCA['Module']; + $this->cController = $MCA['Controller']; + if (!isset($this->classes[$class_key])) { require_once($fullname); @@ -516,6 +524,7 @@ SREG; return $MCA; } } + $this->cAction = $MCA['Action']; if (QFW::$config['QFW']['auto404'] && count($data)==$c && $c>0) { // если из URI после модуля ничего не забрали и что-то осталось commit 22a4c29cfc27657a4c0023e0146c97d27e9d805b Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 4 23:20:57 2010 +0400 Восстановление cMCA при ошибке роутера diff --git a/QFW/QuickFW/Router.php b/QFW/QuickFW/Router.php index acecdb0..18bd1f4 100644 --- a/QFW/QuickFW/Router.php +++ b/QFW/QuickFW/Router.php @@ -136,6 +136,12 @@ class QuickFW_Router //Сохраняем старый путь шаблонов $scriptPath = QFW::$view->getScriptPath(); + //Выставляем новые пути вызова и сохраняем старые + list($lpPath, $this->ParentPath, $this->CurPath) = + array($this->ParentPath, $this->CurPath, $MCA['Path']); + //сохраняем прошлый MCA + list ($oModule, $oController, $oAction) = + array($this->cModule, $this->cController, $this->cAction); if ($Uri instanceof Url) $Uri = $Uri->intern(); @@ -163,6 +169,15 @@ class QuickFW_Router if (isset($MCA['Error'])) { + //восстанавливаем MCA + list ($this->cModule, $this->cController, $this->cAction) = + array($oModule, $oController, $oAction); + //восстанавливаем пути вызова + list($this->CurPath, $this->ParentPath) = + array($this->ParentPath, $lpPath); + //Возвращаем путь к шаблонам после вызова + QFW::$view->setScriptPath($scriptPath); + if (QFW::$config['QFW']['release']) return ''; return "Ошибка подключения блока ".$Uri." адрес был разобран в\t\t ". @@ -174,27 +189,14 @@ class QuickFW_Router if ($Params) $MCA['Params'] = array_merge($MCA['Params'], $Params); - //сохраняем пути вызова - list($lpPath, $this->ParentPath, $this->CurPath) = - array($this->ParentPath, $this->CurPath, $MCA['Path']); - - //сохраняем прошлый MCA - list ($oModule, $oController, $oAction) = - array($this->cModule, $this->cController, $this->cAction); - //устанавливаем текущий - list ($this->cModule, $this->cController, $this->cAction) = - array($MCA['Module'], $MCA['Controller'], $MCA['Action']); - $result = call_user_func_array(array($MCA['Class'], $MCA['Action'].$MCA['Type']), $MCA['Params']); //восстанавливаем MCA list ($this->cModule, $this->cController, $this->cAction) = array($oModule, $oController, $oAction); - //восстанавливаем пути вызова list($this->CurPath, $this->ParentPath) = array($this->ParentPath, $lpPath); - //Возвращаем путь к шаблонам после вызова QFW::$view->setScriptPath($scriptPath); commit 5cd62d380b86a8b5204f89d4b1bed70f5edb07c9 Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 4 22:46:51 2010 +0400 Автолоад классов, не поподающих в иерархий файлов diff --git a/QFW/QuickFW/Autoload.php b/QFW/QuickFW/Autoload.php index 92f9772..c6176c6 100644 --- a/QFW/QuickFW/Autoload.php +++ b/QFW/QuickFW/Autoload.php @@ -14,13 +14,37 @@ class Autoload */ static public function Init($function = false) { + spl_autoload_register(array(__CLASS__, 'Bind')); spl_autoload_register(array(__CLASS__, 'Dirs')); if (is_callable($function)) spl_autoload_register($function); } /** - * Функция автолоада + * Автолоад некоторых стандартных классов + * + * <br>Так получилось, что эти классы находятся тут + * + * @param string $class искомый класс + */ + static public function Bind($class) + { + if (empty(self::$classes)) + self::$classes = array( + 'ScafoldController' => LIBPATH.'/Modules/Scafold/ScafoldController.php', + 'QuickFW_Auth' => QFWPATH.'/QuickFW/Auth.php', + ); + if (empty(self::$classes[$class])) + return false; + require self::$classes[$class]; + return true; + } + + /** @var array соответствие классов и файлов */ + static private $classes; + + /** + * Автолоад в директориях * * @param string $class искомый класс */ commit a0b3d2823dea0a5a4c2f2ca62e1eba22b3c1819a Author: Ivan Borzenkov <iva...@li...> Date: Wed Aug 4 22:11:39 2010 +0400 Перенес класс rss diff --git a/lib/Modules/Rss.php b/lib/Rss.php similarity index 100% rename from lib/Modules/Rss.php rename to lib/Rss.php ----------------------------------------------------------------------- Summary of changes: QFW/QuickFW/Autoload.php | 51 ++++++++++++++++++++++++++++++++++++++++++++- QFW/QuickFW/Router.php | 51 +++++++++++++++++++++++++++----------------- lib/{Modules => }/Rss.php | 0 3 files changed, 81 insertions(+), 21 deletions(-) rename lib/{Modules => }/Rss.php (100%) hooks/post-receive -- quickfw |
From: Ivan1986 <iva...@us...> - 2010-08-04 07:46:00
|
This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "quickfw". The branch, master has been updated via 97d4f68175e4d11ec2cb0204f39cfdabf31ba18a (commit) from f1fb8f6edc5300930e14606b77bba0e99c7e6ceb (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 97d4f68175e4d11ec2cb0204f39cfdabf31ba18a Author: Ivan1986 <iva...@li...> Date: Wed Aug 4 11:39:31 2010 +0400 * Добавлены опции в скафолдинг diff --git a/lib/Modules/Scafold/ScafoldController.php b/lib/Modules/Scafold/ScafoldController.php index f1c9cc2..6c31f06 100644 --- a/lib/Modules/Scafold/ScafoldController.php +++ b/lib/Modules/Scafold/ScafoldController.php @@ -38,6 +38,12 @@ abstract class ScafoldController extends Controller /** @var array ссылка на сессию таблицы */ protected $sess = array(); + //Опции + /** @var bool Ссылка добавить внизу страницы */ + protected $addOnBottom = false; + /** @var bool Показывать картинки при сортировке */ + protected $sortImages = false; + /** @var array Массив методов */ private $methods; /** @var boolean Флаг окончания настройки */ @@ -126,6 +132,10 @@ abstract class ScafoldController extends Controller 'actions' => $this->actions, 'table' => str_replace('?_', '', $this->table), 'session' => $this->sess, + 'options' => array( + 'addOnBottom' => $this->addOnBottom, + 'sortImages' => $this->sortImages, + ), )); } diff --git a/lib/Modules/Scafold/scafold/index.html b/lib/Modules/Scafold/scafold/index.html index d5e4354..75b31ca 100644 --- a/lib/Modules/Scafold/scafold/index.html +++ b/lib/Modules/Scafold/scafold/index.html @@ -16,14 +16,16 @@ ?> <th><a href="<?php echo Url::C('sort/'.$key) ?>"><?php echo $i->title ?></a> <?php if (isset($order) && $order['field'] == $key) { ?><span class="scafoldSort"> - <span><?php echo $order['direction']=='ASC' ? '↓' : '↑' ?></span> - <?php /*<img src="/buildin/<?php echo $order['direction']=='ASC' ? 'az' : 'za' ?>.png" - alt="<?php echo $order['direction']=='ASC' ? '↓' : '↑' ?>" />*/?> + <?php if ($options['sortImages']) {?> + <img src="/buildin/<?php echo $order['direction']=='ASC' ? 'az' : 'za' ?>.png" + alt="<?php echo $order['direction']=='ASC' ? '↓' : '↑' ?>" /> + <?php } else { ?> + <span><?php echo $order['direction']=='ASC' ? '↓' : '↑' ?></span> + <?php } ?> </span><?php } ?> </th> <?php } ?> - <th><a href="<?php echo Url::C('edit/-1') ?>">доб.</a></th> - <th> </th> + <th colspan="2"><a href="<?php echo Url::C('edit/-1') ?>">доб.</a></th> <?php if (count($actions)) { ?><th>действия</th><?php } ?> </tr> <?php foreach($data as $id=>$row) { ?> @@ -49,6 +51,7 @@ </tr> <?php } ?> </table> +<?php if ($options['addOnBottom']) {?><a href="<?php echo Url::C('edit/-1') ?>">добавить</a><?php } ?> <?php } else { ?> Записей нет <a href="<?php echo Url::C('edit/-1') ?>">добавить</a> ----------------------------------------------------------------------- Summary of changes: lib/Modules/Scafold/ScafoldController.php | 10 ++++++++++ lib/Modules/Scafold/scafold/index.html | 13 ++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) hooks/post-receive -- quickfw |