1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-24 10:40:48 +03:00

первая выгрузка

This commit is contained in:
Mzhelskiy Maxim 2008-09-21 06:36:57 +00:00
parent c1776d6587
commit 10337a2051
401 changed files with 66615 additions and 0 deletions

4
.htaccess Normal file
View file

@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php

View file

@ -0,0 +1,2 @@
Order Deny,Allow
Deny from all

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,71 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Класс обработки УРЛа вида /comments/
*
*/
class ActionComments extends Action {
public function Init() {
}
protected function RegisterEvent() {
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Для любого евента(тобишь любого УРЛа после /comments/) выводим комментарии
*
*/
protected function EventNotFound() {
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->sCurrentEvent,$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список комментов
*/
$iCount=0;
$aResult=$this->Comment_GetCommentsAll($iCount,$iPage,BLOG_COMMENT_PER_PAGE);
$aComments=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_COMMENT_PER_PAGE,4,DIR_WEB_ROOT.'/comments');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign("aComments",$aComments);
$this->Viewer_AddHtmlTitle('Прямой эфир');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
}
?>

View file

@ -0,0 +1,52 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Класс обработки УРЛа вида /error/ т.е. ошибок
*
*/
class ActionError extends Action {
/**
* Инициализация экшена
*
*/
public function Init() {
$this->SetDefaultEvent('index');
}
/**
* Регистрируем евент
*
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventError');
}
/**
* То что делаем при выполнении евента, т.е. ничего :) просто выводим шаблон
*
*/
protected function EventError() {
/**
* Если у первой ошибки заголовок 404 значит нажно в хидере послать браузеру HTTP/1.1 404 Not Found
*/
$aError=$this->Message_GetError();
if ($aError[0]['title']=='404') {
header("HTTP/1.1 404 Not Found");
}
$this->Viewer_AddHtmlTitle('Ошибка');
}
}
?>

View file

@ -0,0 +1,129 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка главной страницы, т.е. УРЛа вида /index/
*
*/
class ActionIndex extends Action {
/**
* Меню
*
* @var unknown_type
*/
protected $sMenuItemSelect='index';
/**
* Субменю
*
* @var unknown_type
*/
protected $sMenuSubItemSelect='good';
/**
* Число новых топиков
*
* @var unknown_type
*/
protected $iCountTopicsNew=0;
/**
* Число новых топиков в коллективных блогах
*
* @var unknown_type
*/
protected $iCountTopicsCollectiveNew=0;
/**
* Число новых топиков в персональных блогах
*
* @var unknown_type
*/
protected $iCountTopicsPersonalNew=0;
/**
* Инициализация
*
*/
public function Init() {
$this->Viewer_AddBlocksRight(array('comments','tags','blogs'));
/**
* Подсчитываем новые топики
*/
$this->iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew();
$this->iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew();
$this->iCountTopicsNew=$this->iCountTopicsCollectiveNew+$this->iCountTopicsPersonalNew;
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent() {
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Реализация евента - просто показываем шаблон
*
*/
protected function EventNotFound() {
/**
* Меню
*/
$this->sMenuSubItemSelect='good';
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->sCurrentEvent,$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsGood($iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/index');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* При завершении экшена загружаем переменные в шаблон
*
*/
public function EventShutdown() {
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsNew',$this->iCountTopicsNew);
$this->Viewer_Assign('iCountTopicsCollectiveNew',$this->iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew',$this->iCountTopicsPersonalNew);
}
}
?>

View file

@ -0,0 +1,199 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка персональных блогов, т.е. УРла вида /log/
*
*/
class ActionLog extends Action {
/**
* Меню
*
* @var unknown_type
*/
protected $sMenuItemSelect='log';
/**
* Субменю
*
* @var unknown_type
*/
protected $sMenuSubItemSelect='good';
/**
* Инициализация
*
*/
public function Init() {
$this->SetDefaultEvent('good');
/**
* Добавляем блоки для отображения
*/
$this->Viewer_AddBlocksRight(array('comments','tags'));
}
/**
* Регистрируем необходимые евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('good','EventGood');
$this->AddEvent('bad','EventBad');
$this->AddEvent('new','EventNew');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Выводит хорошие топики
*
*/
protected function EventGood() {
/**
* Меню
*/
$this->sMenuSubItemSelect='good';
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->getParam(0),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsPersonalGood($iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/log/good');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Выводит плохие топики
*
*/
protected function EventBad() {
/**
* Меню
*/
$this->sMenuSubItemSelect='bad';
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->getParam(0),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsPersonalBad($iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/log/bad');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Выводит новые топики
*
*/
protected function EventNew() {
/**
* Меню
*/
$this->sMenuSubItemSelect='new';
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->getParam(0),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsPersonalNew($iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/log/bad');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* При завершении экшена загружаем в шаблон необходимые переменные
*
*/
public function EventShutdown() {
/**
* Подсчитываем новые топики
*/
$iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew();
$iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew();
$iCountTopicsNew=$iCountTopicsCollectiveNew+$iCountTopicsPersonalNew;
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsCollectiveNew',$iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew',$iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsNew',$iCountTopicsNew);
}
}
?>

View file

@ -0,0 +1,83 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывые авторизацию
*
*/
class ActionLogin extends Action {
/**
* Инициализация
*
*/
public function Init() {
$this->SetDefaultEvent('index');
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventLogin');
$this->AddEvent('exit','EventExit');
}
/**
* Обрабатываем процесс залогинивания
*
*/
protected function EventLogin() {
/**
* Если нажали кнопку "Войти"
*/
if (isset($_REQUEST['submit_login'])) {
/**
* Проверяем есть ли такой юзер по логину
*/
if ($oUser=$this->User_GetUserByLogin(getRequest('login'))) {
/**
* Сверяем хеши паролей и проверяем активен ли юзер
*/
if ($oUser->getPassword()==func_encrypt(getRequest('password')) and $oUser->getActivate()) {
/**
* Авторизуем
*/
$this->User_Authorization($oUser);
/**
* Перенаправляем на страницу с которой произошла авторизация
*/
$sBackUrl=$_SERVER['HTTP_REFERER'];
if (strpos($sBackUrl,DIR_WEB_ROOT.'/login')===false) {
func_header_location($sBackUrl);
} else {
func_header_location(DIR_WEB_ROOT.'/');
}
}
}
$this->Viewer_Assign('bLoginError',true);
}
$this->Viewer_AddHtmlTitle('Вход на сайт');
}
/**
* Обрабатываем процесс разлогинивания
*
*/
protected function EventExit() {
$this->User_Logout();
$this->Viewer_Assign('bRefreshToHome',true);
}
}
?>

View file

@ -0,0 +1,170 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка УРЛа вида /my/
*
*/
class ActionMy extends Action {
/**
* Логин юзера из УРЛа
*
* @var unknown_type
*/
protected $sUserLogin=null;
/**
* Объект юзера чей профиль мы смотрим
*
* @var unknown_type
*/
protected $oUserProfile=null;
public function Init() {
}
protected function RegisterEvent() {
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Выводит список топиков которые написал юзер
*
* @param unknown_type $sPage
*/
protected function ShowBlog($sPage) {
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$sPage,$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsPersonalByUser($this->oUserProfile->getId(),1,$iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/my/'.$this->oUserProfile->getLogin());
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_AddHtmlTitle('Публикации '.$this->oUserProfile->getLogin());
$this->Viewer_AddHtmlTitle('Блог');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('blog');
}
/**
* Выводит список комментариев которые написал юзер
*
* @param unknown_type $sPage
*/
protected function ShowComment($sPage) {
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$sPage,$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список комментов
*/
$iCount=0;
$aResult=$this->Comment_GetCommentsByUserId($this->oUserProfile->getId(),$iCount,$iPage,BLOG_COMMENT_PER_PAGE);
$aComments=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_COMMENT_PER_PAGE,4,DIR_WEB_ROOT.'/my/'.$this->oUserProfile->getLogin().'/comment');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aComments',$aComments);
$this->Viewer_AddHtmlTitle('Публикации '.$this->oUserProfile->getLogin());
$this->Viewer_AddHtmlTitle('Комментарии');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('comment');
}
/**
* Определяет какой обработчик запустить, т.е. по сути что показать то? :)
*
* @return unknown
*/
protected function EventNotFound() {
/**
* Получаем логин юзера из URL'а
*/
$this->sUserLogin=$this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!$this->sUserLogin or !($this->oUserProfile=$this->User_GetUserByLogin($this->sUserLogin))) {
return parent::EventNotFound();
}
$iCountTopicUser=$this->Topic_GetCountTopicsPersonalByUser($this->oUserProfile->getId(),1);
$iCountCommentUser=$this->Comment_GetCountCommentsByUserId($this->oUserProfile->getId());
$this->Viewer_Assign('oUserProfile',$this->oUserProfile);
$this->Viewer_Assign('iCountTopicUser',$iCountTopicUser);
$this->Viewer_Assign('iCountCommentUser',$iCountCommentUser);
/**
* Для блога
*/
if (is_null($this->getParam(0)) or preg_match("/^page(\d+)$/i",$this->getParam(0))) {
return $this->ShowBlog($this->getParam(0));
}
if ($this->GetParam(0)=='blog') {
if ((is_null($this->getParam(1)) or preg_match("/^page(\d+)$/i",$this->getParam(1)))) {
return $this->ShowBlog($this->getParam(1));
}
}
/**
* Для комментов
*/
if ($this->GetParam(0)=='comment') {
if ((is_null($this->getParam(1)) or preg_match("/^page(\d+)$/i",$this->getParam(1)))) {
return $this->ShowComment($this->getParam(1));
}
}
/**
* Иначе страницу ошибки
*/
return parent::EventNotFound();
}
}
?>

View file

@ -0,0 +1,129 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка новых топиков главной страницы, т.е. УРЛа вида /new/
*
*/
class ActionNew extends Action {
/**
* Меню
*
* @var unknown_type
*/
protected $sMenuItemSelect='index';
/**
* Субменю
*
* @var unknown_type
*/
protected $sMenuSubItemSelect='new';
/**
* Число новых топиков
*
* @var unknown_type
*/
protected $iCountTopicsNew=0;
/**
* Число новых топиков в коллективных блогах
*
* @var unknown_type
*/
protected $iCountTopicsCollectiveNew=0;
/**
* Число новых топиков в персональных блогах
*
* @var unknown_type
*/
protected $iCountTopicsPersonalNew=0;
/**
* Инициализация
*
*/
public function Init() {
$this->Viewer_AddBlocksRight(array('comments','tags','blogs'));
/**
* Подсчитываем новые топики
*/
$this->iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew();
$this->iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew();
$this->iCountTopicsNew=$this->iCountTopicsCollectiveNew+$this->iCountTopicsPersonalNew;
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent() {
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Реализация евента - просто показываем шаблон
*
*/
protected function EventNotFound() {
/**
* Меню
*/
$this->sMenuSubItemSelect='new';
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->sCurrentEvent,$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsNew($iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/new');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* При завершении экшена загружаем переменные в шаблон
*
*/
public function EventShutdown() {
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsNew',$this->iCountTopicsNew);
$this->Viewer_Assign('iCountTopicsCollectiveNew',$this->iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew',$this->iCountTopicsPersonalNew);
}
}
?>

View file

@ -0,0 +1,56 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка статических страниц, здесь пока пусто :)
*
*/
class ActionPage extends Action {
protected $sUserLogin=null;
public function Init() {
$this->SetDefaultEvent('about');
}
protected function RegisterEvent() {
$this->AddEvent('about','EventAbout');
$this->AddEvent('download','EventDownload');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Просто выводим шаблон
*
*/
protected function EventAbout() {
$this->Viewer_AddHtmlTitle('О проекте');
}
/**
* Просто выводим шаблон
*
*/
protected function EventDownload() {
$this->Viewer_AddHtmlTitle('Скачать движок');
}
}
?>

View file

@ -0,0 +1,140 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка статистики юзеров, т.е. УРЛа вида /people/
*
*/
class ActionPeople extends Action {
/**
* Инициализация
*
*/
public function Init() {
$this->SetDefaultEvent('good');
$this->Viewer_AddHtmlTitle('Люди');
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('good','EventGood');
$this->AddEvent('bad','EventBad');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Показываем хороших юзеров
*
*/
protected function EventGood() {
/**
* Получаем статистику
*/
$this->GetStats();
/**
* Получаем хороших юзеров
*/
$this->GetUserRating('good');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Показываем плохих юзеров
*
*/
protected function EventBad() {
/**
* Получаем статистику
*/
$this->GetStats();
/**
* Получаем хороших юзеров
*/
$this->GetUserRating('bad');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Получение статистики
*
*/
protected function GetStats() {
/**
* Последние по визиту на сайт
*/
$aUsersLast=$this->User_GetUsersByDateLast(15);
/**
* Последние по регистрации
*/
$aUsersRegister=$this->User_GetUsersByDateRegister(15);
/**
* Статистика кто, где и т.п.
*/
$aStat=$this->User_GetStatUsers();
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aUsersLast',$aUsersLast);
$this->Viewer_Assign('aUsersRegister',$aUsersRegister);
$this->Viewer_Assign('aStat',$aStat);
}
/**
* Получаем список юзеров
*
* @param unknown_type $sType
*/
protected function GetUserRating($sType) {
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->getParam(0),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список юзеров
*/
$iCount=0;
$aResult=$this->User_GetUsersRating($sType,$iCount,$iPage,USER_PER_PAGE);
$aUsersRating=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,USER_PER_PAGE,4,DIR_WEB_ROOT.'/people/'.$this->sCurrentEvent);
/**
* Загружаем переменные в шаблон
*/
if ($aUsersRating) {
$this->Viewer_Assign('aPaging',$aPaging);
}
$this->Viewer_Assign('aUsersRating',$aUsersRating);
}
}
?>

View file

@ -0,0 +1,200 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывает профайл юзера, т.е. УРЛ вида /profile/login/
*
*/
class ActionProfile extends Action {
/**
* Логин юзера из УРЛа
*
* @var unknown_type
*/
protected $sUserLogin=null;
/**
* Объект юзера чей профиль мы смотрим
*
* @var unknown_type
*/
protected $oUserProfile;
public function Init() {
}
protected function RegisterEvent() {
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Определяет что показать
*
* @return unknown
*/
protected function EventNotFound() {
/**
* Получаем логин из УРЛа
*/
$this->sUserLogin=$this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!$this->sUserLogin or !($this->oUserProfile=$this->User_GetUserByLogin($this->sUserLogin))) {
return parent::EventNotFound();
}
$iCountTopicFavourite=$this->Topic_GetCountTopicsFavouriteByUserId($this->oUserProfile->getId());
$iCountTopicUser=$this->Topic_GetCountTopicsPersonalByUser($this->oUserProfile->getId(),1);
$iCountCommentUser=$this->Comment_GetCountCommentsByUserId($this->oUserProfile->getId());
$this->Viewer_Assign('oUserProfile',$this->oUserProfile);
$this->Viewer_Assign('iCountTopicUser',$iCountTopicUser);
$this->Viewer_Assign('iCountCommentUser',$iCountCommentUser);
$this->Viewer_Assign('iCountTopicFavourite',$iCountTopicFavourite);
/**
* Определяем что запустить
*/
$sParam=$this->GetParam(0);
if ($sParam=='whois' or $sParam=='') {
// инфу профиля
return $this->ShowWhois();
} elseif ($sParam=='favourites') {
// избранное
$this->ShowFavourite();
} elseif ($sParam=='tags') {
// теги
$this->ShowTags();
} else {
return parent::EventNotFound();
}
}
/**
* Выводит список избранноего юзера
*
*/
protected function ShowFavourite() {
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->GetParam(1),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список избранных топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsFavouriteByUserId($this->oUserProfile->getId(),$iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/my/'.$this->oUserProfile->getLogin());
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_AddHtmlTitle('Профиль '.$this->oUserProfile->getLogin());
$this->Viewer_AddHtmlTitle('Избранное');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('favourites');
}
/**
* Показывает инфу профиля
*
*/
protected function ShowWhois() {
/**
* Получаем список друзей
*/
$aUsersFrend=$this->User_GetUsersFrend($this->oUserProfile->getId());
/**
* Получаем список блогов в которых состоит юзер
*/
$aBlogsUser=$this->Blog_GetRelationBlogUsersByUserId($this->oUserProfile->getId());
/**
* Получаем список блогов которые создал юзер
*/
$aBlogsOwner=$this->Blog_GetBlogsByOwnerId($this->oUserProfile->getId());
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogsUser',$aBlogsUser);
$this->Viewer_Assign('aBlogsOwner',$aBlogsOwner);
$this->Viewer_Assign('aUsersFrend',$aUsersFrend);
$this->Viewer_AddHtmlTitle('Профиль '.$this->oUserProfile->getLogin());
$this->Viewer_AddHtmlTitle('Whois');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('whois');
}
/**
* Выводит список тегов котрые использовал юзер при создании топиков
*
*/
protected function ShowTags() {
/**
* Получаем список тегов
*/
$aTags=$this->Topic_GetTopicTagsByUserId($this->oUserProfile->getId(),100);
/**
* Расчитываем логарифмическое облако тегов
*/
if ($aTags) {
$iMinSize=15; // минимальный размер шрифта
$iMaxSize=40; // максимальный размер шрифта
$iSizeRange=$iMaxSize-$iMinSize;
$iMin=10000;
$iMax=0;
foreach ($aTags as $oTag) {
if ($iMax<$oTag->getCount()) {
$iMax=$oTag->getCount();
}
if ($iMin>$oTag->getCount()) {
$iMin=$oTag->getCount();
}
}
$iMinCount=log($iMin+1);
$iMaxCount=log($iMax+1);
$iCountRange=$iMaxCount-$iMinCount;
if ($iCountRange==0) {
$iCountRange=1;
}
foreach ($aTags as $oTag) {
$iTagSize=$iMinSize+(log($oTag->getCount()+1)-$iMinCount)*($iSizeRange/$iCountRange);
$oTag->setSize(round($iTagSize)); // результирующий размер шрифта для тега
}
$this->Viewer_Assign("aTags",$aTags);
}
$this->Viewer_AddHtmlTitle('Профиль '.$this->oUserProfile->getLogin());
$this->Viewer_AddHtmlTitle('Метки');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('tags');
}
}
?>

View file

@ -0,0 +1,248 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывает регистрацию
*
*/
class ActionRegistration extends Action {
/**
* Инициализация
*
* @return unknown
*/
public function Init() {
/**
* Проверяем аторизован ли юзер
*/
if ($this->User_IsAuthorization()) {
$this->Message_AddErrorSingle('Вы уже зарегистрированы у нас и даже авторизованы!','Упс!');
return Router::Action('error');
}
$this->SetDefaultEvent('index');
$this->Viewer_AddHtmlTitle('Регистрация на сайте');
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventIndex');
$this->AddEvent('ok','EventOk');
$this->AddEvent('confirm','EventConfirm');
$this->AddEvent('activate','EventActivate');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Показывает страничку регистрации и обрабатывает её
*
* @return unknown
*/
protected function EventIndex() {
/**
* Если нажали кнопку "Зарегистрироваться"
*/
if (isset($_REQUEST['submit_register'])) {
//Проверяем входные данные
$bError=false;
/**
* Проверка логина
*/
if (!func_check(getRequest('login'),'login',3,30)) {
$this->Message_AddError('Неверный логин, допустим от 3 до 30 символов','Ошибка');
$bError=true;
}
/**
* Проверка мыла
*/
if (!func_check(getRequest('mail'),'mail')) {
$this->Message_AddError('Неверный мыло','Ошибка');
$bError=true;
}
/**
* Проверка пароля
*/
if (!func_check(getRequest('password'),'password',5)) {
$this->Message_AddError('Неверный пароль, допустим от 5 символов','Ошибка');
$bError=true;
} elseif (getRequest('password')!=getRequest('password_confirm')) {
$this->Message_AddError('Пароли не совпадают','Ошибка');
$bError=true;
}
/**
* Проверка капчи(циферки с картинки)
*/
if ($_SESSION['captcha_keystring']!=strtolower(getRequest('captcha'))) {
$this->Message_AddError('Неверный код','Ошибка');
$bError=true;
}
/**
* А не занят ли логин?
*/
if ($this->User_GetUserByLogin(getRequest('login'))) {
$this->Message_AddError('Этот логин уже занять','Ошибка');
$bError=true;
}
/**
* А не занято ли мыло?
*/
if ($this->User_GetUserByMail(getRequest('mail'))) {
$this->Message_AddError('Этот емайл уже занять','Ошибка');
$bError=true;
}
/**
* Если всё то пробуем зарегить
*/
if (!$bError) {
/**
* Создаем юзера
*/
$oUser=new UserEntity_User();
$oUser->setLogin(getRequest('login'));
$oUser->setMail(getRequest('mail'));
$oUser->setPassword(func_encrypt(getRequest('password')));
$oUser->setDateRegister(date("Y-m-d H:i:s"));
$oUser->setIpRegister(func_getIp());
/**
* Если используется активация, то генерим код активации
*/
if (USER_USE_ACTIVATION) {
$oUser->setActivate(0);
$oUser->setActivateKey(md5(func_generator().time()));
} else {
$oUser->setActivate(1);
$oUser->setActivateKey(null);
}
/**
* Регистрируем
*/
if ($this->User_Add($oUser)) {
/**
* Создаем персональный блог
*/
$this->Blog_CreatePersonalBlog($oUser);
/**
* Если стоит регистрация с активацией то проводим её
*/
if (USER_USE_ACTIVATION) {
/**
* Отправляем на мыло письмо о подтверждении регистрации
* По хорошему тескт письма нужно вынести в отдельный шаблон
*/
$this->Mail_SetAdress($oUser->getMail());
$this->Mail_SetSubject(SITE_NAME.': регистрация');
$this->Mail_SetBody('
Вы зарегистрировались на сайте <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a><br>
Ваши регистрационные данные:<br>
&nbsp;&nbsp;&nbsp;логин: <b>'.$oUser->getLogin().'</b><br>
&nbsp;&nbsp;&nbsp;пароль: <b>'.getRequest('password').'</b><br>
<br>
Для завершения регистрации вам необходимо активировать аккаунт пройдя по ссылке:
<a href="'.DIR_WEB_ROOT.'/registration/activate/'.$oUser->getActivateKey().'/">'.DIR_WEB_ROOT.'/registration/activate/'.$oUser->getActivateKey().'/</a>
<br>
<br>
С уважением, администрация сайта <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a>
');
$this->Mail_setHTML();
$this->Mail_Send();
func_header_location(DIR_WEB_ROOT.'/registration/confirm/');
} else {
$this->Mail_SetAdress($oUser->getMail());
$this->Mail_SetSubject(SITE_NAME.': регистрация');
$this->Mail_SetBody('
Вы зарегистрировались на сайте <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a><br>
Ваши регистрационные данные:<br>
&nbsp;&nbsp;&nbsp;логин: <b>'.$oUser->getLogin().'</b><br>
&nbsp;&nbsp;&nbsp;пароль: <b>'.getRequest('password').'</b><br>
<br>
С уважением, администрация сайта <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a>
');
$this->Mail_setHTML();
$this->Mail_Send();
}
func_header_location(DIR_WEB_ROOT.'/registration/ok/');
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки при регистрации, пожалуйста повторите регистрацию позже.','Внутреняя ошибка');
return Router::Action('error');
}
}
}
}
/**
* Обрабатывает активацию аккаунта
*
* @return unknown
*/
protected function EventActivate() {
$bError=false;
/**
* Проверяет передан ли код активации
*/
$sActivateKey=$this->GetParam(0);
if (!func_check($sActivateKey,'md5')) {
$bError=true;
}
/**
* Проверяет верный ли код активации
*/
if (!($oUser=$this->User_GetUserByActivateKey($sActivateKey))) {
$bError=true;
}
/**
* Если что то не то
*/
if ($bError) {
$this->Message_AddErrorSingle('Неверный код активации!','Ошибка');
return Router::Action('error');
}
/**
* Активируем
*/
$oUser->setActivate(1);
$oUser->setDateActivate(date("Y-m-d H:i:s"));
/**
* Сохраняем юзера
*/
if ($this->User_Update($oUser)) {
return;
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки при активации, пожалуйста повторите активацию позже.','Внутреняя ошибка');
return Router::Action('error');
}
}
/**
* Просто выводит шаблон
*
*/
protected function EventOk() {
}
/**
* Просто выводит шаблон
*
*/
protected function EventConfirm() {
}
}
?>

View file

@ -0,0 +1,221 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывает настройки профила юзера
*
*/
class ActionSettings extends Action {
/**
* Текущий юзер
*
* @var unknown_type
*/
protected $oUserCurrent=null;
/**
* Инициализация
*
* @return unknown
*/
public function Init() {
/**
* Проверяем авторизован ли юзер
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle('Настройки профиля для вас не доступны','Нет доступа');
return Router::Action('error');
}
/**
* Получаем текущего юзера
*/
$this->oUserCurrent=$this->User_GetUserCurrent();
$this->SetDefaultEvent('profile');
$this->Viewer_AddHtmlTitle('Настройки профиля');
}
protected function RegisterEvent() {
$this->AddEvent('profile','EventProfile');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Выводит форму для редактирования профиля и обрабатывает её
*
*/
protected function EventProfile() {
/**
* Если нажали кнопку "Сохранить"
*/
if (isset($_REQUEST['submit_profile_edit'])) {
$bError=false;
/**
* Заполняем профиль из полей формы
*/
/**
* Проверяем имя
*/
if (func_check(getRequest('profile_name'),'text',2,20)) {
$this->oUserCurrent->setProfileName(getRequest('profile_name'));
} else {
$this->oUserCurrent->setProfileName(null);
}
/**
* Проверяем пол
*/
if (in_array(getRequest('profile_sex'),array('man','woman','other'))) {
$this->oUserCurrent->setProfileSex(getRequest('profile_sex'));
} else {
$this->oUserCurrent->setProfileSex('other');
}
/**
* Проверяем дату рождения
*/
if (func_check(getRequest('profile_birthday_day'),'id',1,2) and func_check(getRequest('profile_birthday_month'),'id',1,2) and func_check(getRequest('profile_birthday_year'),'id',4,4)) {
$this->oUserCurrent->setProfileBirthday(date("Y-m-d H:i:s",mktime(0,0,0,getRequest('profile_birthday_month'),getRequest('profile_birthday_day'),getRequest('profile_birthday_year'))));
} else {
$this->oUserCurrent->setProfileBirthday(null);
}
/**
* Проверяем страну
*/
if (func_check(getRequest('profile_country'),'text',1,30)) {
$this->oUserCurrent->setProfileCountry(getRequest('profile_country'));
} else {
$this->oUserCurrent->setProfileCountry(null);
}
/**
* Проверяем регион
*/
if (func_check(getRequest('profile_region'),'text',1,30)) {
$this->oUserCurrent->setProfileRegion(getRequest('profile_region'));
} else {
$this->oUserCurrent->setProfileRegion(null);
}
/**
* Проверяем город
*/
if (func_check(getRequest('profile_city'),'text',1,30)) {
$this->oUserCurrent->setProfileCity(getRequest('profile_city'));
} else {
$this->oUserCurrent->setProfileCity(null);
}
/**
* Проверяем ICQ
*/
if (func_check(getRequest('profile_icq'),'id',4,15)) {
$this->oUserCurrent->setProfileIcq(getRequest('profile_icq'));
} else {
$this->oUserCurrent->setProfileIcq(null);
}
/**
* Проверяем сайт
*/
if (func_check(getRequest('profile_site'),'text',3,200)) {
$this->oUserCurrent->setProfileSite(getRequest('profile_site'));
} else {
$this->oUserCurrent->setProfileSite(null);
}
/**
* Проверяем название сайта
*/
if (func_check(getRequest('profile_site_name'),'text',3,50)) {
$this->oUserCurrent->setProfileSiteName(getRequest('profile_site_name'));
} else {
$this->oUserCurrent->setProfileSiteName(null);
}
/**
* Проверяем информацию о себе
*/
if (func_check(getRequest('profile_about'),'text',1,3000)) {
$this->oUserCurrent->setProfileAbout(getRequest('profile_about'));
} else {
$this->oUserCurrent->setProfileAbout(null);
}
/**
* Проверка на смену пароля
*/
if (getRequest('password','')!='') {
if (func_check(getRequest('password'),'password',5)) {
if (getRequest('password')==getRequest('password_confirm')) {
if (func_encrypt(getRequest('password_now'))==$this->oUserCurrent->getPassword()) {
$this->oUserCurrent->setPassword(func_encrypt(getRequest('password')));
} else {
$bError=true;
$this->Message_AddError('Неверный текущий пароль','Ошибка');
}
} else {
$bError=true;
$this->Message_AddError('Пароли не совпадают','Ошибка');
}
} else {
$bError=true;
$this->Message_AddError('Неверный пароль, допустим от 5 символов','Ошибка');
}
}
/**
* Загрузка аватара, делаем ресайзы
*/
if (is_uploaded_file($_FILES['avatar']['tmp_name'])) {
$sFileTmp=$_FILES['avatar']['tmp_name'];
if ($sFileAvatar=func_img_resize($sFileTmp,DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId(),'avatar_100x100',3000,3000,100,100)) {
func_img_resize($sFileTmp,DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId(),'avatar_64x64',3000,3000,64,64);
func_img_resize($sFileTmp,DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId(),'avatar_48x48',3000,3000,48,48);
func_img_resize($sFileTmp,DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId(),'avatar_24x24',3000,3000,24,24);
func_img_resize($sFileTmp,DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId(),'avatar',3000,3000);
$this->oUserCurrent->setProfileAvatar(1);
$aFileInfo=pathinfo($sFileAvatar);
$this->oUserCurrent->setProfileAvatarType($aFileInfo['extension']);
} else {
$bError=true;
$this->Message_AddError('Не удалось загрузить аватар','Ошибка');
}
}
/**
* Удалить аватара
*/
if (isset($_REQUEST['avatar_delete'])) {
$this->oUserCurrent->setProfileAvatar(0);
@unlink(DIR_SERVER_ROOT.DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId().'/avatar_100x100.'.$this->oUserCurrent->getProfileAvatarType());
@unlink(DIR_SERVER_ROOT.DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId().'/avatar_64x64.'.$this->oUserCurrent->getProfileAvatarType());
@unlink(DIR_SERVER_ROOT.DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId().'/avatar_48x48.'.$this->oUserCurrent->getProfileAvatarType());
@unlink(DIR_SERVER_ROOT.DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId().'/avatar_24x24.'.$this->oUserCurrent->getProfileAvatarType());
@unlink(DIR_SERVER_ROOT.DIR_UPLOADS_IMAGES.'/'.$this->oUserCurrent->getId().'/avatar.'.$this->oUserCurrent->getProfileAvatarType());
}
/**
* Ставим дату последнего изменения профиля
*/
$this->oUserCurrent->setProfileDate(date("Y-m-d H:i:s"));
/**
* Сохраняем изменения профиля
*/
if (!$bError) {
if ($this->User_Update($this->oUserCurrent)) {
$this->Message_AddNoticeSingle('Профиль успешно сохранён','Ура');
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки, пожалуйста повторите позже.','Внутреняя ошибка');
}
}
}
}
}
?>

View file

@ -0,0 +1,84 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывает поиск по тегам
*
*/
class ActionTag extends Action {
/**
* Инициализация
*
*/
public function Init() {
/**
* Определяем какие блоки выводить
*/
$this->Viewer_AddBlocksRight(array('tags','comments'));
}
protected function RegisterEvent() {
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Отображение топиков
*
*/
protected function EventNotFound() {
/**
* Получаем тег из УРЛа
*/
$sTag=urldecode($this->sCurrentEvent);
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->getParam(0),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsByTag($sTag,$iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/tag/'.htmlspecialchars($sTag));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('sTag',$sTag);
$this->Viewer_AddHtmlTitle('Поиск по тегам');
$this->Viewer_AddHtmlTitle($sTag);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
}
?>

View file

@ -0,0 +1,329 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывает разговоры(почту)
*
*/
class ActionTalk extends Action {
/**
* Текущий юзер
*
* @var unknown_type
*/
protected $oUserCurrent=null;
/**
* Массив ID юзеров адресатов
*
* @var unknown_type
*/
protected $aUsersId=array();
/**
* Инициализация
*
* @return unknown
*/
public function Init() {
/**
* Проверяем авторизован ли юзер
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle('Почта для вас не доступна, необходимо авторизоваться','Нет доступа');
return Router::Action('error');
}
/**
* Получаем текущего юзера
*/
$this->oUserCurrent=$this->User_GetUserCurrent();
$this->SetDefaultEvent('inbox');
$this->Viewer_AddHtmlTitle('Почта');
}
protected function RegisterEvent() {
$this->AddEvent('inbox','EventInbox');
$this->AddEvent('add','EventAdd');
$this->AddEvent('read','EventRead');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
protected function EventInbox() {
/**
* Обработка удаления сообщений
*/
if (isset($_REQUEST['submit_talk_del'])) {
$aTalksIdDel=getRequest('talk_del');
if (is_array($aTalksIdDel)) {
foreach ($aTalksIdDel as $sTalkId => $value) {
if ($oTalkUser=$this->Talk_GetTalkUser($sTalkId,$this->oUserCurrent->getId())) {
$this->Talk_DeleteTalkUser($oTalkUser);
}
}
}
}
/**
* Получаем список сообщений
*/
$aTalks=$this->Talk_GetTalksByUserId($this->oUserCurrent->getId());
$this->Viewer_Assign('aTalks',$aTalks);
}
protected function EventAdd() {
$this->Viewer_AddHtmlTitle('Создание сообщения');
/**
* Проверяем отправлена ли форма с данными
*/
if (!isset($_REQUEST['submit_talk_add'])) {
return false;
}
/**
* Проверка корректности полей формы
*/
if (!$this->checkTalkFields()) {
return false;
}
/**
* Теперь можно смело добавлять
*/
$oTalk=new TalkEntity_Talk();
$oTalk->setUserId($this->oUserCurrent->getId());
$oTalk->setTitle(getRequest('talk_title'));
/**
* Парсим на предмет ХТМЛ тегов
*/
$sText=$this->Text_Parser(getRequest('talk_text'));
$oTalk->setText($sText);
$oTalk->setDate(date("Y-m-d H:i:s"));
$oTalk->setUserIp(func_getIp());
/**
* Добавляем
*/
if ($oTalk=$this->Talk_AddTalk($oTalk)) {
/**
* Тут добавляем всех читателей этого сообщения(автора сообщения также добавляем, т.к. он читатель собственной мессаги :) )
*/
$this->aUsersId[]=$this->oUserCurrent->getId();
foreach ($this->aUsersId as $iUserId) {
$oTalkUser=new TalkEntity_TalkUser();
$oTalkUser->setTalkId($oTalk->getId());
$oTalkUser->setUserId($iUserId);
$oTalkUser->setDateLast(null);
$this->Talk_AddTalkUser($oTalkUser);
/**
* Отправляем уведомления
*/
if ($iUserId!=$this->oUserCurrent->getId()) {
$oUserToMail=$this->User_GetUserById($iUserId);
$this->Mail_SetAdress($oUserToMail->getMail(),$oUserToMail->getLogin());
$this->Mail_SetSubject(SITE_NAME.': у вас новое письмо');
$this->Mail_SetBody('
Вам пришло новое письмо, прочитать и ответить на него можно перейдя по <a href="'.DIR_WEB_ROOT.'/talk/read/'.$oTalk->getId().'/">этой ссылке</a><br>
Тема письма: <b>'.htmlspecialchars($oTalk->getTitle()).'</b><br>
Не забудьте предварительно авторизоваться!<br>
<br>
С уважением, администрация сайта <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a>
');
$this->Mail_setHTML();
$this->Mail_Send();
}
}
func_header_location(DIR_WEB_ROOT.'/talk/read/'.$oTalk->getId().'/');
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки, пожалуйста повторите позже.','Внутреняя ошибка');
return Router::Action('error');
}
}
protected function EventRead() {
/**
* Получаем номер сообщения из УРЛ и проверяем существует ли оно
*/
$sTalkId=$this->GetParam(0);
if (!$oTalk=$this->Talk_GetTalkByIdAndUserId($sTalkId,$this->oUserCurrent->getId())) {
return parent::EventNotFound();
}
/**
* Помечаем дату последнего просмотра
*/
$this->Talk_SetTalkUserDateLast($oTalk->getId(),$this->oUserCurrent->getId());
/**
* Обрабатываем добавление коммента
*/
$this->SubmitComment($oTalk);
/**
* Достаём комменты к сообщению
*/
$aComments=$this->Talk_GetCommentsByTalkId($oTalk->getId());
$this->Viewer_AddHtmlTitle($oTalk->getTitle());
$this->Viewer_Assign('oTalk',$oTalk);
$this->Viewer_Assign('aComments',$aComments);
}
protected function checkTalkFields() {
$bOk=true;
/**
* Проверяем есть ли заголовок
*/
if (!func_check(getRequest('talk_title'),'text',2,200)) {
$this->Message_AddError('Заголовок сообщения должен быть от 2 до 200 символов','Ошибка');
$bOk=false;
}
/**
* Проверяем есть ли содержание топика
*/
if (!func_check(getRequest('talk_text'),'text',2,3000)) {
$this->Message_AddError('Текст сообщения должен быть от 2 до 3000 символов','Ошибка');
$bOk=false;
}
/**
* проверяем адресатов
*/
$sUsers=getRequest('talk_users');
$aUsers=explode(',',$sUsers);
$aUsersNew=array();
$this->aUsersId=array();
foreach ($aUsers as $sUser) {
$sUser=trim($sUser);
if ($sUser=='' or strtolower($sUser)==strtolower($this->oUserCurrent->getLogin())) {
continue;
}
if ($oUser=$this->User_GetUserByLogin($sUser) and $oUser->getActivate()==1) {
$this->aUsersId[]=$oUser->getId();
} else {
$this->Message_AddError('У нас нет пользователя с логином «'.htmlspecialchars($sUser).'»','Ошибка');
$bOk=false;
}
$aUsersNew[]=$sUser;
}
if (!count($aUsersNew)) {
$this->Message_AddError('Необходимо указать кому вы хотите отправить сообщение','Ошибка');
$_REQUEST['talk_users']='';
$bOk=false;
} else {
$_REQUEST['talk_users']=join(',',$aUsersNew);
}
//$bOk=false;
return $bOk;
}
/**
* Обработка добавление комментария к сообщению
*
* @param unknown_type $oTalk
* @return unknown
*/
protected function SubmitComment($oTalk) {
/**
* Если нажали кнопку "Отправить"
*/
if (isset($_REQUEST['submit_comment'])) {
/**
* Проверяем текст комментария
*/
if (!func_check(getRequest('comment_text'),'text',2,3000)) {
$this->Message_AddError('Текст комментария должен быть от 2 до 3000 символов','Ошибка');
return false;
}
/**
* Проверям на какой коммент отвечаем
*/
$sParentId=getRequest('reply',0);
if (!func_check($sParentId,'id')) {
$this->Message_AddError('Что то не так..','Ошибка');
return false;
}
if ($sParentId!=0) {
/**
* Проверяем существует ли комментарий на который отвечаем
*/
if (!($oCommentParent=$this->Talk_GetCommentById($sParentId))) {
return false;
}
/**
* Проверяем из одного сообщения ли новый коммент и тот на который отвечаем
*/
if ($oCommentParent->getTalkId()!=$oTalk->getId()) {
return false;
}
} else {
/**
* Корневой комментарий
*/
$sParentId=null;
}
/**
* Создаём коммент
*/
$oCommentNew=new TalkEntity_TalkComment();
$oCommentNew->setTalkId($oTalk->getId());
$oCommentNew->setUserId($this->oUserCurrent->getId());
/**
* Парсим коммент на предмет ХТМЛ тегов
*/
$sText=$this->Text_Parser(getRequest('comment_text'));
$oCommentNew->setText($sText);
$oCommentNew->setDate(date("Y-m-d H:i:s"));
$oCommentNew->setUserIp(func_getIp());
$oCommentNew->setPid($sParentId);
/**
* Добавляем коммент
*/
if ($this->Talk_AddComment($oCommentNew)) {
/**
* Отсылаем уведомления всем адресатам
*/
$aUsersTalk=$this->Talk_GetTalkUsers($oCommentNew->getTalkId());
foreach ($aUsersTalk as $oUserTalk) {
if ($oUserTalk->getId()!=$oCommentNew->getUserId()) {
$this->Mail_SetAdress($oUserTalk->getMail(),$oUserTalk->getLogin());
$this->Mail_SetSubject(SITE_NAME.': у вас новый комментарий к письму');
$this->Mail_SetBody('
Получен новый комментарий на письмо <b>«'.htmlspecialchars($oTalk->getTitle()).'»</b>, прочитать его можно перейдя по <a href="'.DIR_WEB_ROOT.'/talk/read/'.$oTalk->getId().'/#comment'.$oCommentNew->getId().'">этой ссылке</a><br>
Не забудьте предварительно авторизоваться!<br>
<br>
С уважением, администрация сайта <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a>
');
$this->Mail_setHTML();
$this->Mail_Send();
}
}
func_header_location(DIR_WEB_ROOT.'/talk/read/'.$oTalk->getId().'/#comment'.$oCommentNew->getId());
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки при добавлении комментария, пожалуйста повторите позже.','Внутреняя ошибка');
return false;
}
}
}
}
?>

View file

@ -0,0 +1,181 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывает ТОПы
*
*/
class ActionTop extends Action {
/**
* Меню
*
* @var unknown_type
*/
protected $sMenuItemSelect='top';
/**
* Субменю
*
* @var unknown_type
*/
protected $sMenuSubItemSelect='blog';
/**
* Инициализация
*
*/
public function Init() {
$this->SetDefaultEvent('topic');
$this->Viewer_AddHtmlTitle('Рейтинг');
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent() {
$this->AddEvent('blog','EventBlog');
$this->AddEvent('topic','EventTopic');
$this->AddEvent('comment','EventComment');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Выводит ТОП блогов
*
*/
protected function EventBlog() {
/**
* Меню
*/
$this->sMenuSubItemSelect='blog';
/**
* Получаем список блогов
*/
$aBlogs=$this->Blog_GetBlogsRating(20);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogs',$aBlogs);
$this->Viewer_AddHtmlTitle('Блоги');
}
protected function EventTopic() {
/**
* Меню
*/
$this->sMenuSubItemSelect='topic';
/**
* Определяем период ТОПа
*/
$iTimeDelta=$this->GetTimeDelta();
$sDate=date("Y-m-d H:00:00",time()-$iTimeDelta);
/**
* Получаем список топиков
*/
$aTopics=$this->Topic_GetTopicsRatingByDate($sDate,20);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_AddHtmlTitle('Топики');
}
protected function EventComment() {
/**
* Меню
*/
$this->sMenuSubItemSelect='comment';
/**
* Определяем период ТОПа
*/
$iTimeDelta=$this->GetTimeDelta();
$sDate=date("Y-m-d H:00:00",time()-$iTimeDelta);
/**
* Получаем список комментов
*/
$aComments=$this->Comment_GetCommentsRatingByDate($sDate,20);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aComments',$aComments);
$this->Viewer_AddHtmlTitle('Комментарии');
}
/**
* Переводит параметр в нужный период времени
*
* @return unknown
*/
protected function GetTimeDelta() {
$aDateParam=$this->GetParam(0);
switch ($aDateParam) {
case 'all':
/**
* за последние 100 лет :)
*/
$iTimeDelta=60*60*24*350*100;
break;
case '30d':
/**
* за последние 30 дней
*/
$iTimeDelta=60*60*24*30;
break;
case '7d':
/**
* за последние 7 дней
*/
$iTimeDelta=60*60*24*7;
break;
case '24h':
/**
* за последние 24 часа
*/
$iTimeDelta=60*60*24*1;
break;
default:
$iTimeDelta=60*60*24*7;
$this->SetParam(0,'7d');
break;
}
return $iTimeDelta;
}
/**
* После завершшения экшена загружаем переменные
*
*/
public function EventShutdown() {
/**
* Получаем список новых топиков
*/
$iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew();
$iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew();
$iCountTopicsNew=$iCountTopicsCollectiveNew+$iCountTopicsPersonalNew;
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsCollectiveNew',$iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew',$iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsNew',$iCountTopicsNew);
}
}
?>

View file

@ -0,0 +1,497 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка УРЛа вида /topic/ - управление своими топиками
*
*/
class ActionTopic extends Action {
/**
* Меню
*
* @var unknown_type
*/
protected $sMenuItemSelect='topic';
/**
* СубМеню
*
* @var unknown_type
*/
protected $sMenuSubItemSelect='add';
/**
* Текущий юзер
*
* @var unknown_type
*/
protected $oUserCurrent=null;
/**
* Инициализация
*
* @return unknown
*/
public function Init() {
/**
* Проверяем авторизован ли юзер
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle('Для того чтобы что то написать, сначало нужно войти под своим аккаунтом.','Нет доступа');
return Router::Action('error');
}
$this->oUserCurrent=$this->User_GetUserCurrent();
$this->SetDefaultEvent('add');
$this->Viewer_AddHtmlTitle('Топики');
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('add','EventAdd');
$this->AddEvent('saved','EventSaved');
$this->AddEvent('published','EventPublished');
$this->AddEvent('edit','EventEdit');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Редактирование топика
*
* @return unknown
*/
protected function EventEdit() {
/**
* Меню
*/
$this->sMenuSubItemSelect='saved';
$this->sMenuItemSelect='';
/**
* Получаем номер топика из УРЛ и проверяем существует ли он
*/
$sTopicId=$this->GetParam(0);
if (!$oTopic=$this->Topic_GetTopicById($sTopicId,$this->oUserCurrent)) {
return parent::EventNotFound();
}
/**
* проверяем кто владелец топика
*/
if ($oTopic->getUserId()!=$this->oUserCurrent->getId()) {
return parent::EventNotFound();
}
/**
* Добавляем блок вывода информации о блоге
*/
$this->Viewer_AddBlocksRight(array('actions/'.$this->GetActionClass().'/blog_info.tpl'));
/**
* Получаем данные для отображения формы
*/
$aBlogsOwner=$this->Blog_GetBlogsByOwnerId($this->oUserCurrent->getId());
$aBlogsUser=$this->Blog_GetRelationBlogUsersByUserId($this->oUserCurrent->getId());
$aAllowBlogsUser=array();
foreach ($aBlogsUser as $oBlogUser) {
$oBlog=$this->Blog_GetBlogById($oBlogUser->getBlogId());
// делаем через "or" чтоб дать возможность юзеру отредактировать свой топик в блоге в котором он уже не может постить, т.е. для тех топиков что были запощены раньше и был доступ в блог
if ($this->ACL_CanAddTopic($this->oUserCurrent,$oBlog) or $oTopic->getBlogId()==$oBlog->getId()) {
$aAllowBlogsUser[]=$oBlogUser;
}
}
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogsUser',$aAllowBlogsUser);
$this->Viewer_Assign('aBlogsOwner',$aBlogsOwner);
$this->Viewer_AddHtmlTitle('Редактирование топика');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('add');
/**
* Проверяем отправлена ли форма с данными(хотяб одна кнопка)
*/
if (isset($_REQUEST['submit_topic_publish']) or isset($_REQUEST['submit_topic_save'])) {
/**
* Обрабатываем отправку формы
*/
return $this->SubmitEdit($oTopic);
} else {
/**
* Заполняем поля формы для редактирования
* Только перед отправкой формы!
*/
$_REQUEST['topic_title']=$oTopic->getTitle();
$_REQUEST['topic_text']=$oTopic->getTextSource();
$_REQUEST['topic_tags']=$oTopic->getTags();
$_REQUEST['blog_id']=$oTopic->getBlogId();
$_REQUEST['topic_id']=$oTopic->getId();
}
}
/**
* Добавление топика
*
* @return unknown
*/
protected function EventAdd() {
/**
* Меню
*/
$this->sMenuSubItemSelect='add';
/**
* Добавляем блок вывода информации о блоге
*/
$this->Viewer_AddBlocksRight(array('actions/'.$this->GetActionClass().'/blog_info.tpl'));
/**
* Получаем данные для отображения формы
*/
$aBlogsOwner=$this->Blog_GetBlogsByOwnerId($this->oUserCurrent->getId());
$aBlogsUser=$this->Blog_GetRelationBlogUsersByUserId($this->oUserCurrent->getId());
$aAllowBlogsUser=array();
foreach ($aBlogsUser as $oBlogUser) {
$oBlog=$this->Blog_GetBlogById($oBlogUser->getBlogId());
if ($this->ACL_CanAddTopic($this->oUserCurrent,$oBlog)) {
$aAllowBlogsUser[]=$oBlogUser;
}
}
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogsUser',$aAllowBlogsUser);
$this->Viewer_Assign('aBlogsOwner',$aBlogsOwner);
$this->Viewer_AddHtmlTitle('Добавление топика');
/**
* Обрабатываем отправку формы
*/
return $this->SubmitAdd();
}
/**
* Выводит список сохранёных топиков
*
*/
protected function EventSaved() {
/**
* Меню
*/
$this->sMenuSubItemSelect='saved';
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->getParam(0),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsPersonalByUser($this->oUserCurrent->getId(),0,$iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/topic/saved');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_AddHtmlTitle('Сохранённые');
}
/**
* Выводит список опубликованых топиков
*
*/
protected function EventPublished() {
/**
* Меню
*/
$this->sMenuSubItemSelect='published';
/**
* Передан ли номер страницы
*/
if (preg_match("/^page(\d+)$/i",$this->getParam(0),$aMatch)) {
$iPage=$aMatch[1];
} else {
$iPage=1;
}
/**
* Получаем список топиков
*/
$iCount=0;
$aResult=$this->Topic_GetTopicsPersonalByUser($this->oUserCurrent->getId(),1,$iCount,$iPage,BLOG_TOPIC_PER_PAGE);
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,BLOG_TOPIC_PER_PAGE,4,DIR_WEB_ROOT.'/topic/published');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_AddHtmlTitle('Опубликованные');
}
/**
* Обработка добавлени топика
*
* @return unknown
*/
protected function SubmitAdd() {
/**
* Проверяем отправлена ли форма с данными(хотяб одна кнопка)
*/
if (!isset($_REQUEST['submit_topic_publish']) and !isset($_REQUEST['submit_topic_save'])) {
return false;
}
/**
* Проверка корректности полей формы
*/
if (!$this->checkTopicFields()) {
return false;
}
/**
* Определяем в какой блог делаем запись
*/
$iBlogId=getRequest('blog_id');
if ($iBlogId==0) {
$oBlog=$this->Blog_GetPersonalBlogByUser($this->oUserCurrent);
} else {
$oBlog=$this->Blog_GetBlogById($iBlogId);
}
/**
* Если блог не определен выдаем предупреждение
*/
if (!$oBlog) {
$this->Message_AddErrorSingle('Пытаетесь запостить топик в неизвестный блог?','Ошибка');
return false;
}
/**
* Проверка состоит ли юзер в блоге в который постит
*/
if (!$this->Blog_GetRelationBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId())) {
if ($oBlog->getOwnerId()!=$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle('Вы не сотоите в этом блоге!','Ошибка');
return false;
}
}
/**
* Проверяем есть ли права на постинг топика в этот блог
*/
if (!$this->ACL_CanAddTopic($this->User_GetUserCurrent(),$oBlog)) {
$this->Message_AddErrorSingle('Вы еще не достаточно окрепли чтобы постить в этот блог','Ошибка');
return false;
}
/**
* Теперь можно смело добавлять топик к блогу
*/
$oTopic=new TopicEntity_Topic();
$oTopic->setBlogId($oBlog->getId());
$oTopic->setUserId($this->oUserCurrent->getId());
$oTopic->setType('topic');
$oTopic->setTitle(getRequest('topic_title'));
/**
* Парсим на предмет ХТМЛ тегов
*/
$sText=$this->Text_Parser(getRequest('topic_text'));
/**
* Создаёт анонс топика(обрезаем по тег <cut>)
*/
$sTestShort=$sText;
$sTextTemp=str_replace("\r\n",'[<n>]',$sText);
if (preg_match("/^(.*)<cut>(.*)$/i",$sTextTemp,$aMatch)) {
$sTestShort=$aMatch[1];
}
$sTestShort=str_replace('[<n>]',"\r\n",$sTestShort);
$oTopic->setText($sText);
$oTopic->setTextShort($sTestShort);
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setDateAdd(date("Y-m-d H:i:s"));
$oTopic->setUserIp(func_getIp());
/**
* Публикуем или сохраняем
*/
if (isset($_REQUEST['submit_topic_publish'])) {
$oTopic->setPublish(1);
} else {
$oTopic->setPublish(0);
}
/**
* Добавляем топик
*/
if ($this->Topic_AddTopic($oTopic)) {
func_header_location(DIR_WEB_ROOT.'/blog/'.$oTopic->getId().'.html');
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки при добавлении топика, пожалуйста повторите позже.','Внутреняя ошибка');
return Router::Action('error');
}
}
/**
* Обработка редактирования топика
*
* @param unknown_type $oTopic
* @return unknown
*/
protected function SubmitEdit($oTopic) {
/**
* Проверка корректности полей формы
*/
if (!$this->checkTopicFields()) {
return false;
}
/**
* Определяем в какой блог делаем запись
*/
$iBlogId=getRequest('blog_id');
if ($iBlogId==0) {
$oBlog=$this->Blog_GetPersonalBlogByUser($this->oUserCurrent);
} else {
$oBlog=$this->Blog_GetBlogById($iBlogId);
}
/**
* Если блог не определен выдаем предупреждение
*/
if (!$oBlog) {
$this->Message_AddErrorSingle('Пытаетесь запостить топик в неизвестный блог?','Ошибка');
return false;
}
/**
* Проверка состоит ли юзер в блоге в который постит
* Если нужно разрешить редактировать топик в блоге в котором юзер уже не стоит
*/
if (!$this->Blog_GetRelationBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId())) {
if ($oBlog->getOwnerId()!=$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle('Вы не сотоите в этом блоге!','Ошибка');
return false;
}
}
/**
* Проверяем есть ли права на постинг топика в этот блог
* Условие $oBlog->getId()!=$oTopic->getBlogId() для того чтоб разрешить отредактировать топик в блоге в который сейчас юзер не имеет права на постинг, но раньше успел в него запостить этот топик
*/
if (!$this->ACL_CanAddTopic($this->User_GetUserCurrent(),$oBlog) and $oBlog->getId()!=$oTopic->getBlogId()) {
$this->Message_AddErrorSingle('Вы еще не достаточно окрепли чтобы постить в этот блог','Ошибка');
return false;
}
/**
* Теперь можно смело редактировать топик
*/
$oTopic->setBlogId($oBlog->getId());
$oTopic->setTitle(getRequest('topic_title'));
/**
* Парсим на предмет ХТМЛ тегов
*/
$sText=$this->Text_Parser(getRequest('topic_text'));
$sTestShort=$sText;
$sTextTemp=str_replace("\r\n",'[<n>]',$sText);
if (preg_match("/^(.*)<cut>(.*)$/i",$sTextTemp,$aMatch)) {
$sTestShort=$aMatch[1];
}
$sTestShort=str_replace('[<n>]',"\r\n",$sTestShort);
$oTopic->setText($sText);
$oTopic->setTextShort($sTestShort);
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setUserIp(func_getIp());
/**
* Публикуем или сохраняем в черновиках
*/
if (isset($_REQUEST['submit_topic_publish'])) {
$oTopic->setPublish(1);
} else {
$oTopic->setPublish(0);
}
/**
* Сохраняем топик
*/
if ($this->Topic_UpdateTopic($oTopic)) {
func_header_location(DIR_WEB_ROOT.'/blog/'.$oTopic->getId().'.html');
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки при изменении топика, пожалуйста повторите позже.','Внутреняя ошибка');
return Router::Action('error');
}
}
/**
* Проверка полей формы
*
* @return unknown
*/
protected function checkTopicFields() {
$bOk=true;
/**
* Проверяем есть ли блог в кторый постим
*/
if (!func_check(getRequest('blog_id'),'id')) {
$this->Message_AddError('Что то не то с блогом..','Ошибка');
$bOk=false;
}
/**
* Проверяем есть ли заголовок топика
*/
if (!func_check(getRequest('topic_title'),'text',2,200)) {
$this->Message_AddError('Название топика должно быть от 2 до 200 символов','Ошибка');
$bOk=false;
}
/**
* Проверяем есть ли содержание топика
*/
if (!func_check(getRequest('topic_text'),'text',2,3000)) {
$this->Message_AddError('Текст топика должен быть от 2 до 3000 символов','Ошибка');
$bOk=false;
}
/**
* Проверяем есть ли теги(метки)
*/
if (!func_check(getRequest('topic_tags'),'text',2,500)) {
$this->Message_AddError('Метки топика должны быть от 2 до 50 символов с общей диной не более 500 символов','Ошибка');
$bOk=false;
}
/**
* проверяем ввод тегов
*/
$sTags=getRequest('topic_tags');
$aTags=explode(',',$sTags);
$aTagsNew=array();
foreach ($aTags as $sTag) {
$sTag=trim($sTag);
if (func_check($sTag,'text',2,50)) {
$aTagsNew[]=$sTag;
}
}
if (!count($aTagsNew)) {
$this->Message_AddError('Проверьте правильность меток','Ошибка');
$bOk=false;
} else {
$_REQUEST['topic_tags']=join(',',$aTagsNew);
}
return $bOk;
}
/**
* При завершении экшена загружаем необходимые переменные
*
*/
public function EventShutdown() {
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
}
}
?>

2
classes/blocks/.htaccess Normal file
View file

@ -0,0 +1,2 @@
Order Deny,Allow
Deny from all

View file

@ -0,0 +1,34 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка блока с рейтингом блогов
*
*/
class BlockBlogs extends Block {
public function Exec() {
/**
* Получаем список блогов
*/
$aBlogs=$this->Blog_GetBlogsRating(20);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign("aBlogs",$aBlogs);
}
}
?>

View file

@ -0,0 +1,34 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обработка блока с комментариями
*
*/
class BlockComments extends Block {
public function Exec() {
/**
* Получаем список комментов
*/
$aComments=$this->oEngine->Comment_GetCommentsAllGroup(20);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign("aComments",$aComments);
}
}
?>

View file

@ -0,0 +1,65 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Обрабатывает блок облака тегов
*
*/
class BlockTags extends Block {
public function Exec() {
/**
* Получаем список тегов
*/
$aTags=$this->oEngine->Topic_GetTopicTags(70);
//dump($aTags);
/**
* Расчитываем логарифмическое облако тегов
*/
if ($aTags) {
$iMinSize=12; // минимальный размер шрифта
$iMaxSize=22; // максимальный размер шрифта
$iSizeRange=$iMaxSize-$iMinSize;
$iMin=10000;
$iMax=0;
foreach ($aTags as $oTag) {
if ($iMax<$oTag->getCount()) {
$iMax=$oTag->getCount();
}
if ($iMin>$oTag->getCount()) {
$iMin=$oTag->getCount();
}
}
$iMinCount=log($iMin+1);
$iMaxCount=log($iMax+1);
$iCountRange=$iMaxCount-$iMinCount;
if ($iCountRange==0) {
$iCountRange=1;
}
foreach ($aTags as $oTag) {
$iTagSize=$iMinSize+(log($oTag->getCount()+1)-$iMinCount)*($iSizeRange/$iCountRange);
$oTag->setSize(round($iTagSize)); // результирующий размер шрифта для тега
}
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aTags",$aTags);
}
}
}
?>

2
classes/engine/.htaccess Normal file
View file

@ -0,0 +1,2 @@
Order Deny,Allow
Deny from all

View file

@ -0,0 +1,208 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Абстрактный класс экшена
*
*/
abstract class Action extends Object {
protected $aRegisterEvent=array();
protected $aParams=array();
protected $oEngine=null;
protected $sActionTemplate=null;
protected $sDefaultEvent=null;
protected $sCurrentEvent=null;
protected $sCurrentAction=null;
/**
* Конструктор
*
* @param Engine $oEngine
* @param string $sAction
*/
public function __construct(Engine $oEngine, $sAction) {
$this->RegisterEvent();
$this->oEngine=$oEngine;
$this->sCurrentAction=$sAction;
$this->aParams=Router::GetParams();
}
/**
* Добавляет евент в экшен
*
* @param string $sEventName Название евента
* @param string $sEventFunction Какой метод ему соответствует
*/
protected function AddEvent($sEventName,$sEventFunction) {
$sEventName=strtolower($sEventName);
if (!isset($this->aRegisterEvent[$sEventName])) {
if (method_exists($this,$sEventFunction)) {
$this->aRegisterEvent[$sEventName]=$sEventFunction;
} else {
throw new Exception("Добавляемый метод евента не найден: ".$sEventFunction);
}
}
}
/**
* Запускает евент на выполнение
* Если текущий евент не определен то запускается тот которые определен по умолчанию(default event)
*
* @return unknown
*/
public function ExecEvent() {
$this->sCurrentEvent=Router::GetActionEvent();
if ($this->sCurrentEvent==null) {
$this->sCurrentEvent=$this->GetDefaultEvent();
Router::SetActionEvent($this->sCurrentEvent);
}
if (isset($this->aRegisterEvent[$this->sCurrentEvent])) {
$sCmd='$result=$this->'.$this->aRegisterEvent[$this->sCurrentEvent].'();';
eval($sCmd);
return $result;
} else {
return $this->EventNotFound();
}
}
/**
* Устанавливает евент по умолчанию
*
* @param string $sEvent
*/
public function SetDefaultEvent($sEvent) {
$this->sDefaultEvent=$sEvent;
}
/**
* Получает евент по умолчанию
*
* @return string
*/
public function GetDefaultEvent() {
return $this->sDefaultEvent;
}
/**
* Получает параметр из URL по его номеру, если его нет то null
*
* @param unknown_type $iOffset
* @return unknown
*/
public function GetParam($iOffset) {
$iOffset=(int)$iOffset;
return isset($this->aParams[$iOffset]) ? $this->aParams[$iOffset] : null;
}
/**
* Установить значение параметра(эмуляция параметра в URL).
* После установки занова считывает параметры из роутера - для корректной работы
*
* @param int $iOffset - по идеи может быть не только числом
* @param unknown_type $value
*/
public function SetParam($iOffset,$value) {
Router::SetParam($iOffset,$value);
$this->aParams=Router::GetParams();
}
/**
* Устанавливает какой шаблон выводить
*
* @param string $sTemplate Путь до шаблона относительно общего каталога шаблонов
*/
protected function SetTemplate($sTemplate) {
$this->sActionTemplate=$sTemplate;
}
/**
* Устанавливает какой шаблон выводить
*
* @param string $sTemplate Путь до шаблона относительно каталога шаблонов экшена
*/
protected function SetTemplateAction($sTemplate) {
$this->sActionTemplate='actions/'.$this->GetActionClass().'/'.$sTemplate.'.tpl';
}
/**
* Получить шаблон
* Если шаблон не определен то возвращаем дефолтный шаблон евента: action/{Action}.{event}.tpl
*
* @return unknown
*/
public function GetTemplate() {
if (is_null($this->sActionTemplate)) {
$this->sActionTemplate='actions/'.$this->GetActionClass().'/'.$this->sCurrentEvent.'.tpl';
}
return $this->sActionTemplate;
}
/**
* Получить каталог с шаблонами экшена(совпадает с именем класса)
*
* @return unknown
*/
public function GetActionClass() {
return Router::GetActionClass();
}
/**
* Вызывается в том случаи если не найден евент который запросили через URL
* По дефолту происходит перекидывание на страницу ошибки, это можно переопределить в наследнике, а в ряде случаев и необходимо :) Для примера смотри экшен Profile
*
* @return unknown
*/
protected function EventNotFound() {
$this->Message_AddErrorSingle('К сожалению, такой страницы не существует. Вероятно, она была удалена с сервера, либо ее здесь никогда не было.','404');
return Router::Action('error');
}
/**
* Выполняется при завершение экшена, после вызова основного евента
*
*/
public function EventShutdown() {
}
/**
* Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
*
* @param string $sName
* @param array $aArgs
* @return unknown
*/
public function __call($sName,$aArgs) {
return $this->oEngine->_CallModule($sName,$aArgs);
}
/**
* Абстрактный метод инициализации экшена
*
*/
abstract public function Init();
/**
* Абстрактный метод регистрации евентов.
* В нём необходимо вызывать метод AddEvent($sEventName,$sEventFunction)
*
*/
abstract protected function RegisterEvent();
}
?>

View file

@ -0,0 +1,36 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Абстрактный класс блока
* Это те блоки которые обрабатывают шаблоны Smarty перед выводом(например блок "Облако тегов")
*
*/
abstract class Block extends Object {
protected $oEngine=null;
public function __construct() {
$this->oEngine=Engine::getInstance();
}
public function __call($sName,$aArgs) {
return $this->oEngine->_CallModule($sName,$aArgs);
}
abstract public function Exec();
}
?>

View file

@ -0,0 +1,208 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Основной класс движка, который позволяет напрямую обращаться к любому модулю
*
*/
class Engine extends Object {
static protected $oInstance=null;
protected $aModules=array();
protected $aConfigModule;
public $iTimeLoadModule=0;
/**
* При создании объекта делаем инициализацию
*
*/
protected function __construct() {
$this->Init();
}
/**
* Ограничиваем объект только одним экземпляром
*
* @return Engine
*/
static public function getInstance() {
if (isset(self::$oInstance) and (self::$oInstance instanceof self)) {
return self::$oInstance;
} else {
self::$oInstance= new self();
return self::$oInstance;
}
}
/**
* Инициализация
*
*/
protected function Init() {
$this->LoadModules();
}
/**
* Производит инициализацию всех модулей
*
*/
public function InitModules() {
foreach ($this->aModules as $oModule) {
$oModule->Init();
}
}
/**
* Завершаем работу всех модулей
*
*/
public function ShutdownModules() {
foreach ($this->aModules as $sKey => $oModule) {
$oModule->Shutdown();
}
}
/**
* Выполняет загрузку модуля по его названию
*
* @param string $sModuleName
* @param bool $bInit - инициализировать модуль или нет
* @return unknown
*/
protected function LoadModule($sModuleName,$bInit=false) {
$tm1=microtime(true);
if (file_exists("./classes/modules/".strtolower($sModuleName)."/".$sModuleName.".class.php")) {
require_once("./classes/modules/".strtolower($sModuleName)."/".$sModuleName.".class.php");
} elseif (file_exists("./classes/modules/sys_".strtolower($sModuleName)."/".$sModuleName.".class.php")) {
require_once("./classes/modules/sys_".strtolower($sModuleName)."/".$sModuleName.".class.php");
} else {
throw new Exception("Не найден класс модуля - ".$sModuleName);
}
$oModule=new $sModuleName($this);
if ($bInit) {
$oModule->Init();
}
$this->aModules[$sModuleName]=$oModule;
$tm2=microtime(true);
$this->iTimeLoadModule+=$tm2-$tm1;
dump("load $sModuleName - \t\t".($tm2-$tm1)."");
return $oModule;
}
/**
* Загружает все используемые модули и передает им в конструктор ядро
*
*/
protected function LoadModules() {
$this->aConfigModule=include("./config/config.module.php");
foreach ($this->aConfigModule['autoLoad'] as $sModuleName) {
$this->LoadModule($sModuleName);
}
}
/**
* Вызывает метод нужного модуля
*
* @param string $sName
* @param array $aArgs
* @return unknown
*/
public function _CallModule($sName,$aArgs) {
$sArgs='';
$aStrArgs=array();
foreach ($aArgs as $sKey => $arg) {
$aStrArgs[]='$aArgs['.$sKey.']';
}
$sArgs=join(',',$aStrArgs);
$aName=explode("_",$sName);
$sModuleName=$aName[0];
if (isset($this->aModules[$sModuleName])) {
$oModule=$this->aModules[$sModuleName];
} else {
$oModule=$this->LoadModule($sModuleName,true);
}
$sCmd='$result=$oModule->'.$aName[1].'('.$sArgs.');';
eval($sCmd);
return $result;
/*
$sCmd='$bExists=isset($this->MOD_'.$sModuleName.');';
eval($sCmd);
if ($bExists) {
$sCmd='$bExists=method_exists($this->MOD_'.$sModuleName.',"'.$aName[1].'");';
eval($sCmd);
if ($bExists) {
$sCmd='$result=$this->MOD_'.$sModuleName.'->'.$aName[1].'('.$sArgs.');';
eval($sCmd);
return $result;
}
throw new Exception('В модуле '.$sModuleName.' нет метода '.$aName[1].'()');
} else {
throw new Exception("Не найден модуль: ".$sModuleName);
}
*/
return false;
}
/**
* Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
*
* @param string $sName
* @param array $aArgs
* @return unknown
*/
public function __call($sName,$aArgs) {
return $this->_CallModule($sName,$aArgs);
}
/**
* Блокируем копирование/клонирование объекта роутинга
*
*/
protected function __clone() {
}
}
/**
* Автозагрузка кслассов
*
* @param unknown_type $sClassName
*/
function __autoload($sClassName) {
/**
* Если класс подходит под шблон класса сущности то згружаем его
*/
if (preg_match("/^(\w+)Entity\_(\w+)$/i",$sClassName,$aMatch)) {
$tm1=microtime(true);
$sFileClass='classes/modules/'.strtolower($aMatch[1]).'/entity/'.$aMatch[2].'.entity.class.php';
if (file_exists($sFileClass)) {
require_once($sFileClass);
$tm2=microtime(true);
dump($sClassName." - \t\t".($tm2-$tm1));
}
}
}
?>

View file

@ -0,0 +1,52 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Абстрактный класс сущности
*
*/
abstract class Entity extends Object {
protected $_aData=array();
/**
* Если передать в конструктор ассоциативный массив свойств и их значений, то они автоматом загрузятся в сущность
*
* @param unknown_type $aParam
*/
public function __construct($aParam = false) {
if(is_array($aParam)) {
foreach ($aParam as $sKey => $val) {
$this->_aData[$sKey] = $val;
}
}
}
/**
* При попытке вызвать неопределенный метод сущности возвращаем null
* В принципе можно это закомментить чтоб отлавливать ошибки при обращении к несуществующим методам :)
*
* @param string $sName
* @param array $aArgs
* @return unknown
*/
/*
public function __call($sName,$aArgs) {
return null;
}
*/
}
?>

View file

@ -0,0 +1,35 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Абстрактный класс мапера
*
*/
abstract class Mapper extends Object {
protected $oDb;
/**
* Сохраняем коннект к БД
*
* @param DbSimple_Generic_Database $oDb
*/
public function __construct(DbSimple_Generic_Database $oDb) {
$this->oDb = $oDb;
}
}
?>

View file

@ -0,0 +1,62 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Абстракция модуля, от которой наследуются все модули
*
*/
abstract class Module extends Object {
protected $oEngine=null;
final public function __construct(Engine $oEngine) {
$this->oEngine=$oEngine;
}
/**
* Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
*
* @param string $sName
* @param array $aArgs
* @return unknown
*/
public function __call($sName,$aArgs) {
return $this->oEngine->_CallModule($sName,$aArgs);
}
/**
* Блокируем копирование/клонирование объекта роутинга
*
*/
protected function __clone() {
}
/**
* Абстрактный метод инициализации модуля, должен быть переопределен в модуле
*
*/
abstract public function Init();
/**
* Метод срабатывает после отработки цепочки экшенов(action)
*
*/
public function Shutdown() {
}
}
?>

View file

@ -0,0 +1,25 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* От этого класса наследуются все остальные
*
*/
abstract class Object {
}
?>

View file

@ -0,0 +1,262 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Класс роутинга(контроллера)
* Инициализирует ядро, определяет какой экшен запустить согласно URL'у и запускает его.
*/
set_include_path(get_include_path().PATH_SEPARATOR.dirname(__FILE__));
require_once("Object.class.php");
require_once("Action.class.php");
require_once("Block.class.php");
require_once("Module.class.php");
require_once("Engine.class.php");
require_once("Entity.class.php");
require_once("Mapper.class.php");
class Router extends Object {
protected $aConfigRoute=array();
static protected $sAction=null;
static protected $sActionEvent=null;
static protected $sActionClass=null;
static protected $aParams=array();
protected $oAction=null;
protected $oEngine=null;
static protected $oInstance=null;
/**
* Делает возможным только один экземпляр этого класса
*
* @return Router
*/
static public function getInstance() {
if (isset(self::$oInstance) and (self::$oInstance instanceof self)) {
return self::$oInstance;
} else {
self::$oInstance= new self();
return self::$oInstance;
}
}
/**
* В конструкторе парсим URL
* Пример: http://site.ru/action/event/param1/param2/ на выходе получим:
* self::$sAction='action';
* self::$sActionEvent='event';
* self::$aParams=array('param1','param2');
*
*/
protected function __construct() {
//Конфиг роутинга, содержит соответствия URL и классов экшенов
$this->aConfigRoute=include("./config/config.route.php");
if (get_magic_quotes_gpc()) {
func_stripslashes($_REQUEST);
}
$sReq=preg_replace("/\/+/",'/',$_SERVER['REQUEST_URI']);
$sReq=preg_replace("/^\/(.*)\/?$/U",'\\1',$sReq);
$aRequestUrl = ($sReq=='') ? array() : explode('/',$sReq);
for ($i=0;$i<SYS_OFFSET_REQUEST_URL;$i++) {
array_shift($aRequestUrl);
}
self::$sAction=array_shift($aRequestUrl);
self::$sActionEvent=array_shift($aRequestUrl);
self::$aParams=$aRequestUrl;
}
/**
* Запускает весь процесс :)
*
*/
public function Exec() {
$this->oEngine=Engine::getInstance();
$this->oEngine->InitModules();
$this->ExecAction();
$this->AssignVars();
$this->Viewer_VarAssign();
/**
* тут такое дело: модуль Viewer сначала шатдаунится а потом выполняет метод дисплей
*/
$this->oEngine->ShutdownModules();
$this->Viewer_Display($this->oAction->GetTemplate());
}
public function getStats() {
return array('sql'=>$this->Database_GetStats(),'cache'=>$this->Cache_GetStats(),'engine'=>array('time_load_module'=>round($this->oEngine->iTimeLoadModule,3)));
}
/**
* Загружает в шаблонизатор Smarty необходимые переменные
*
*/
protected function AssignVars() {
$this->Viewer_Assign('sAction',self::$sAction);
$this->Viewer_Assign('sEvent',self::$sActionEvent);
$this->Viewer_Assign('aParams',self::$aParams);
}
/**
* Запускает на выполнение экшен
* Может запускаться рекурсивно если в одном экшене стоит переадресация на другой
*
*/
public function ExecAction() {
$sActionClass=$this->DefineActionClass();
require_once('./classes/actions/'.$sActionClass.'.class.php');
$this->oAction=new $sActionClass($this->oEngine,self::$sAction);
if ($this->oAction->Init()==='next') {
$this->ExecAction();
} else {
$res=$this->oAction->ExecEvent();
$this->oAction->EventShutdown();
if ($res==='next') {
$this->ExecAction();
}
}
}
/**
* Определяет какой класс соответствует текущему экшену
*
* @return string
*/
protected function DefineActionClass() {
if (isset($this->aConfigRoute['page'][self::$sAction])) {
} elseif (self::$sAction===null) {
self::$sAction=$this->aConfigRoute['config']['action_default'];
} else {
//Если не находим нужного класса то отправляем на страницу ошибки
$this->Message_AddError('К сожалению, такой страницы не существует. Вероятно, она была удалена с сервера, либо ее здесь никогда не было.','404');
self::$sAction=$this->aConfigRoute['config']['action_not_found'];
}
self::$sActionClass=$this->aConfigRoute['page'][self::$sAction];
return self::$sActionClass;
}
/**
* Функция переадресации на другой экшен
* Если ею завершить евент в экшене то запуститься новый экшен
* Пример: return Router::Action('error');
*
* @param string $sAction
* @param string $sEvent
* @param array $aParams
* @return 'next'
*/
static public function Action($sAction,$sEvent=null,$aParams=null) {
self::$sAction=$sAction;
self::$sActionEvent=$sEvent;
if (is_array($aParams)) {
self::$aParams=$aParams;
}
return 'next';
}
/**
* Получить текущий экшен
*
* @return string
*/
static public function GetAction() {
return self::$sAction;
}
/**
* Получить текущий евент
*
* @return string
*/
static public function GetActionEvent() {
return self::$sActionEvent;
}
/**
* Получить класс текущего экшена
*
* @return string
*/
static public function GetActionClass() {
return self::$sActionClass;
}
/**
* Установить новый текущий евент
*
* @param string $sEvent
*/
static public function SetActionEvent($sEvent) {
self::$sActionEvent=$sEvent;
}
/**
* Получить параметры(те которые передаются в URL)
*
* @return array
*/
static public function GetParams() {
return self::$aParams;
}
/**
* Получить параметр по номеру, если его нет то возвращается null
*
* @param int $iOffset
* @return string
*/
static public function GetParam($iOffset) {
$iOffset=(int)$iOffset;
return isset(self::$aParams[$iOffset]) ? self::$aParams[$iOffset] : null;
}
/**
* Установить значение параметра
*
* @param int $iOffset - по идеи может быть не только числом
* @param unknown_type $value
*/
static public function SetParam($iOffset,$value) {
self::$aParams[$iOffset]=$value;
}
/**
* Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
*
* @param string $sName
* @param array $aArgs
* @return unknown
*/
public function __call($sName,$aArgs) {
return $this->oEngine->_CallModule($sName,$aArgs);
}
/**
* Блокируем копирование/клонирование объекта роутинга
*
*/
protected function __clone() {
}
}
?>

1361
classes/lib/external/DbSimple/Generic.php vendored Normal file

File diff suppressed because it is too large Load diff

290
classes/lib/external/DbSimple/Ibase.php vendored Normal file
View file

@ -0,0 +1,290 @@
<?php
/**
* DbSimple_Ibase: Interbase/Firebird database.
* (C) Dk Lab, http://en.dklab.ru
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* See http://www.gnu.org/copyleft/lesser.html
*
* Placeholders are emulated because of logging purposes.
*
* @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 $
*/
require_once dirname(__FILE__) . '/Generic.php';
/**
* Best transaction parameters for script queries.
* They never give us update conflicts (unlike others)!
* Used by default.
*/
define('IBASE_BEST_TRANSACTION', IBASE_COMMITTED + IBASE_WAIT + IBASE_REC_VERSION);
define('IBASE_BEST_FETCH', IBASE_UNIXTIME);
/**
* Database class for Interbase/Firebird.
*/
class DbSimple_Ibase extends DbSimple_Generic_Database
{
var $DbSimple_Ibase_BEST_TRANSACTION = IBASE_BEST_TRANSACTION;
var $DbSimple_Ibase_USE_NATIVE_PHOLDERS = true;
var $fetchFlags = IBASE_BEST_FETCH;
var $link;
var $trans;
var $prepareCache = array();
/**
* constructor(string $dsn)
* Connect to Interbase/Firebird.
*/
function DbSimple_Ibase($dsn)
{
$p = DbSimple_Generic::parseDSN($dsn);
if (!is_callable('ibase_connect')) {
return $this->_setLastError("-1", "Interbase/Firebird extension is not loaded", "ibase_connect");
}
$ok = $this->link = ibase_connect(
$p['host'] . (empty($p['port'])? "" : ":".$p['port']) .':'.preg_replace('{^/}s', '', $p['path']),
$p['user'],
$p['pass'],
isset($p['CHARSET']) ? $p['CHARSET'] : 'win1251',
isset($p['BUFFERS']) ? $p['BUFFERS'] : 0,
isset($p['DIALECT']) ? $p['DIALECT'] : 3,
isset($p['ROLE']) ? $p['ROLE'] : ''
);
if (isset($p['TRANSACTION'])) $this->DbSimple_Ibase_BEST_TRANSACTION = eval($p['TRANSACTION'].";");
$this->_resetLastError();
if (!$ok) return $this->_setDbError('ibase_connect()');
}
function _performEscape($s, $isIdent=false)
{
if (!$isIdent)
return "'" . str_replace("'", "''", $s) . "'";
else
return '"' . str_replace('"', '_', $s) . '"';
}
function _performTransaction($parameters=null)
{
if ($parameters === null) $parameters = $this->DbSimple_Ibase_BEST_TRANSACTION;
$this->trans = @ibase_trans($parameters, $this->link);
}
function& _performNewBlob($blobid=null)
{
$obj =& new DbSimple_Ibase_Blob($this, $blobid);
return $obj;
}
function _performGetBlobFieldNames($result)
{
$blobFields = array();
for ($i=ibase_num_fields($result)-1; $i>=0; $i--) {
$info = ibase_field_info($result, $i);
if ($info['type'] === "BLOB") $blobFields[] = $info['name'];
}
return $blobFields;
}
function _performGetPlaceholderIgnoreRe()
{
return '
" (?> [^"\\\\]+|\\\\"|\\\\)* " |
\' (?> [^\'\\\\]+|\\\\\'|\\\\)* \' |
` (?> [^`]+ | ``)* ` | # backticks
/\* .*? \*/ # comments
';
}
function _performCommit()
{
if (!is_resource($this->trans)) return false;
$result = @ibase_commit($this->trans);
if (true === $result) {
$this->trans = null;
}
return $result;
}
function _performRollback()
{
if (!is_resource($this->trans)) return false;
$result = @ibase_rollback($this->trans);
if (true === $result) {
$this->trans = null;
}
return $result;
}
function _performTransformQuery(&$queryMain, $how)
{
// If we also need to calculate total number of found rows...
switch ($how) {
// Prepare total calculation (if possible)
case 'CALC_TOTAL':
// Not possible
return true;
// Perform total calculation.
case 'GET_TOTAL':
// TODO: GROUP BY ... -> COUNT(DISTINCT ...)
$re = '/^
(?> -- [^\r\n]* | \s+)*
(\s* SELECT \s+) #1
((?:FIRST \s+ \S+ \s+ (?:SKIP \s+ \S+ \s+)? )?) #2
(.*?) #3
(\s+ FROM \s+ .*?) #4
((?:\s+ ORDER \s+ BY \s+ .*)?) #5
$/six';
$m = null;
if (preg_match($re, $queryMain[0], $m)) {
$queryMain[0] = $m[1] . $this->_fieldList2Count($m[3]) . " AS C" . $m[4];
$skipHead = substr_count($m[2], '?');
if ($skipHead) array_splice($queryMain, 1, $skipHead);
$skipTail = substr_count($m[5], '?');
if ($skipTail) array_splice($queryMain, -$skipTail);
}
return true;
}
return false;
}
function _performQuery($queryMain)
{
$this->_lastQuery = $queryMain;
$this->_expandPlaceholders($queryMain, $this->DbSimple_Ibase_USE_NATIVE_PHOLDERS);
$hash = $queryMain[0];
if (!isset($this->prepareCache[$hash])) {
$this->prepareCache[$hash] = @ibase_prepare((is_resource($this->trans) ? $this->trans : $this->link), $queryMain[0]);
} else {
// Prepare cache hit!
}
$prepared = $this->prepareCache[$hash];
if (!$prepared) return $this->_setDbError($queryMain[0]);
$queryMain[0] = $prepared;
$result = @call_user_func_array('ibase_execute', $queryMain);
// ATTENTION!!!
// WE MUST save prepared ID (stored in $prepared variable) somewhere
// before returning $result because of ibase destructor. Now it is done
// by $this->prepareCache. When variable $prepared goes out of scope, it
// is destroyed, and memory for result also freed by PHP. Totally we
// got "Invalud statement handle" error message.
if ($result === false) return $this->_setDbError($queryMain[0]);
if (!is_resource($result)) {
// Non-SELECT queries return number of affected rows, SELECT - resource.
return @ibase_affected_rows((is_resource($this->trans) ? $this->trans : $this->link));
}
return $result;
}
function _performFetch($result)
{
// Select fetch mode.
$flags = $this->fetchFlags;
if (empty($this->attributes['BLOB_OBJ'])) $flags = $flags | IBASE_TEXT;
else $flags = $flags & ~IBASE_TEXT;
$row = @ibase_fetch_assoc($result, $flags);
if (ibase_errmsg()) return $this->_setDbError($this->_lastQuery);
if ($row === false) return null;
return $row;
}
function _setDbError($query)
{
return $this->_setLastError(ibase_errcode(), ibase_errmsg(), $query);
}
}
class DbSimple_Ibase_Blob extends DbSimple_Generic_Blob
{
var $blob; // resourse link
var $id;
var $database;
function DbSimple_Ibase_Blob(&$database, $id=null)
{
$this->database =& $database;
$this->id = $id;
$this->blob = null;
}
function read($len)
{
if ($this->id === false) return ''; // wr-only blob
if (!($e=$this->_firstUse())) return $e;
$data = @ibase_blob_get($this->blob, $len);
if ($data === false) return $this->_setDbError('read');
return $data;
}
function write($data)
{
if (!($e=$this->_firstUse())) return $e;
$ok = @ibase_blob_add($this->blob, $data);
if ($ok === false) return $this->_setDbError('add data to');
return true;
}
function close()
{
if (!($e=$this->_firstUse())) return $e;
if ($this->blob) {
$id = @ibase_blob_close($this->blob);
if ($id === false) return $this->_setDbError('close');
$this->blob = null;
} else {
$id = null;
}
return $this->id ? $this->id : $id;
}
function length()
{
if ($this->id === false) return 0; // wr-only blob
if (!($e=$this->_firstUse())) return $e;
$info = @ibase_blob_info($this->id);
if (!$info) return $this->_setDbError('get length of');
return $info[0];
}
function _setDbError($query)
{
$hId = $this->id === null ? "null" : ($this->id === false ? "false" : $this->id);
$query = "-- $query BLOB $hId";
$this->database->_setDbError($query);
}
// Called on each blob use (reading or writing).
function _firstUse()
{
// BLOB is opened - nothing to do.
if (is_resource($this->blob)) return true;
// Open or create blob.
if ($this->id !== null) {
$this->blob = @ibase_blob_open($this->id);
if ($this->blob === false) return $this->_setDbError('open');
} else {
$this->blob = @ibase_blob_create($this->database->link);
if ($this->blob === false) return $this->_setDbError('create');
}
return true;
}
}
?>

227
classes/lib/external/DbSimple/Mysql.php vendored Normal file
View file

@ -0,0 +1,227 @@
<?php
/**
* DbSimple_Mysql: MySQL database.
* (C) Dk Lab, http://en.dklab.ru
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* See http://www.gnu.org/copyleft/lesser.html
*
* Placeholders end blobs are emulated.
*
* @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
* @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/
*
* @version 2.x $Id: Mysql.php 163 2007-01-10 09:47:49Z dk $
*/
require_once dirname(__FILE__) . '/Generic.php';
/**
* Database class for MySQL.
*/
class DbSimple_Mysql extends DbSimple_Generic_Database
{
var $link;
/**
* constructor(string $dsn)
* Connect to MySQL.
*/
function DbSimple_Mysql($dsn)
{
$p = DbSimple_Generic::parseDSN($dsn);
if (!is_callable('mysql_connect')) {
return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect");
}
$ok = $this->link = @mysql_connect(
$p['host'] . (empty($p['port'])? "" : ":".$p['port']),
$p['user'],
$p['pass'],
true
);
$this->_resetLastError();
if (!$ok) return $this->_setDbError('mysql_connect()');
$ok = @mysql_select_db(preg_replace('{^/}s', '', $p['path']), $this->link);
if (!$ok) return $this->_setDbError('mysql_select_db()');
}
function _performEscape($s, $isIdent=false)
{
if (!$isIdent) {
return "'" . mysql_real_escape_string($s, $this->link) . "'";
} else {
return "`" . str_replace('`', '``', $s) . "`";
}
}
function _performTransaction($parameters=null)
{
return $this->query('BEGIN');
}
function& _performNewBlob($blobid=null)
{
$obj =& new DbSimple_Mysql_Blob($this, $blobid);
return $obj;
}
function _performGetBlobFieldNames($result)
{
$blobFields = array();
for ($i=mysql_num_fields($result)-1; $i>=0; $i--) {
$type = mysql_field_type($result, $i);
if (strpos($type, "BLOB") !== false) $blobFields[] = mysql_field_name($result, $i);
}
return $blobFields;
}
function _performGetPlaceholderIgnoreRe()
{
return '
" (?> [^"\\\\]+|\\\\"|\\\\)* " |
\' (?> [^\'\\\\]+|\\\\\'|\\\\)* \' |
` (?> [^`]+ | ``)* ` | # backticks
/\* .*? \*/ # comments
';
}
function _performCommit()
{
return $this->query('COMMIT');
}
function _performRollback()
{
return $this->query('ROLLBACK');
}
function _performTransformQuery(&$queryMain, $how)
{
// If we also need to calculate total number of found rows...
switch ($how) {
// Prepare total calculation (if possible)
case 'CALC_TOTAL':
$m = null;
if (preg_match('/^(\s* SELECT)(.*)/six', $queryMain[0], $m)) {
if ($this->_calcFoundRowsAvailable()) {
$queryMain[0] = $m[1] . ' SQL_CALC_FOUND_ROWS' . $m[2];
}
}
return true;
// Perform total calculation.
case 'GET_TOTAL':
// Built-in calculation available?
if ($this->_calcFoundRowsAvailable()) {
$queryMain = array('SELECT FOUND_ROWS()');
}
// Else use manual calculation.
// TODO: GROUP BY ... -> COUNT(DISTINCT ...)
$re = '/^
(?> -- [^\r\n]* | \s+)*
(\s* SELECT \s+) #1
(.*?) #2
(\s+ FROM \s+ .*?) #3
((?:\s+ ORDER \s+ BY \s+ .*?)?) #4
((?:\s+ LIMIT \s+ \S+ \s* (?:, \s* \S+ \s*)? )?) #5
$/six';
$m = null;
if (preg_match($re, $queryMain[0], $m)) {
$query[0] = $m[1] . $this->_fieldList2Count($m[2]) . " AS C" . $m[3];
$skipTail = substr_count($m[4] . $m[5], '?');
if ($skipTail) array_splice($query, -$skipTail);
}
return true;
}
return false;
}
function _performQuery($queryMain)
{
$this->_lastQuery = $queryMain;
$this->_expandPlaceholders($queryMain, false);
$result = @mysql_query($queryMain[0], $this->link);
if ($result === false) return $this->_setDbError($queryMain[0]);
if (!is_resource($result)) {
if (preg_match('/^\s* INSERT \s+/six', $queryMain[0])) {
// INSERT queries return generated ID.
return @mysql_insert_id($this->link);
}
// Non-SELECT queries return number of affected rows, SELECT - resource.
return @mysql_affected_rows($this->link);
}
return $result;
}
function _performFetch($result)
{
$row = @mysql_fetch_assoc($result);
if (mysql_error()) return $this->_setDbError($this->_lastQuery);
if ($row === false) return null;
return $row;
}
function _setDbError($query)
{
return $this->_setLastError(mysql_errno(), mysql_error(), $query);
}
function _calcFoundRowsAvailable()
{
$ok = version_compare(mysql_get_server_info($this->link), '4.0') >= 0;
return $ok;
}
}
class DbSimple_Mysql_Blob extends DbSimple_Generic_Blob
{
// MySQL does not support separate BLOB fetching.
var $blobdata = null;
var $curSeek = 0;
function DbSimple_Mysql_Blob(&$database, $blobdata=null)
{
$this->blobdata = $blobdata;
$this->curSeek = 0;
}
function read($len)
{
$p = $this->curSeek;
$this->curSeek = min($this->curSeek + $len, strlen($this->blobdata));
return substr($this->blobdata, $this->curSeek, $len);
}
function write($data)
{
$this->blobdata .= $data;
}
function close()
{
return $this->blobdata;
}
function length()
{
return strlen($this->blobdata);
}
}
?>

View file

@ -0,0 +1,312 @@
<?php
/**
* DbSimple_Postgreql: PostgreSQL database.
* (C) Dk Lab, http://en.dklab.ru
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* See http://www.gnu.org/copyleft/lesser.html
*
* Placeholders are emulated because of logging purposes.
*
* @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
* @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/
*
* @version 2.x $Id: Postgresql.php 167 2007-01-22 10:12:09Z tit $
*/
require_once dirname(__FILE__) . '/Generic.php';
/**
* Database class for PostgreSQL.
*/
class DbSimple_Postgresql extends DbSimple_Generic_Database
{
var $DbSimple_Postgresql_USE_NATIVE_PHOLDERS = null;
var $prepareCache = array();
var $link;
/**
* constructor(string $dsn)
* Connect to PostgresSQL.
*/
function DbSimple_Postgresql($dsn)
{
$p = DbSimple_Generic::parseDSN($dsn);
if (!is_callable('pg_connect')) {
return $this->_setLastError("-1", "PostgreSQL extension is not loaded", "pg_connect");
}
// Prepare+execute works only in PHP 5.1+.
$this->DbSimple_Postgresql_USE_NATIVE_PHOLDERS = function_exists('pg_prepare');
$ok = $this->link = @pg_connect(
$t = (!empty($p['host']) ? 'host='.$p['host'].' ' : '').
(!empty($p['port']) ? 'port='.$p['port'].' ' : '').
'dbname='.preg_replace('{^/}s', '', $p['path']).' '.
(!empty($p['user']) ? 'user='.$p['user'].' ' : '').
(!empty($p['pass']) ? 'password='.$p['pass'].' ' : '')
);
$this->_resetLastError();
if (!$ok) return $this->_setDbError('pg_connect()');
}
function _performEscape($s, $isIdent=false)
{
if (!$isIdent)
return "'" . str_replace("'", "''", $s) . "'";
else
return '"' . str_replace('"', '_', $s) . '"';
}
function _performTransaction($parameters=null)
{
return $this->query('BEGIN');
}
function& _performNewBlob($blobid=null)
{
$obj =& new DbSimple_Postgresql_Blob($this, $blobid);
return $obj;
}
function _performGetBlobFieldNames($result)
{
$blobFields = array();
for ($i=pg_num_fields($result)-1; $i>=0; $i--) {
$type = pg_field_type($result, $i);
if (strpos($type, "BLOB") !== false) $blobFields[] = pg_field_name($result, $i);
}
return $blobFields;
}
// TODO: Real PostgreSQL escape
function _performGetPlaceholderIgnoreRe()
{
return '
" (?> [^"\\\\]+|\\\\"|\\\\)* " |
\' (?> [^\'\\\\]+|\\\\\'|\\\\)* \' |
/\* .*? \*/ # comments
';
}
function _performGetNativePlaceholderMarker($n)
{
// PostgreSQL uses specific placeholders such as $1, $2, etc.
return '$' . ($n + 1);
}
function _performCommit()
{
return $this->query('COMMIT');
}
function _performRollback()
{
return $this->query('ROLLBACK');
}
function _performTransformQuery(&$queryMain, $how)
{
// If we also need to calculate total number of found rows...
switch ($how) {
// Prepare total calculation (if possible)
case 'CALC_TOTAL':
// Not possible
return true;
// Perform total calculation.
case 'GET_TOTAL':
// TODO: GROUP BY ... -> COUNT(DISTINCT ...)
$re = '/^
(?> -- [^\r\n]* | \s+)*
(\s* SELECT \s+) #1
(.*?) #2
(\s+ FROM \s+ .*?) #3
((?:\s+ ORDER \s+ BY \s+ .*?)?) #4
((?:\s+ LIMIT \s+ \S+ \s* (?: OFFSET \s* \S+ \s*)? )?) #5
$/six';
$m = null;
if (preg_match($re, $queryMain[0], $m)) {
$queryMain[0] = $m[1] . $this->_fieldList2Count($m[2]) . " AS C" . $m[3];
$skipTail = substr_count($m[4] . $m[5], '?');
if ($skipTail) array_splice($queryMain, -$skipTail);
}
return true;
}
return false;
}
function _performQuery($queryMain)
{
$this->_lastQuery = $queryMain;
$isInsert = preg_match('/^\s* INSERT \s+/six', $queryMain[0]);
//
// Note that in case of INSERT query we CANNOT work with prepare...execute
// cache, because RULEs do not work after pg_execute(). This is a very strange
// bug... To reproduce:
// $DB->query("CREATE TABLE test(id SERIAL, str VARCHAR(10)) WITH OIDS");
// $DB->query("CREATE RULE test_r AS ON INSERT TO test DO (SELECT 111 AS id)");
// print_r($DB->query("INSERT INTO test(str) VALUES ('test')"));
// In case INSERT + pg_execute() it returns new row OID (numeric) instead
// of result of RULE query. Strange, very strange...
//
if ($this->DbSimple_Postgresql_USE_NATIVE_PHOLDERS && !$isInsert) {
// Use native placeholders only if PG supports them.
$this->_expandPlaceholders($queryMain, true);
$hash = md5($queryMain[0]);
if (!isset($this->prepareCache[$hash])) {
$this->prepareCache[$hash] = true;
$prepared = @pg_prepare($this->link, $hash, $queryMain[0]);
if ($prepared === false) return $this->_setDbError($queryMain[0]);
} else {
// Prepare cache hit!
}
$result = pg_execute($this->link, $hash, array_slice($queryMain, 1));
} else {
// No support for native placeholders or INSERT query.
$this->_expandPlaceholders($queryMain, false);
$result = @pg_query($this->link, $queryMain[0]);
}
if ($result === false) return $this->_setDbError($queryMain);
if (!pg_num_fields($result)) {
if ($isInsert) {
// INSERT queries return generated OID (if table is WITH OIDs).
//
// Please note that unfortunately we cannot use lastval() PostgreSQL
// stored function because it generates fatal error if INSERT query
// does not contain sequence-based field at all. This error terminates
// the current transaction, and we cannot continue to work nor know
// if table contains sequence-updateable field or not.
//
// To use auto-increment functionality you must invoke
// $insertedId = $DB->query("SELECT lastval()")
// manually where it is really needed.
//
return @pg_last_oid($result);
}
// Non-SELECT queries return number of affected rows, SELECT - resource.
return @pg_affected_rows($result);
}
return $result;
}
function _performFetch($result)
{
$row = @pg_fetch_assoc($result);
if (pg_last_error($this->link)) return $this->_setDbError($this->_lastQuery);
if ($row === false) return null;
return $row;
}
function _setDbError($query)
{
return $this->_setLastError(null, pg_last_error($this->link), $query);
}
function _getVersion()
{
}
}
class DbSimple_Postgresql_Blob extends DbSimple_Generic_Blob
{
var $blob; // resourse link
var $id;
var $database;
function DbSimple_Postgresql_Blob(&$database, $id=null)
{
$this->database =& $database;
$this->database->transaction();
$this->id = $id;
$this->blob = null;
}
function read($len)
{
if ($this->id === false) return ''; // wr-only blob
if (!($e=$this->_firstUse())) return $e;
$data = @pg_lo_read($this->blob, $len);
if ($data === false) return $this->_setDbError('read');
return $data;
}
function write($data)
{
if (!($e=$this->_firstUse())) return $e;
$ok = @pg_lo_write($this->blob, $data);
if ($ok === false) return $this->_setDbError('add data to');
return true;
}
function close()
{
if (!($e=$this->_firstUse())) return $e;
if ($this->blob) {
$id = @pg_lo_close($this->blob);
if ($id === false) return $this->_setDbError('close');
$this->blob = null;
} else {
$id = null;
}
$this->database->commit();
return $this->id? $this->id : $id;
}
function length()
{
if (!($e=$this->_firstUse())) return $e;
@pg_lo_seek($this->blob, 0, PGSQL_SEEK_END);
$len = @pg_lo_tell($this->blob);
@pg_lo_seek($this->blob, 0, PGSQL_SEEK_SET);
if (!$len) return $this->_setDbError('get length of');
return $len;
}
function _setDbError($query)
{
$hId = $this->id === null? "null" : ($this->id === false? "false" : $this->id);
$query = "-- $query BLOB $hId";
$this->database->_setDbError($query);
}
// Called on each blob use (reading or writing).
function _firstUse()
{
// BLOB opened - do nothing.
if (is_resource($this->blob)) return true;
// Open or create blob.
if ($this->id !== null) {
$this->blob = @pg_lo_open($this->database->link, $this->id, 'rw');
if ($this->blob === false) return $this->_setDbError('open');
} else {
$this->id = @pg_lo_create($this->database->link);
$this->blob = @pg_lo_open($this->database->link, $this->id, 'w');
if ($this->blob === false) return $this->_setDbError('create');
}
return true;
}
}
?>

View file

@ -0,0 +1,74 @@
<?php
/**
* Dklab_Cache_Backend_Profiler: wrapper for backend statistics counting.
*
* Calls $incrementor each time the code invokes a backend call.
* This class may be used in debugging purposes.
*
* $Id: MetaForm.php 238 2008-03-17 21:07:17Z dk $
*/
require_once "Zend/Cache/Backend/Interface.php";
class Dklab_Cache_Backend_Profiler implements Zend_Cache_Backend_Interface
{
private $_backend = null;
private $_incrementor = null;
public function __construct(Zend_Cache_Backend_Interface $backend, $incrementor)
{
$this->_backend = $backend;
$this->_incrementor = $incrementor;
}
public function setDirectives($directives)
{
return $this->_backend->setDirectives($directives);
}
public function load($id, $doNotTestCacheValidity = false)
{
$t0 = microtime(true);
$result = $this->_backend->load($id, $doNotTestCacheValidity);
call_user_func($this->_incrementor, microtime(true) - $t0, __METHOD__);
return $result;
}
public function test($id)
{
$t0 = microtime(true);
$result = $this->_backend->test($id);
call_user_func($this->_incrementor, microtime(true) - $t0, __METHOD__);
return $result;
}
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$t0 = microtime(true);
$result = $this->_backend->save($data, $id, $tags, $specificLifetime);
call_user_func($this->_incrementor, microtime(true) - $t0, __METHOD__);
return $result;
}
public function remove($id)
{
$t0 = microtime(true);
$result = $this->_backend->remove($id);
call_user_func($this->_incrementor, microtime(true) - $t0, __METHOD__);
return $result;
}
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
$t0 = microtime(true);
$result = $this->_backend->clean($mode, $tags);
call_user_func($this->_incrementor, microtime(true) - $t0, __METHOD__);
return $result;
}
}

View file

@ -0,0 +1,147 @@
<?php
/**
* Dklab_Cache_Backend_TagEmuWrapper: tag wrapper for any Zend_Cache backend.
*
* Implements tags. Tags are emulated via keys: unfortunately this
* increases the data read cost (the more tags are assigned to a key,
* the more read cost becomes).
*
* $Id: MetaForm.php 238 2008-03-17 21:07:17Z dk $
*/
require_once "Zend/Cache/Backend/Interface.php";
class Dklab_Cache_Backend_TagEmuWrapper implements Zend_Cache_Backend_Interface
{
const VERSION = "01";
private $_backend = null;
public function __construct(Zend_Cache_Backend_Interface $backend)
{
$this->_backend = $backend;
}
public function setDirectives($directives)
{
return $this->_backend->setDirectives($directives);
}
public function load($id, $doNotTestCacheValidity = false)
{
return $this->_loadOrTest($id, $doNotTestCacheValidity, false);
}
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
// Save/update tags as usual infinite keys with value of tag version.
// If the tag already exists, do not rewrite it.
$tagsWithVersion = array();
if (is_array($tags)) {
foreach ($tags as $tag) {
$mangledTag = $this->_mangleTag($tag);
$tagVersion = $this->_backend->load($mangledTag);
if ($tagVersion === false) {
$tagVersion = $this->_generateNewTagVersion();
$this->_backend->save($tagVersion, $mangledTag, array(), null);
}
$tagsWithVersion[$tag] = $tagVersion;
}
}
// Data is saved in form of: array(tagsWithVersionArray, anyData).
$combined = array($tagsWithVersion, $data);
$serialized = serialize($combined);
return $this->_backend->save($serialized, $id, array(), $specificLifetime);
}
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
if ($mode == Zend_Cache::CLEANING_MODE_MATCHING_TAG) {
if (is_array($tags)) {
foreach ($tags as $tag) {
$this->_backend->remove($this->_mangleTag($tag));
}
}
} else {
return $this->_backend->clean($mode, $tags);
}
}
public function test($id)
{
return $this->_loadOrTest($id, false, true);
}
public function remove($id)
{
return $this->_backend->remove($id);
}
/**
* Mangles the name to deny intersection of tag keys & data keys.
* Mangled tag names are NOT saved in memcache $combined[0] value,
* mangling is always performed on-demand (to same some space).
*
* @param string $tag Tag name to mangle.
* @return string Mangled tag name.
*/
private function _mangleTag($tag)
{
return __CLASS__ . "_" . self::VERSION . "_" . $tag;
}
/**
* Common method called from load() and test().
*
* @param string $id
* @param bool $doNotTestCacheValidity
* @param bool $returnTrueIfValid If true, returns not the value contained
* in the slot, but "true".
* @return mixed
*/
private function _loadOrTest($id, $doNotTestCacheValidity = false, $returnTrueIfValid = false)
{
// Data is saved in form of: array(tagsWithVersionArray, anyData).
$serialized = $this->_backend->load($id, $doNotTestCacheValidity);
if ($serialized === false) {
return false;
}
$combined = unserialize($serialized);
if (!is_array($combined)) {
return false;
}
// Test if all tags has the same version as when the slot was created
// (i.e. still not removed and then recreated).
if (is_array($combined[0])) {
foreach ($combined[0] as $tag => $savedTagVersion) {
$actualTagVersion = $this->_backend->load($this->_mangleTag($tag));
if ($actualTagVersion !== $savedTagVersion) {
return false;
}
}
}
return $returnTrueIfValid? true : $combined[1];
}
/**
* Generates a new unique identifier for tag version.
*
* @return string Globally (hopefully) unique identifier.
*/
private function _generateNewTagVersion()
{
static $counter = 0;
$counter++;
return md5(microtime() . getmypid() . uniqid('') . $counter);
}
}

View file

@ -0,0 +1,159 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @package Zend_Cache
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Cache
{
/**
* Standard frontends
*
* @var array
*/
public static $standardFrontends = array('Core', 'Output', 'Class', 'File', 'Function', 'Page');
/**
* Standard backends
*
* @var array
*/
public static $standardBackends = array('File', 'Sqlite', 'Memcached', 'Apc', 'ZendPlatform');
/**
* Only for backward compatibily (will be removed in 1.2.0)
*
* @var array
*/
public static $availableFrontends = array('Core', 'Output', 'Class', 'File', 'Function', 'Page');
/**
* Only for backward compatibily (will be removed in 1.2.0)
*
* @var array
*/
public static $availableBackends = array('File', 'Sqlite', 'Memcached', 'Apc', 'ZendPlatform');
/**
* Consts for clean() method
*/
const CLEANING_MODE_ALL = 'all';
const CLEANING_MODE_OLD = 'old';
const CLEANING_MODE_MATCHING_TAG = 'matchingTag';
const CLEANING_MODE_NOT_MATCHING_TAG = 'notMatchingTag';
/**
* Factory
*
* @param string $frontend frontend name
* @param string $backend backend name
* @param array $frontendOptions associative array of options for the corresponding frontend constructor
* @param array $backendOptions associative array of options for the corresponding backend constructor
* @throws Zend_Cache_Exception
* @return Zend_Cache_Frontend
*/
public static function factory($frontend, $backend, $frontendOptions = array(), $backendOptions = array())
{
// because lowercase will fail
$frontend = self::_normalizeName($frontend);
$backend = self::_normalizeName($backend);
// working on the frontend
if (in_array($frontend, self::$availableFrontends)) {
// we use a standard frontend
// For perfs reasons, with frontend == 'Core', we can interact with the Core itself
$frontendClass = 'Zend_Cache_' . ($frontend != 'Core' ? 'Frontend_' : '') . $frontend;
// For perfs reasons, we do not use the Zend_Loader::loadClass() method
// (security controls are explicit)
require_once str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php';
} else {
// we use a custom frontend
$frontendClass = 'Zend_Cache_Frontend_' . $frontend;
// To avoid security problems in this case, we use Zend_Loader to load the custom class
require_once 'Zend/Loader.php';
$file = str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php';
if (!(Zend_Loader::isReadable($file))) {
self::throwException("file $file not found in include_path");
}
Zend_Loader::loadClass($frontendClass);
}
// working on the backend
if (in_array($backend, Zend_Cache::$availableBackends)) {
// we use a standard backend
$backendClass = 'Zend_Cache_Backend_' . $backend;
// For perfs reasons, we do not use the Zend_Loader::loadClass() method
// (security controls are explicit)
require_once str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php';
} else {
// we use a custom backend
$backendClass = 'Zend_Cache_Backend_' . $backend;
// To avoid security problems in this case, we use Zend_Loader to load the custom class
require_once 'Zend/Loader.php';
$file = str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php';
if (!(Zend_Loader::isReadable($file))) {
self::throwException("file $file not found in include_path");
}
Zend_Loader::loadClass($backendClass);
}
// Making objects
$frontendObject = new $frontendClass($frontendOptions);
$backendObject = new $backendClass($backendOptions);
$frontendObject->setBackend($backendObject);
return $frontendObject;
}
/**
* Throw an exception
*
* Note : for perf reasons, the "load" of Zend/Cache/Exception is dynamic
* @param string $msg Message for the exception
* @throws Zend_Cache_Exception
*/
public static function throwException($msg)
{
// For perfs reasons, we use this dynamic inclusion
require_once 'Zend/Cache/Exception.php';
throw new Zend_Cache_Exception($msg);
}
/**
* Normalize frontend and backend names to allow multiple words TitleCased
*
* @param string $name Name to normalize
* @return string
*/
protected static function _normalizeName($name)
{
$name = ucfirst(strtolower($name));
$name = str_replace(array('-', '_', '.'), ' ', $name);
$name = ucwords($name);
$name = str_replace(' ', '', $name);
return $name;
}
}

View file

@ -0,0 +1,224 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend
{
/**
* Frontend or Core directives
*
* =====> (int) lifetime :
* - Cache lifetime (in seconds)
* - If null, the cache is valid forever
*
* =====> (int) logging :
* - if set to true, a logging is activated throw Zend_Log
*
* @var array directives
*/
protected $_directives = array(
'lifetime' => 3600,
'logging' => false,
'logger' => null
);
/**
* Available options
*
* @var array available options
*/
protected $_options = array();
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct($options = array())
{
if (!is_array($options)) {
Zend_Cache::throwException('Options parameter must be an array');
}
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
if (!is_array($directives)) Zend_Cache::throwException('Directives parameter must be an array');
while (list($name, $value) = each($directives)) {
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$name = strtolower($name);
if (array_key_exists($name, $this->_directives)) {
$this->_directives[$name] = $value;
}
}
$this->_loggerSanity();
}
/**
* Set an option
*
* @param string $name
* @param mixed $value
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$name = strtolower($name);
if (!array_key_exists($name, $this->_options)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$this->_options[$name] = $value;
}
/**
* Get the life time
*
* if $specificLifetime is not false, the given specific life time is used
* else, the global lifetime is used
*
* @param int $specificLifetime
* @return int Cache life time
*/
public function getLifetime($specificLifetime)
{
if ($specificLifetime === false) {
return $this->_directives['lifetime'];
}
return $specificLifetime;
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return true;
}
/**
* Return a system-wide tmp directory
*
* @return string System-wide tmp directory
*/
static function getTmpDir()
{
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// windows...
foreach (array($_ENV, $_SERVER) as $tab) {
foreach (array('TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
if (isset($tab[$key])) {
$result = $tab[$key];
if (($key == 'windir') or ($key == 'SystemRoot')) {
$result = $result . '\\temp';
}
return $result;
}
}
}
return '\\temp';
} else {
// unix...
if (isset($_ENV['TMPDIR'])) return $_ENV['TMPDIR'];
if (isset($_SERVER['TMPDIR'])) return $_SERVER['TMPDIR'];
return '/tmp';
}
}
/**
* Make sure if we enable logging that the Zend_Log class
* is available.
* Create a default log object if none is set.
*
* @throws Zend_Cache_Exception
* @return void
*/
protected function _loggerSanity()
{
if (!isset($this->_directives['logging']) || !$this->_directives['logging']) {
return;
}
try {
/**
* @see Zend_Loader
* @see Zend_Log
*/
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Log');
} catch (Zend_Exception $e) {
Zend_Cache::throwException('Logging feature is enabled but the Zend_Log class is not available');
}
if (isset($this->_directives['logger']) && $this->_directives['logger'] instanceof Zend_Log) {
return;
}
// Create a default logger to the standard output stream
Zend_Loader::loadClass('Zend_Log_Writer_Stream');
$logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
$this->_directives['logger'] = $logger;
}
/**
* Log a message at the WARN (4) priority.
*
* @param string $message
* @throws Zend_Cache_Exception
* @return void
*/
protected function _log($message, $priority = 4)
{
if (!$this->_directives['logging']) {
return;
}
if (!(isset($this->_directives['logger']) || $this->_directives['logger'] instanceof Zend_Log)) {
Zend_Cache::throwException('Logging is enabled but logger is not set');
}
$logger = $this->_directives['logger'];
$logger->log($message, $priority);
}
}

View file

@ -0,0 +1,716 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @see Zend_Cache_Backend_Interface
*/
require_once 'Zend/Cache/Backend/Interface.php';
/**
* @see Zend_Cache_Backend
*/
require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_File extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Available options
*
* =====> (string) cache_dir :
* - Directory where to put the cache files
*
* =====> (boolean) file_locking :
* - Enable / disable file_locking
* - Can avoid cache corruption under bad circumstances but it doesn't work on multithread
* webservers and on NFS filesystems for example
*
* =====> (boolean) read_control :
* - Enable / disable read control
* - If enabled, a control key is embeded in cache file and this key is compared with the one
* calculated after the reading.
*
* =====> (string) read_control_type :
* - Type of read control (only if read control is enabled). Available values are :
* 'md5' for a md5 hash control (best but slowest)
* 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
* 'adler32' for an adler32 hash control (excellent choice too, faster than crc32)
* 'strlen' for a length only test (fastest)
*
* =====> (int) hashed_directory_level :
* - Hashed directory level
* - Set the hashed directory structure level. 0 means "no hashed directory
* structure", 1 means "one level of directory", 2 means "two levels"...
* This option can speed up the cache only when you have many thousands of
* cache file. Only specific benchs can help you to choose the perfect value
* for you. Maybe, 1 or 2 is a good start.
*
* =====> (int) hashed_directory_umask :
* - Umask for hashed directory structure
*
* =====> (string) file_name_prefix :
* - prefix for cache files
* - be really carefull with this option because a too generic value in a system cache dir
* (like /tmp) can cause disasters when cleaning the cache
*
* =====> (int) cache_file_umask :
* - Umask for cache files
*
* =====> (int) metatadatas_array_max_size :
* - max size for the metadatas array (don't change this value unless you
* know what you are doing)
*
* @var array available options
*/
protected $_options = array(
'cache_dir' => null,
'file_locking' => true,
'read_control' => true,
'read_control_type' => 'crc32',
'hashed_directory_level' => 0,
'hashed_directory_umask' => 0700,
'file_name_prefix' => 'zend_cache',
'cache_file_umask' => 0600,
'metadatas_array_max_size' => 100
);
/**
* Array of metadatas (each item is an associative array)
*
* @var array
*/
private $_metadatasArray = array();
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
if (!is_null($this->_options['cache_dir'])) { // particular case for this option
$this->setCacheDir($this->_options['cache_dir']);
} else {
$this->setCacheDir(self::getTmpDir() . DIRECTORY_SEPARATOR, false);
}
if (isset($this->_options['file_name_prefix'])) { // particular case for this option
if (!preg_match('~^[\w]+$~', $this->_options['file_name_prefix'])) {
Zend_Cache::throwException('Invalid file_name_prefix : must use only [a-zA-A0-9_]');
}
}
if ($this->_options['metadatas_array_max_size'] < 10) {
Zend_Cache::throwException('Invalid metadatas_array_max_size, must be > 10');
}
}
/**
* Set the cache_dir (particular case of setOption() method)
*
* @param string $value
* @param boolean $trailingSeparator If true, add a trailing separator is necessary
* @throws Zend_Cache_Exception
* @return void
*/
public function setCacheDir($value, $trailingSeparator = true)
{
if (!is_dir($value)) {
Zend_Cache::throwException('cache_dir must be a directory');
}
if (!is_writable($value)) {
Zend_Cache::throwException('cache_dir is not writable');
}
if ($trailingSeparator) {
// add a trailing DIRECTORY_SEPARATOR if necessary
$value = rtrim(realpath($value), '\\/') . DIRECTORY_SEPARATOR;
}
$this->_options['cache_dir'] = $value;
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
if (!($this->_test($id, $doNotTestCacheValidity))) {
// The cache is not hit !
return false;
}
$metadatas = $this->_getMetadatas($id);
$file = $this->_file($id);
$data = $this->_fileGetContents($file);
if ($this->_options['read_control']) {
$hashData = $this->_hash($data, $this->_options['read_control_type']);
$hashControl = $metadatas['hash'];
if ($hashData != $hashControl) {
// Problem detected by the read control !
$this->_log('Zend_Cache_Backend_File::load() / read_control : stored hash and computed hash do not match');
$this->remove($id);
return false;
}
}
return $data;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
clearstatcache();
return $this->_test($id, false);
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
clearstatcache();
$file = $this->_file($id);
$path = $this->_path($id);
$firstTry = true;
$result = false;
if ($this->_options['hashed_directory_level'] > 0) {
if (!is_writable($path)) {
// maybe, we just have to build the directory structure
@mkdir($this->_path($id), $this->_options['hashed_directory_umask'], true);
@chmod($this->_path($id), $this->_options['hashed_directory_umask']); // see #ZF-320 (this line is required in some configurations)
}
if (!is_writable($path)) {
return false;
}
}
if ($this->_options['read_control']) {
$hash = $this->_hash($data, $this->_options['read_control_type']);
} else {
$hash = '';
}
$metadatas = array(
'hash' => $hash,
'mtime' => time(),
'expire' => $this->_expireTime($this->getLifetime($specificLifetime)),
'tags' => $tags
);
$res = $this->_setMetadatas($id, $metadatas);
if (!$res) {
// FIXME : log
return false;
}
$res = $this->_filePutContents($file, $data);
return $res;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
$file = $this->_file($id);
return ($this->_delMetadatas($id) && $this->_remove($file));
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => remove too old cache entries ($tags is not used)
* 'matchingTag' => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* 'notMatchingTag' => remove cache entries not matching one of the given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode clean mode
* @param tags array $tags array of tags
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
// We use this private method to hide the recursive stuff
clearstatcache();
return $this->_clean($this->_options['cache_dir'], $mode, $tags);
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
$metadatas = $this->_getMetadatas($id);
if ($metadatas) {
$metadatas['expire'] = 1;
$this->_setMetadatas($id, $metadatas);
}
}
/**
* Get a metadatas record
*
* @param string $id Cache id
* @return array|false Associative array of metadatas
*/
private function _getMetadatas($id)
{
if (isset($this->_metadatasArray[$id])) {
return $this->_metadatasArray[$id];
} else {
$metadatas = $this->_loadMetadatas($id);
if (!$metadatas) {
return false;
}
$this->_setMetadatas($id, $metadatas, false);
return $metadatas;
}
}
/**
* Set a metadatas record
*
* @param string $id Cache id
* @param array $metadatas Associative array of metadatas
* @param boolean $save optional pass false to disable saving to file
* @return boolean True if no problem
*/
private function _setMetadatas($id, $metadatas, $save = true)
{
if (count($this->_metadatasArray) >= $this->_options['metadatas_array_max_size']) {
$n = (int) ($this->_options['metadatas_array_max_size'] / 10);
$this->_metadatasArray = array_slice($this->_metadatasArray, $n);
}
if ($save) {
$result = $this->_saveMetadatas($id, $metadatas);
if (!$result) {
return false;
}
}
$this->_metadatasArray[$id] = $metadatas;
return true;
}
/**
* Drop a metadata record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
private function _delMetadatas($id)
{
if (isset($this->_metadatasArray[$id])) {
unset($this->_metadatasArray[$id]);
}
$file = $this->_metadatasFile($id);
return $this->_remove($file);
}
/**
* Clear the metadatas array
*
* @return void
*/
private function _cleanMetadatas()
{
$this->_metadatasArray = array();
}
/**
* Load metadatas from disk
*
* @param string $id Cache id
* @return array|false Metadatas associative array
*/
private function _loadMetadatas($id)
{
$file = $this->_metadatasFile($id);
$result = $this->_fileGetContents($file);
if (!$result) {
return false;
}
$tmp = @unserialize($result);
return $tmp;
}
/**
* Save metadatas to disk
*
* @param string $id Cache id
* @param array $metadatas Associative array
* @return boolean True if no problem
*/
private function _saveMetadatas($id, $metadatas)
{
$file = $this->_metadatasFile($id);
$result = $this->_filePutContents($file, serialize($metadatas));
if (!$result) {
return false;
}
return true;
}
/**
* Make and return a file name (with path) for metadatas
*
* @param string $id Cache id
* @return string Metadatas file name (with path)
*/
private function _metadatasFile($id)
{
$path = $this->_path($id);
$fileName = $this->_idToFileName('internal-metadatas---' . $id);
return $path . $fileName;
}
/**
* Check if the given filename is a metadatas one
*
* @param string $fileName File name
* @return boolean True if it's a metadatas one
*/
private function _isMetadatasFile($fileName)
{
$id = $this->_fileNameToId($fileName);
if (substr($id, 0, 21) == 'internal-metadatas---') {
return true;
} else {
return false;
}
}
/**
* Remove a file
*
* If we can't remove the file (because of locks or any problem), we will touch
* the file to invalidate it
*
* @param string $file Complete file path
* @return boolean True if ok
*/
private function _remove($file)
{
if (!is_file($file)) {
return false;
}
if (!@unlink($file)) {
# we can't remove the file (because of locks or any problem)
$this->_log("Zend_Cache_Backend_File::_remove() : we can't remove $file");
return false;
}
return true;
}
/**
* Clean some cache records (private method used for recursive stuff)
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
*
* @param string $dir Directory to clean
* @param string $mode Clean mode
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
private function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
if (!is_dir($dir)) {
return false;
}
$result = true;
$prefix = $this->_options['file_name_prefix'];
$glob = @glob($dir . $prefix . '--*');
if ($glob === false) {
return true;
}
foreach ($glob as $file) {
if (is_file($file)) {
$fileName = basename($file);
if ($this->_isMetadatasFile($fileName)) {
// in CLEANING_MODE_ALL, we drop anything, even remainings old metadatas files
if ($mode != Zend_Cache::CLEANING_MODE_ALL) {
continue;
}
}
$id = $this->_fileNameToId($fileName);
$metadatas = $this->_getMetadatas($id);
if ($metadatas === FALSE) {
$metadatas = array('expire' => 1, 'tags' => array());
}
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$res = $this->remove($id);
if (!$res) {
// in this case only, we accept a problem with the metadatas file drop
$res = $this->_remove($file);
}
$result = $result && $res;
break;
case Zend_Cache::CLEANING_MODE_OLD:
if (time() > $metadatas['expire']) {
$result = ($result) && ($this->remove($id));
}
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$matching = true;
foreach ($tags as $tag) {
if (!in_array($tag, $metadatas['tags'])) {
$matching = false;
break;
}
}
if ($matching) {
$result = ($result) && ($this->remove($id));
}
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$matching = false;
foreach ($tags as $tag) {
if (in_array($tag, $metadatas['tags'])) {
$matching = true;
break;
}
}
if (!$matching) {
$result = ($result) && $this->remove($id);
}
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) {
// Recursive call
$result = ($result) && ($this->_clean($file . DIRECTORY_SEPARATOR, $mode, $tags));
if ($mode=='all') {
// if mode=='all', we try to drop the structure too
@rmdir($file);
}
}
}
return $result;
}
/**
* Compute & return the expire time
*
* @return int expire time (unix timestamp)
*/
private function _expireTime($lifetime)
{
if (is_null($lifetime)) {
return 9999999999;
}
return time() + $lifetime;
}
/**
* Make a control key with the string containing datas
*
* @param string $data Data
* @param string $controlType Type of control 'md5', 'crc32' or 'strlen'
* @throws Zend_Cache_Exception
* @return string Control key
*/
private function _hash($data, $controlType)
{
switch ($controlType) {
case 'md5':
return md5($data);
case 'crc32':
return crc32($data);
case 'strlen':
return strlen($data);
case 'adler32':
return hash('adler32', $data);
default:
Zend_Cache::throwException("Incorrect hash function : $controlType");
}
}
/**
* Transform a cache id into a file name and return it
*
* @param string $id Cache id
* @return string File name
*/
private function _idToFileName($id)
{
$prefix = $this->_options['file_name_prefix'];
$result = $prefix . '---' . $id;
return $result;
}
/**
* Make and return a file name (with path)
*
* @param string $id Cache id
* @return string File name (with path)
*/
private function _file($id)
{
$path = $this->_path($id);
$fileName = $this->_idToFileName($id);
return $path . $fileName;
}
/**
* Return the complete directory path of a filename (including hashedDirectoryStructure)
*
* @param string $id Cache id
* @return string Complete directory path
*/
private function _path($id)
{
$root = $this->_options['cache_dir'];
$prefix = $this->_options['file_name_prefix'];
if ($this->_options['hashed_directory_level']>0) {
$hash = hash('adler32', $id);
for ($i=0 ; $i < $this->_options['hashed_directory_level'] ; $i++) {
$root = $root . $prefix . '--' . substr($hash, 0, $i + 1) . DIRECTORY_SEPARATOR;
}
}
return $root;
}
/**
* Test if the given cache id is available (and still valid as a cache record)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return boolean|mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
private function _test($id, $doNotTestCacheValidity)
{
$metadatas = $this->_getMetadatas($id);
if (!$metadatas) {
return false;
}
if ($doNotTestCacheValidity || (time() <= $metadatas['expire'])) {
return $metadatas['mtime'];
}
return false;
}
/**
* Return the file content of the given file
*
* @param string $file File complete path
* @return string File content (or false if problem)
*/
private function _fileGetContents($file)
{
$result = false;
if (!is_file($file)) {
return false;
}
if (function_exists('get_magic_quotes_runtime')) {
$mqr = @get_magic_quotes_runtime();
@set_magic_quotes_runtime(0);
}
$f = @fopen($file, 'rb');
if ($f) {
if ($this->_options['file_locking']) @flock($f, LOCK_SH);
$result = stream_get_contents($f);
if ($this->_options['file_locking']) @flock($f, LOCK_UN);
@fclose($f);
}
if (function_exists('set_magic_quotes_runtime')) {
@set_magic_quotes_runtime($mqr);
}
return $result;
}
/**
* Put the given string into the given file
*
* @param string $file File complete path
* @param string $string String to put in file
* @return boolean true if no problem
*/
private function _filePutContents($file, $string)
{
$result = false;
$f = @fopen($file, 'ab+');
if ($f) {
if ($this->_options['file_locking']) @flock($f, LOCK_EX);
fseek($f, 0);
ftruncate($f, 0);
$tmp = @fwrite($f, $string);
if (!($tmp === FALSE)) {
$result = true;
}
@fclose($f);
}
@chmod($file, $this->_options['cache_file_umask']);
return $result;
}
/**
* Transform a file name into cache id and return it
*
* @param string $fileName File name
* @return string Cache id
*/
private function _fileNameToId($fileName)
{
$prefix = $this->_options['file_name_prefix'];
return preg_replace('~^' . $prefix . '---(.*)$~', '$1', $fileName);
}
}

View file

@ -0,0 +1,96 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cache_Backend_Interface
{
/**
* Set the frontend directives
*
* @param array $directives assoc of directives
*/
public function setDirectives($directives);
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* Note : return value is always "string" (unserialization is done by the core not by the backend)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false);
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id);
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false);
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id);
/**
* Clean some cache records
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array());
}

View file

@ -0,0 +1,234 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @see Zend_Cache_Backend_Interface
*/
require_once 'Zend/Cache/Backend/Interface.php';
/**
* @see Zend_Cache_Backend
*/
require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Memcached extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Default Host IP Address or DNS
*/
const DEFAULT_HOST = '127.0.0.1';
/**
* Default port
*/
const DEFAULT_PORT = 11211;
/**
* Persistent
*/
const DEFAULT_PERSISTENT = true;
/**
* Available options
*
* =====> (array) servers :
* an array of memcached server ; each memcached server is described by an associative array :
* 'host' => (string) : the name of the memcached server
* 'port' => (int) : the port of the memcached server
* 'persistent' => (bool) : use or not persistent connections to this memcached server
*
* =====> (boolean) compression :
* true if you want to use on-the-fly compression
*
* @var array available options
*/
protected $_options = array(
'servers' => array(array(
'host' => Zend_Cache_Backend_Memcached::DEFAULT_HOST,
'port' => Zend_Cache_Backend_Memcached::DEFAULT_PORT,
'persistent' => Zend_Cache_Backend_Memcached::DEFAULT_PERSISTENT
)),
'compression' => false
);
/**
* Memcache object
*
* @var mixed memcache object
*/
private $_memcache = null;
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct($options = array())
{
if (!extension_loaded('memcache')) {
Zend_Cache::throwException('The memcache extension must be loaded for using this backend !');
}
parent::__construct($options);
if (isset($this->_options['servers'])) {
$value= $this->_options['servers'];
if (isset($value['host'])) {
// in this case, $value seems to be a simple associative array (one server only)
$value = array(0 => $value); // let's transform it into a classical array of associative arrays
}
$this->setOption('servers', $value);
}
$this->_memcache = new Memcache;
foreach ($this->_options['servers'] as $server) {
if (!array_key_exists('persistent', $server)) {
$server['persistent'] = Zend_Cache_Backend_Memcached::DEFAULT_PERSISTENT;
}
if (!array_key_exists('port', $server)) {
$server['port'] = Zend_Cache_Backend_Memcached::DEFAULT_PORT;
}
$this->_memcache->addServer($server['host'], $server['port'], $server['persistent']);
}
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
// WARNING : $doNotTestCacheValidity is not supported !!!
if ($doNotTestCacheValidity) {
$this->_log("Zend_Cache_Backend_Memcached::load() : \$doNotTestCacheValidity=true is unsupported by the Memcached backend");
}
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
return $tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
if ($this->_options['compression']) {
$flag = MEMCACHE_COMPRESSED;
} else {
$flag = 0;
}
$result = $this->_memcache->set($id, array($data, time()), $flag, $lifetime);
if (count($tags) > 0) {
$this->_log("Zend_Cache_Backend_Memcached::save() : tags are unsupported by the Memcached backend");
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return $this->_memcache->delete($id);
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => remove too old cache entries ($tags is not used)
* 'matchingTag' => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* 'notMatchingTag' => remove cache entries not matching one of the given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
if ($mode==Zend_Cache::CLEANING_MODE_ALL) {
return $this->_memcache->flush();
}
if ($mode==Zend_Cache::CLEANING_MODE_OLD) {
$this->_log("Zend_Cache_Backend_Memcached::clean() : CLEANING_MODE_OLD is unsupported by the Memcached backend");
}
if ($mode==Zend_Cache::CLEANING_MODE_MATCHING_TAG) {
$this->_log("Zend_Cache_Backend_Memcached::clean() : tags are unsupported by the Memcached backend");
}
if ($mode==Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG) {
$this->_log("Zend_Cache_Backend_Memcached::clean() : tags are unsupported by the Memcached backend");
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
}

View file

@ -0,0 +1,31 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @see Zend_Exception
*/
require_once 'Zend/Exception.php';
/**
* @package Zend_Cache
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Exception extends Zend_Exception {}

View file

@ -0,0 +1,30 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @category Zend
* @package Zend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Exception extends Exception
{}

View file

@ -0,0 +1,5 @@
<?php
if (!defined("PATH_SEPARATOR"))
define("PATH_SEPARATOR", getenv("COMSPEC")? ";" : ":");
ini_set("include_path", ini_get("include_path").PATH_SEPARATOR.dirname(__FILE__));
?>

159
classes/lib/external/HackerConsole/Js.js vendored Normal file
View file

@ -0,0 +1,159 @@
/**
* Debug_HackerConsole_Js: JavaScript frontend for hacker console.
* (C) 2005 Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* See http://www.gnu.org/copyleft/lesser.html
*
* @version 1.x $Id: Js.js 235 2008-03-17 20:53:05Z dk $
*/
function Debug_HackerConsole_Js(top) { this.construct(window) }
Debug_HackerConsole_Js.prototype = {
top: null,
div: null,
height: parseInt('{HEIGHT}'), // JS syntax OK
curHeight: 0,
step: 0,
speedOn: 0.3,
speedOff: 10,
dt: 50,
fontsize: 15,
groups: null,
scrollTimeout: null,
construct: function(t) { with (this) {
top = t || window;
groups = {};
if (!top.document.body) {
top.document.writeln("<" + "body style='padding:0; margin:0'><" + "/body>");
}
with (top.document) {
if (body.childNodes[0]) {
div = body.insertBefore(createElement('div'), body.childNodes[0]);
} else {
div = body.appendChild(createElement('div'));
}
div.className = 'hackerConsole';
with (div.style) {
display = 'none';
background = 'black';
zIndex = 999999999;
position = 'relative';
textAlign = 'left';
padding = '4px';
margin = '0px';
width = '100%';
maxWidth = (screen.width-30) + 'px';
height = this.height + 'px';
overflow = 'auto';
border = '1px solid black';
color = '#00EE00';
font = 'normal ' + this.fontsize + 'px "Courier new", Courier';
}
var th = this;
var owner = window.HTMLElement? window : body;
var prevKeydown = owner.onkeydown;
owner.onkeydown = function(e) {
if (!e) e = window.event;
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 192 || e.keyCode == 96 || e.keyCode == 191)) {
th.toggle(-1);
return false;
}
if (prevKeydown) {
this.__prev = prevKeydown;
return this.__prev(e);
}
}
toggle(null);
}
}},
toggle: function(on, onstart) {
var cookName = 'hackerConsole';
if (on == null) on = Math.round(this.getCookie(cookName));
if (on < 0) on = !Math.round(this.getCookie(cookName));
if (on) {
this.curHeight = 0;
this.step = this.speedOn;
} else {
this.curHeight = this.div.style.display!='none'? this.height : 0;
this.step = -this.speedOff;
}
var th = this;
var fResizer = function() {
th.div.style.display = on? '' : 'none';
th.curHeight = th.curHeight + th.height*th.step;
if (th.curHeight < 0) th.curHeight = 0;
if (th.curHeight > th.height) th.curHeight = th.height;
th.div.style.height = (Math.round(th.curHeight)+1) + "px";
th.div.style.display = '';
if (th.curHeight <= 1) {
th.div.style.display = 'none';
return;
} else if (th.curHeight >= th.height) {
return;
}
setTimeout(fResizer, th.dt);
}
fResizer();
this.setCookie(cookName, on? 1 : 0, '/', new Date(new Date().getTime()+3600*24*365*1000));
},
out: function(msg, title, group) { with (this) {
if (!msg) return;
var span = top.document.createElement('div');
span.innerHTML = msg;
var container = div;
if (group) {
container = groups[group];
if (!container) {
var groupDiv = top.document.createElement('div');
div.appendChild(groupDiv);
groupDiv.style.marginBottom = "7px";
var headDiv = top.document.createElement('div');
groupDiv.appendChild(headDiv);
headDiv.innerHTML = group + ":";
headDiv.style.fontWeight = "bold";
headDiv.style.fontSize = (fontsize+5)+"px";
container = top.document.createElement('div');
groupDiv.appendChild(container);
container.style.marginLeft = "1em";
container.style.paddingLeft = "4px";
container.style.borderLeft = "3px double";
groups[group] = container;
}
}
container.appendChild(span);
if (scrollTimeout) clearTimeout(scrollTimeout);
var d = this.div;
scrollTimeout = setTimeout(function() { d.scrollTop = 10000000 }, 100);
if (title != null) {
span.title = title;
try { span.style.cursor = "pointer"; } catch (e) {}
}
}},
// Ôóíêöèÿ óñòàíîâêè çíà÷åíèÿ cookie.
setCookie: function(name, value, path, expires, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "; path=/") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
},
// Ôóíêöèÿ ÷òåíèÿ çíà÷åíèÿ cookie.
getCookie: function(name) {
var prefix = name + "=";
var cookieStartIndex = document.cookie.indexOf(prefix);
if (cookieStartIndex == -1) return null;
var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}
}

View file

@ -0,0 +1,309 @@
<?php
/**
* Debug_HackerConsole_Main: write debug messages into hidden console.
* (C) 2005 Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* See http://www.gnu.org/copyleft/lesser.html
* Console may be toggled using Shift+Ctrl+` (tilde) combination.
*
* @version 1.x $Id: Main.php 168 2007-01-30 21:12:03Z dk $
*/
class Debug_HackerConsole_Main
{
var $_hc_height = "400"; // height of the console (pixels)
var $_hc_entries = array();
var $TAB_SIZE = 4;
/**
* constructor($autoAttachToHtmlOutput=true)
* Create new console. If $autoAttachToHtmlOutput, output buffering
* handler is set to automatically attach JavaScript showing code to
* HTML page.
*/
function Debug_HackerConsole_Main($autoAttach=false)
{
if ($autoAttach) ob_start(array(&$this, '_obHandler'));
$GLOBALS['Debug_HackerConsole_Main_LAST'] =& $this;
}
/**
* string attachToHtml(string $pageHtml)
* Attach the console to given HTML page.
*/
function attachToHtml($page)
{
$js = implode("", file(dirname(__FILE__).'/Js.js'));
if (get_magic_quotes_runtime()) $js = stripslashes($js);
$js = str_replace('{HEIGHT}', $this->_hc_height, $js);
// We MUST use "hackerConsole" instead of "console" because of Safari.
$code = "window.hackerConsole = window.hackerConsole || window.Debug_HackerConsole_Js && new window.Debug_HackerConsole_Js();\n";
$code .= "if (window.hackerConsole) setTimeout(function() { with (window.hackerConsole) {\n";
foreach ($this->_hc_entries as $gid=>$elements) {
foreach ($elements as $e) {
if ($e['tip'] === null) {
$file = str_replace('\\', '/', $e['file']);
if (isset($_SERVER['DOCUMENT_ROOT'])) {
// Under IIS DOCUMENT_ROOT may not be available.
$dr = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
$file = preg_replace('{^'.preg_quote($dr,'{}').'}is', '~', $file);
}
$title = "at {$file} line {$e['line']}" . (!empty($e['function'])? ", {$e['function']}" : "");
} else {
$title = $e['tip'];
}
$text = $this->toPre($e['text']);
if (!empty($e['color'])) $text = "<div style=\"color:{$e['color']}\">$text</div>";
$code .= " out(".$this->_toJs($text).", ".$this->_toJs($title).", ".$this->_toJs($gid).");\n";
}
}
$code .= "}}, 200);";
$html = '';
// Dirty close opened tags. This is bad, but better than nothing...
$lower = strtolower($page);
if (strpos($lower, '</body>') === false) {
foreach (array('script', 'xmp', 'pre') as $tag) {
if (substr_count($lower, "<$tag") > substr_count($lower, "</$tag")) {
$html .= "</$tag>";
}
}
}
$html .= "\n";
$html .= "<!-- ##################### -->\n";
$html .= "<!-- ### HackerConsole ### -->\n";
$html .= "<!-- ##################### -->\n";
$html .= "<script type=\"text/javascript\" language=\"JavaScript\">//<![CDATA[\n{$js}\n{$code}\n//]]></script>\n";
$page = preg_replace('{(?=</body[^>]*>|$)}si', preg_replace('/([\\\\$])/', '\\\\$1', $html), $page, 1);
return $page;
}
/**
* void out(string $msg, string $group="message", $color=null, $tip=null)
* Add new message to the console.
* Messages may be grouped together using $group parameters for better view.
* By default messages are tipped with caller context (file, line).
* Contexts generated by call_user_func() are skipped!
*/
function out($v, $group="message", $color=null, $tip=null)
{
static $dumpCnt;
if (is_null($dumpCnt)) {
$dumpCnt = 0;
}
// Have to work only with $obj, NOT $this!
if (empty($this) || strtolower(get_class($this)) != 'debug_hackerconsole_main') {
$obj =& $GLOBALS['Debug_HackerConsole_Main_LAST'];
} else {
$obj =& $this;
}
if (!$obj) return;
// Detect caller if needed. Used in tip.
$s = array();
if ($tip === null) {
// Find caller. Use call_user_func to get context of out() calling.
$s = call_user_func(
array(&$obj, 'debug_backtrace_smart'),
'call_user_func.*', // ignore indirect contexts
true
);
}
if (is_scalar($v)) $text = "$v\n";
else $text = Debug_HackerConsole_Main::print_r($v, true);
$obj->_hc_entries[$group][] = array(
'file' => isset($s['file'])? $s['file'] : null,
'line' => isset($s['line'])? $s['line'] : null,
'function' => isset($s['function'])? $s['function'] : null,
'text' => '#'.$dumpCnt.' '.$text,
'color' => $color,
'tip' => $tip,
);
$dumpCnt++;
}
/**
* void disable()
* Disable displaying of the console.
*/
function disable()
{
// Work only with $obj, NOT $this!
if (empty($this) || strtolower(get_class($this)) != 'debug_hackerconsole_main') {
$obj =& $GLOBALS['Debug_HackerConsole_Main_LAST'];
} else {
$obj =& $this;
}
$obj->disabled = true;
}
/**
* string toPre($text)
* Format plaintext like <pre> tag does, but with <br> at the line tails
* and &nbsp; in line prefixes.
*/
function toPre($text, $tabSize=null)
{
$text = htmlspecialchars($text);
// Expand tabulators.
if ($tabSize === null) {
if (isset($GLOBALS['Debug_HackerConsole_Main_LAST']))
$tabSize = $GLOBALS['Debug_HackerConsole_Main_LAST']->TAB_SIZE;
else
$tabSize = 4;
}
$text = Debug_HackerConsole_Main::expandTabs($text, $tabSize);
$text = str_replace(' ', '&nbsp;', $text);
$text = nl2br($text);
return $text;
}
/**
* We need manual custom print_r() to use it in OB handlers
* (original print_r() cannot work inside OB handler).
*/
function print_r($obj, $no_print=0, $level=0)
{
if ($level < 10) {
if (is_array($obj)) {
$type = "Array[".count($obj)."]";
} elseif (is_object($obj)) {
$type = "Object";
} elseif (gettype($obj) == "boolean") {
$type = $obj? "TRUE" : "FALSE";
} elseif ($obj === null) {
$type = "NULL";
} else {
$type = preg_replace("/\r?\n/", "\\n", $obj);
}
$buf = $type;
if (is_array($obj) || is_object($obj)) {
$leftSp = str_repeat(" ", $level+1);
for (reset($obj); list($k, $v) = each($obj); ) {
if ($k === "GLOBALS") continue;
$buf .= "\n{$leftSp}[$k] => ".Debug_HackerConsole_Main::print_r($v, $no_print, $level+1);
}
}
} else {
$buf = "*RECURSION*";
}
$buf = str_replace("\x00", " ", $buf); // PHP5 private methods contain \x00 in names
if ($no_print) return $buf;
else echo $buf;
return null;
}
/**
* string expandTabs($text, $tabSize=4)
* Correctly convert tabulators to spaces.
*/
function expandTabs($text, $tabSize=4)
{
$GLOBALS['expandTabs_tabSize'] = $tabSize;
while (1) {
$old = $text;
$text = preg_replace_callback('/^([^\t\r\n]*)\t(\t*)/m', array('Debug_HackerConsole_Main', 'expandTabs_callback'), $text);
if ($old === $text) return $text;
}
}
function expandTabs_callback($m)
{
$tabSize = $GLOBALS['expandTabs_tabSize'];
$n =
intval((strlen($m[1]) + $tabSize) / $tabSize) * $tabSize
- strlen($m[1])
+ strlen($m[2]) * $tabSize;
return $m[1] . str_repeat(' ', $n);
}
/**
* Internal methods.
*/
function _obHandler($s)
{
return $this->attachToHtml($s);
}
function _toJs($a)
{
$a = addslashes($a);
$a = str_replace(array("\n", "\r", ">", "<"), array('\n', '\r', "'+'>", "<'+'"), $a);
return "'$a'";
}
/**
* 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
*/
function debug_backtrace_smart($ignoresRe=null, $returnCaller=false)
{
if (!is_callable($tracer='debug_backtrace')) return array();
$trace = $tracer();
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
}
// 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;
}
return $smart;
}
}
/**
* Last created console.
*/
$GLOBALS['Debug_HackerConsole_Main_LAST'] = null;
?>

1206
classes/lib/external/Jevix/jevix.class.php vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,26 @@
/**
* JsHttpRequest & Prototype integration module.
* Include this file just after the JsHttpRequest and Prototype inclusion.
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
Ajax.Request.prototype._jshr_setOptions = Ajax.Request.prototype.setOptions;
Ajax.Request.prototype.setOptions = function(options) {
// Support for whole form & form element sending.
var parameters = options.parameters;
options.parameters = {};
this.transport._jshr_send = this.transport.send;
this.transport.send = function(body) {
return this._jshr_send(body || parameters);
}
this._jshr_setOptions(options);
}
Ajax.getTransport = function() {
return new JsHttpRequest();
}
Ajax.Request.prototype.evalResponse = Prototype.emptyFunction;

View file

@ -0,0 +1,576 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader
* Minimized version: see debug directory for the complete one.
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
function JsHttpRequest(){
var t=this;
t.onreadystatechange=null;
t.readyState=0;
t.responseText=null;
t.responseXML=null;
t.status=200;
t.statusText="OK";
t.responseJS=null;
t.caching=false;
t.loader=null;
t.session_name="PHPSESSID";
t._ldObj=null;
t._reqHeaders=[];
t._openArgs=null;
t._errors={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%"};
t.abort=function(){
with(this){
if(_ldObj&&_ldObj.abort){
_ldObj.abort();
}
_cleanup();
if(readyState==0){
return;
}
if(readyState==1&&!_ldObj){
readyState=0;
return;
}
_changeReadyState(4,true);
}
};
t.open=function(_2,_3,_4,_5,_6){
with(this){
if(_3.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){
this.loader=RegExp.$2?RegExp.$2:null;
_2=RegExp.$3;
_3=RegExp.$4;
}
try{
if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){
_3+=(_3.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1);
}
}
catch(e){
}
_openArgs={method:(_2||"").toUpperCase(),url:_3,asyncFlag:_4,username:_5!=null?_5:"",password:_6!=null?_6:""};
_ldObj=null;
_changeReadyState(1,true);
return true;
}
};
t.send=function(_7){
if(!this.readyState){
return;
}
this._changeReadyState(1,true);
this._ldObj=null;
var _8=[];
var _9=[];
if(!this._hash2query(_7,null,_8,_9)){
return;
}
var _a=null;
if(this.caching&&!_9.length){
_a=this._openArgs.username+":"+this._openArgs.password+"@"+this._openArgs.url+"|"+_8+"#"+this._openArgs.method;
var _b=JsHttpRequest.CACHE[_a];
if(_b){
this._dataReady(_b[0],_b[1]);
return false;
}
}
var _c=(this.loader||"").toLowerCase();
if(_c&&!JsHttpRequest.LOADERS[_c]){
return this._error("unk_loader",_c);
}
var _d=[];
var _e=JsHttpRequest.LOADERS;
for(var _f in _e){
var ldr=_e[_f].loader;
if(!ldr){
continue;
}
if(_c&&_f!=_c){
continue;
}
var _11=new ldr(this);
JsHttpRequest.extend(_11,this._openArgs);
JsHttpRequest.extend(_11,{queryText:_8.join("&"),queryElem:_9,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:_a,span:null});
var _12=_11.load();
if(!_12){
this._ldObj=_11;
JsHttpRequest.PENDING[_11.id]=this;
return true;
}
if(!_c){
_d[_d.length]="- "+_f.toUpperCase()+": "+this._l(_12);
}else{
return this._error(_12);
}
}
return _f?this._error("no_loader_matched",_d.join("\n")):this._error("no_loaders");
};
t.getAllResponseHeaders=function(){
with(this){
return _ldObj&&_ldObj.getAllResponseHeaders?_ldObj.getAllResponseHeaders():[];
}
};
t.getResponseHeader=function(_13){
with(this){
return _ldObj&&_ldObj.getResponseHeader?_ldObj.getResponseHeader(_13):null;
}
};
t.setRequestHeader=function(_14,_15){
with(this){
_reqHeaders[_reqHeaders.length]=[_14,_15];
}
};
t._dataReady=function(_16,js){
with(this){
if(caching&&_ldObj){
JsHttpRequest.CACHE[_ldObj.hash]=[_16,js];
}
responseText=responseXML=_16;
responseJS=js;
if(js!==null){
status=200;
statusText="OK";
}else{
status=500;
statusText="Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}
};
t._l=function(_18){
var i=0,p=0,msg=this._errors[_18[0]];
while((p=msg.indexOf("%",p))>=0){
var a=_18[++i]+"";
msg=msg.substring(0,p)+a+msg.substring(p+1,msg.length);
p+=1+a.length;
}
return msg;
};
t._error=function(msg){
msg=this._l(typeof (msg)=="string"?arguments:msg);
msg="JsHttpRequest: "+msg;
if(!window.Error){
throw msg;
}else{
if((new Error(1,"test")).description=="test"){
throw new Error(1,msg);
}else{
throw new Error(msg);
}
}
};
t._hash2query=function(_1e,_1f,_20,_21){
if(_1f==null){
_1f="";
}
if((""+typeof (_1e)).toLowerCase()=="object"){
var _22=false;
if(_1e&&_1e.parentNode&&_1e.parentNode.appendChild&&_1e.tagName&&_1e.tagName.toUpperCase()=="FORM"){
_1e={form:_1e};
}
for(var k in _1e){
var v=_1e[k];
if(v instanceof Function){
continue;
}
var _25=_1f?_1f+"["+this.escape(k)+"]":this.escape(k);
var _26=v&&v.parentNode&&v.parentNode.appendChild&&v.tagName;
if(_26){
var tn=v.tagName.toUpperCase();
if(tn=="FORM"){
_22=true;
}else{
if(tn=="INPUT"||tn=="TEXTAREA"||tn=="SELECT"){
}else{
return this._error("inv_form_el",(v.name||""),v.tagName);
}
}
_21[_21.length]={name:_25,e:v};
}else{
if(v instanceof Object){
this._hash2query(v,_25,_20,_21);
}else{
if(v===null){
continue;
}
if(v===true){
v=1;
}
if(v===false){
v="";
}
_20[_20.length]=_25+"="+this.escape(""+v);
}
}
if(_22&&_21.length>1){
return this._error("must_be_single_el");
}
}
}else{
_20[_20.length]=_1e;
}
return true;
};
t._cleanup=function(){
var _28=this._ldObj;
if(!_28){
return;
}
JsHttpRequest.PENDING[_28.id]=false;
var _29=_28.span;
if(!_29){
return;
}
_28.span=null;
var _2a=function(){
_29.parentNode.removeChild(_29);
};
JsHttpRequest.setTimeout(_2a,50);
};
t._changeReadyState=function(s,_2c){
with(this){
if(_2c){
status=statusText=responseJS=null;
responseText="";
}
readyState=s;
if(onreadystatechange){
onreadystatechange();
}
}
};
t.escape=function(s){
return escape(s).replace(new RegExp("\\+","g"),"%2B");
};
}
JsHttpRequest.COUNT=0;
JsHttpRequest.MAX_URL_LEN=2000;
JsHttpRequest.CACHE={};
JsHttpRequest.PENDING={};
JsHttpRequest.LOADERS={};
JsHttpRequest._dummy=function(){
};
JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};
JsHttpRequest.setTimeout=function(_2e,dt){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;
if(typeof (_2e)=="string"){
id=window.JsHttpRequest_tmp(_2e,dt);
}else{
var id=null;
var _31=function(){
_2e();
delete JsHttpRequest.TIMEOUTS[id];
};
id=window.JsHttpRequest_tmp(_31,dt);
JsHttpRequest.TIMEOUTS[id]=_31;
}
window.JsHttpRequest_tmp=null;
return id;
};
JsHttpRequest.clearTimeout=function(id){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id];
var r=window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp=null;
return r;
};
JsHttpRequest.query=function(url,_35,_36,_37){
var req=new this();
req.caching=!_37;
req.onreadystatechange=function(){
if(req.readyState==4){
_36(req.responseJS,req.responseText);
}
};
req.open(null,url,true);
req.send(_35);
};
JsHttpRequest.dataReady=function(d){
var th=this.PENDING[d.id];
delete this.PENDING[d.id];
if(th){
th._dataReady(d.text,d.js);
}else{
if(th!==false){
throw "dataReady(): unknown pending id: "+d.id;
}
}
};
JsHttpRequest.extend=function(_3b,src){
for(var k in src){
_3b[k]=src[k];
}
};
JsHttpRequest.LOADERS.xml={loader:function(req){
JsHttpRequest.extend(req._errors,{xml_no:"Cannot use XMLHttpRequest or ActiveX loader: not supported",xml_no_diffdom:"Cannot use XMLHttpRequest to load data from different domain %",xml_no_headers:"Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly",xml_no_form_upl:"Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryElem.length){
return ["xml_no_form_upl"];
}
if(this.url.match(new RegExp("^([a-z]+://[^\\/]+)(.*)","i"))){
if(RegExp.$1.toLowerCase()!=document.location.protocol+"//"+document.location.hostname.toLowerCase()){
return ["xml_no_diffdom",RegExp.$1];
}
}
var xr=null;
if(window.XMLHttpRequest){
try{
xr=new XMLHttpRequest();
}
catch(e){
}
}else{
if(window.ActiveXObject){
try{
xr=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
if(!xr){
try{
xr=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
}
}
}
}
if(!xr){
return ["xml_no"];
}
var _40=window.ActiveXObject||xr.setRequestHeader;
if(!this.method){
this.method=_40&&this.queryText.length?"POST":"GET";
}
if(this.method=="GET"){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.queryText="";
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
}else{
if(this.method=="POST"&&!_40){
return ["xml_no_headers"];
}
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+(req.caching?"0":this.id)+"-xml";
var id=this.id;
xr.onreadystatechange=function(){
if(xr.readyState!=4){
return;
}
xr.onreadystatechange=JsHttpRequest._dummy;
req.status=null;
try{
req.status=xr.status;
req.responseText=xr.responseText;
}
catch(e){
}
if(!req.status){
return;
}
try{
eval("JsHttpRequest._tmp = function(id) { var d = "+req.responseText+"; d.id = id; JsHttpRequest.dataReady(d); }");
}
catch(e){
return req._error("js_invalid",req.responseText);
}
JsHttpRequest._tmp(id);
JsHttpRequest._tmp=null;
};
xr.open(this.method,this.url,true,this.username,this.password);
if(_40){
for(var i=0;i<req._reqHeaders.length;i++){
xr.setRequestHeader(req._reqHeaders[i][0],req._reqHeaders[i][1]);
}
xr.setRequestHeader("Content-Type","application/octet-stream");
}
xr.send(this.queryText);
this.span=null;
this.xr=xr;
return null;
};
this.getAllResponseHeaders=function(){
return this.xr.getAllResponseHeaders();
};
this.getResponseHeader=function(_43){
return this.xr.getResponseHeader(_43);
};
this.abort=function(){
this.xr.abort();
this.xr=null;
};
}};
JsHttpRequest.LOADERS.script={loader:function(req){
JsHttpRequest.extend(req._errors,{script_only_get:"Cannot use SCRIPT loader: it supports only GET method",script_no_form:"Cannot use SCRIPT loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+this.id+"-"+"script";
this.queryText="";
if(!this.method){
this.method="GET";
}
if(this.method!=="GET"){
return ["script_only_get"];
}
if(this.queryElem.length){
return ["script_no_form"];
}
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var th=this,d=document,s=null,b=d.body;
if(!window.opera){
this.span=s=d.createElement("SCRIPT");
var _49=function(){
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
b.insertBefore(s,b.lastChild);
};
}else{
this.span=s=d.createElement("SPAN");
s.style.display="none";
b.insertBefore(s,b.lastChild);
s.innerHTML="Workaround for IE.<s"+"cript></"+"script>";
var _49=function(){
s=s.getElementsByTagName("SCRIPT")[0];
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
};
}
JsHttpRequest.setTimeout(_49,10);
return null;
};
}};
JsHttpRequest.LOADERS.form={loader:function(req){
JsHttpRequest.extend(req._errors,{form_el_not_belong:"Element \"%\" does not belong to any form!",form_el_belong_diff:"Element \"%\" belongs to a different form. All elements must belong to the same form!",form_el_inv_enctype:"Attribute \"enctype\" of the form must be \"%\" (for IE), \"%\" given."});
this.load=function(){
var th=this;
if(!th.method){
th.method="POST";
}
th.url+=(th.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+th.id+"-"+"form";
if(th.method=="GET"){
if(th.queryText){
th.url+=(th.url.indexOf("?")>=0?"&":"?")+th.queryText;
}
if(th.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var p=th.url.split("?",2);
th.url=p[0];
th.queryText=p[1]||"";
}
var _4d=null;
var _4e=false;
if(th.queryElem.length){
if(th.queryElem[0].e.tagName.toUpperCase()=="FORM"){
_4d=th.queryElem[0].e;
_4e=true;
th.queryElem=[];
}else{
_4d=th.queryElem[0].e.form;
for(var i=0;i<th.queryElem.length;i++){
var e=th.queryElem[i].e;
if(!e.form){
return ["form_el_not_belong",e.name];
}
if(e.form!=_4d){
return ["form_el_belong_diff",e.name];
}
}
}
if(th.method=="POST"){
var _51="multipart/form-data";
var _52=(_4d.attributes.encType&&_4d.attributes.encType.nodeValue)||(_4d.attributes.enctype&&_4d.attributes.enctype.value)||_4d.enctype;
if(_52!=_51){
return ["form_el_inv_enctype",_51,_52];
}
}
}
var d=_4d&&(_4d.ownerDocument||_4d.document)||document;
var _54="jshr_i_"+th.id;
var s=th.span=d.createElement("DIV");
s.style.position="absolute";
s.style.display="none";
s.style.visibility="hidden";
s.innerHTML=(_4d?"":"<form"+(th.method=="POST"?" enctype=\"multipart/form-data\" method=\"post\"":"")+"></form>")+"<iframe name=\""+_54+"\" id=\""+_54+"\" style=\"width:0px; height:0px; overflow:hidden; border:none\"></iframe>";
if(!_4d){
_4d=th.span.firstChild;
}
d.body.insertBefore(s,d.body.lastChild);
var _56=function(e,_58){
var sv=[];
var _5a=e;
if(e.mergeAttributes){
var _5a=d.createElement("form");
_5a.mergeAttributes(e,false);
}
for(var i=0;i<_58.length;i++){
var k=_58[i][0],v=_58[i][1];
sv[sv.length]=[k,_5a.getAttribute(k)];
_5a.setAttribute(k,v);
}
if(e.mergeAttributes){
e.mergeAttributes(_5a,false);
}
return sv;
};
var _5e=function(){
top.JsHttpRequestGlobal=JsHttpRequest;
var _5f=[];
if(!_4e){
for(var i=0,n=_4d.elements.length;i<n;i++){
_5f[i]=_4d.elements[i].name;
_4d.elements[i].name="";
}
}
var qt=th.queryText.split("&");
for(var i=qt.length-1;i>=0;i--){
var _63=qt[i].split("=",2);
var e=d.createElement("INPUT");
e.type="hidden";
e.name=unescape(_63[0]);
e.value=_63[1]!=null?unescape(_63[1]):"";
_4d.appendChild(e);
}
for(var i=0;i<th.queryElem.length;i++){
th.queryElem[i].e.name=th.queryElem[i].name;
}
var sv=_56(_4d,[["action",th.url],["method",th.method],["onsubmit",null],["target",_54]]);
_4d.submit();
_56(_4d,sv);
for(var i=0;i<qt.length;i++){
_4d.lastChild.parentNode.removeChild(_4d.lastChild);
}
if(!_4e){
for(var i=0,n=_4d.elements.length;i<n;i++){
_4d.elements[i].name=_5f[i];
}
}
};
JsHttpRequest.setTimeout(_5e,100);
return null;
};
}};

View file

@ -0,0 +1,536 @@
<?php
/**
* JsHttpRequest: PHP backend for JavaScript DHTML loader.
* (C) Dmitry Koterov, http://en.dklab.ru
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* See http://www.gnu.org/copyleft/lesser.html
*
* Do not remove this comment if you want to use the script!
* Íå óäàëÿéòå äàííûé êîììåíòàðèé, åñëè âû õîòèòå èñïîëüçîâàòü ñêðèïò!
*
* This backend library also supports POST requests additionally to GET.
*
* @author Dmitry Koterov
* @version 5.x $Id$
*/
class JsHttpRequest
{
var $SCRIPT_ENCODING = "windows-1251";
var $SCRIPT_DECODE_MODE = '';
var $LOADER = null;
var $ID = null;
var $RESULT = null;
// Internal; uniq value.
var $_uniqHash;
// Magic number for display_error checking.
var $_magic = 14623;
// Previous display_errors value.
var $_prevDisplayErrors = null;
// Internal: response content-type depending on loader type.
var $_contentTypes = array(
"script" => "text/javascript",
"xml" => "text/plain", // In XMLHttpRequest mode we must return text/plain - stupid Opera 8.0. :(
"form" => "text/html",
"" => "text/plain", // for unknown loader
);
// Internal: conversion to UTF-8 JSON cancelled because of non-ascii key.
var $_toUtfFailed = false;
// Internal: list of characters 128...255 (for strpbrk() ASCII check).
var $_nonAsciiChars = '';
// Which Unicode conversion function is available?
var $_unicodeConvMethod = null;
// Emergency memory buffer to be freed on memory_limit error.
var $_emergBuffer = null;
/**
* Constructor.
*
* Create new JsHttpRequest backend object and attach it
* to script output buffer. As a result - script will always return
* correct JavaScript code, even in case of fatal errors.
*
* QUERY_STRING is in form of: PHPSESSID=<sid>&a=aaa&b=bbb&JsHttpRequest=<id>-<loader>
* where <id> is a request ID, <loader> is a loader name, <sid> - a session ID (if present),
* PHPSESSID - session parameter name (by default = "PHPSESSID").
*
* If an object is created WITHOUT an active AJAX query, it is simply marked as
* non-active. Use statuc method isActive() to check.
*/
function JsHttpRequest($enc)
{
global $JsHttpRequest_Active;
// To be on a safe side - do not allow to drop reference counter on ob processing.
$GLOBALS['_RESULT'] =& $this->RESULT;
// Parse QUERY_STRING.
if (preg_match('/^(.*)(?:&|^)JsHttpRequest=(?:(\d+)-)?([^&]+)((?:&|$).*)$/s', @$_SERVER['QUERY_STRING'], $m)) {
$this->ID = $m[2];
$this->LOADER = strtolower($m[3]);
$_SERVER['QUERY_STRING'] = preg_replace('/^&+|&+$/s', '', preg_replace('/(^|&)'.session_name().'=[^&]*&?/s', '&', $m[1] . $m[4]));
unset(
$_GET['JsHttpRequest'],
$_REQUEST['JsHttpRequest'],
$_GET[session_name()],
$_POST[session_name()],
$_REQUEST[session_name()]
);
// Detect Unicode conversion method.
$this->_unicodeConvMethod = function_exists('mb_convert_encoding')? 'mb' : (function_exists('iconv')? 'iconv' : null);
// Fill an emergency buffer. We erase it at the first line of OB processor
// to free some memory. This memory may be used on memory_limit error.
$this->_emergBuffer = str_repeat('a', 1024 * 200);
// Intercept fatal errors via display_errors (seems it is the only way).
$this->_uniqHash = md5('JsHttpRequest' . microtime() . getmypid());
$this->_prevDisplayErrors = ini_get('display_errors');
ini_set('display_errors', $this->_magic); //
ini_set('error_prepend_string', $this->_uniqHash . ini_get('error_prepend_string'));
ini_set('error_append_string', ini_get('error_append_string') . $this->_uniqHash);
if (function_exists('xdebug_disable')) xdebug_disable(); // else Fatal errors are not catched
// Start OB handling early.
ob_start(array(&$this, "_obHandler"));
$JsHttpRequest_Active = true;
// Set up the encoding.
$this->setEncoding($enc);
// Check if headers are already sent (see Content-Type library usage).
// If true - generate a debug message and exit.
$file = $line = null;
$headersSent = version_compare(PHP_VERSION, "4.3.0") < 0? headers_sent() : headers_sent($file, $line);
if ($headersSent) {
trigger_error(
"HTTP headers are already sent" . ($line !== null? " in $file on line $line" : " somewhere in the script") . ". "
. "Possibly you have an extra space (or a newline) before the first line of the script or any library. "
. "Please note that JsHttpRequest uses its own Content-Type header and fails if "
. "this header cannot be set. See header() function documentation for more details",
E_USER_ERROR
);
exit();
}
} else {
$this->ID = 0;
$this->LOADER = 'unknown';
$JsHttpRequest_Active = false;
}
}
/**
* Static function.
* Returns true if JsHttpRequest output processor is currently active.
*
* @return boolean True if the library is active, false otherwise.
*/
function isActive()
{
return !empty($GLOBALS['JsHttpRequest_Active']);
}
/**
* string getJsCode()
*
* Return JavaScript part of the library.
*/
function getJsCode()
{
return file_get_contents(dirname(__FILE__) . '/JsHttpRequest.js');
}
/**
* void setEncoding(string $encoding)
*
* Set an active script encoding & correct QUERY_STRING according to it.
* Examples:
* "windows-1251" - set plain encoding (non-windows characters,
* e.g. hieroglyphs, are totally ignored)
* "windows-1251 entities" - set windows encoding, BUT additionally replace:
* "&" -> "&amp;"
* hieroglyph -> &#XXXX; entity
*/
function setEncoding($enc)
{
// Parse an encoding.
preg_match('/^(\S*)(?:\s+(\S*))$/', $enc, $p);
$this->SCRIPT_ENCODING = strtolower(!empty($p[1])? $p[1] : $enc);
$this->SCRIPT_DECODE_MODE = !empty($p[2])? $p[2] : '';
// Manually parse QUERY_STRING because of damned Unicode's %uXXXX.
$this->_correctSuperglobals();
}
/**
* string quoteInput(string $input)
*
* Quote a string according to the input decoding mode.
* If entities are used (see setEncoding()), no '&' character is quoted,
* only '"', '>' and '<' (we presume that '&' is already quoted by
* an input reader function).
*
* Use this function INSTEAD of htmlspecialchars() for $_GET data
* in your scripts.
*/
function quoteInput($s)
{
if ($this->SCRIPT_DECODE_MODE == 'entities')
return str_replace(array('"', '<', '>'), array('&quot;', '&lt;', '&gt;'), $s);
else
return htmlspecialchars($s);
}
/**
* Convert a PHP scalar, array or hash to JS scalar/array/hash. This function is
* an analog of json_encode(), but it can work with a non-UTF8 input and does not
* analyze the passed data. Output format must be fully JSON compatible.
*
* @param mixed $a Any structure to convert to JS.
* @return string JavaScript equivalent structure.
*/
function php2js($a=false)
{
if (is_null($a)) return 'null';
if ($a === false) return 'false';
if ($a === true) return 'true';
if (is_scalar($a)) {
if (is_float($a)) {
// Always use "." for floats.
$a = str_replace(",", ".", strval($a));
}
// All scalars are converted to strings to avoid indeterminism.
// PHP's "1" and 1 are equal for all PHP operators, but
// JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
// we should get the same result in the JS frontend (string).
// Character replacements for JSON.
static $jsonReplaces = array(
array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')
);
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
}
$isList = true;
for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
if (key($a) !== $i) {
$isList = false;
break;
}
}
$result = array();
if ($isList) {
foreach ($a as $v) {
$result[] = JsHttpRequest::php2js($v);
}
return '[ ' . join(', ', $result) . ' ]';
} else {
foreach ($a as $k => $v) {
$result[] = JsHttpRequest::php2js($k) . ': ' . JsHttpRequest::php2js($v);
}
return '{ ' . join(', ', $result) . ' }';
}
}
/**
* Internal methods.
*/
/**
* Parse & decode QUERY_STRING.
*/
function _correctSuperglobals()
{
// In case of FORM loader we may go to nirvana, everything is already parsed by PHP.
if ($this->LOADER == 'form') return;
// ATTENTION!!!
// HTTP_RAW_POST_DATA is only accessible when Content-Type of POST request
// is NOT default "application/x-www-form-urlencoded"!!!
// Library frontend sets "application/octet-stream" for that purpose,
// see JavaScript code. In PHP 5.2.2.HTTP_RAW_POST_DATA is not set sometimes;
// in such cases - read the POST data manually from the STDIN stream.
$rawPost = strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') == 0? (isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : @file_get_contents("php://input")) : null;
$source = array(
'_GET' => !empty($_SERVER['QUERY_STRING'])? $_SERVER['QUERY_STRING'] : null,
'_POST'=> $rawPost,
);
foreach ($source as $dst=>$src) {
// First correct all 2-byte entities.
$s = preg_replace('/%(?!5B)(?!5D)([0-9a-f]{2})/si', '%u00\\1', $src);
// Now we can use standard parse_str() with no worry!
$data = null;
parse_str($s, $data);
$GLOBALS[$dst] = $this->_ucs2EntitiesDecode($data);
}
$GLOBALS['HTTP_GET_VARS'] = $_GET; // deprecated vars
$GLOBALS['HTTP_POST_VARS'] = $_POST;
$_REQUEST =
(isset($_COOKIE)? $_COOKIE : array()) +
(isset($_POST)? $_POST : array()) +
(isset($_GET)? $_GET : array());
if (ini_get('register_globals')) {
// TODO?
}
}
/**
* Called in case of error too!
*/
function _obHandler($text)
{
unset($this->_emergBuffer); // free a piece of memory for memory_limit error
unset($GLOBALS['JsHttpRequest_Active']);
// Check for error & fetch a resulting data.
if (preg_match("/{$this->_uniqHash}(.*?){$this->_uniqHash}/sx", $text, $m)) {
if (!ini_get('display_errors') || (!$this->_prevDisplayErrors && ini_get('display_errors') == $this->_magic)) {
// Display_errors:
// 1. disabled manually after the library initialization, or
// 2. was initially disabled and is not changed
$text = str_replace($m[0], '', $text); // strip whole error message
} else {
$text = str_replace($this->_uniqHash, '', $text);
}
}
// $f = fopen('/a', 'w'); fwrite($f, "{$text}\n{$this->_uniqHash}"); fclose($f);
if ($m && preg_match('/\bFatal error(<.*?>)?:/i', $m[1])) {
// On fatal errors - force null result (generate 500 error).
$this->RESULT = null;
} else {
// Make a resulting hash.
if (!isset($this->RESULT)) {
global $_RESULT;
$this->RESULT = $_RESULT;
}
}
$result = array(
'id' => $this->ID,
'js' => $this->RESULT,
'text' => $text,
);
$text = null;
$encoding = $this->SCRIPT_ENCODING;
$status = $this->RESULT !== null? 200 : 500;
// Try to use very fast json_encode: 3-4 times faster than a manual encoding.
if (function_exists('array_walk_recursive') && function_exists('json_encode') && $this->_unicodeConvMethod) {
$this->_nonAsciiChars = join("", array_map('chr', range(128, 255)));
$this->_toUtfFailed = false;
$resultUtf8 = $result;
array_walk_recursive($resultUtf8, array(&$this, '_toUtf8_callback'), $this->SCRIPT_ENCODING);
if (!$this->_toUtfFailed) {
// If some key contains non-ASCII character, convert everything manually.
$text = json_encode($resultUtf8);
$encoding = "UTF-8";
}
}
// On failure, use manual encoding.
if ($text === null) {
$text = $this->php2js($result);
}
if ($this->LOADER != "xml") {
// In non-XML mode we cannot use plain JSON. So - wrap with JS function call.
// If top.JsHttpRequestGlobal is not defined, loading is aborted and
// iframe is removed, so - do not call dataReady().
$text = ""
. ($this->LOADER == "form"? 'top && top.JsHttpRequestGlobal && top.JsHttpRequestGlobal' : 'JsHttpRequest')
. ".dataReady(" . $text . ")\n"
. "";
if ($this->LOADER == "form") {
$text = '<script type="text/javascript" language="JavaScript"><!--' . "\n$text" . '//--></script>';
}
// Always return 200 code in non-XML mode (else SCRIPT does not work in FF).
// For XML mode, 500 code is okay.
$status = 200;
}
// Status header. To be safe, display it only in error mode. In case of success
// termination, do not modify the status (""HTTP/1.1 ..." header seems to be not
// too cross-platform).
if ($this->RESULT === null) {
if (php_sapi_name() == "cgi") {
header("Status: $status");
} else {
header("HTTP/1.1 $status");
}
}
// In XMLHttpRequest mode we must return text/plain - damned stupid Opera 8.0. :(
$ctype = !empty($this->_contentTypes[$this->LOADER])? $this->_contentTypes[$this->LOADER] : $this->_contentTypes[''];
header("Content-type: $ctype; charset=$encoding");
return $text;
}
/**
* Internal function, used in array_walk_recursive() before json_encode() call.
* If a key contains non-ASCII characters, this function sets $this->_toUtfFailed = true,
* becaues array_walk_recursive() cannot modify array keys.
*/
function _toUtf8_callback(&$v, $k, $fromEnc)
{
if ($v === null || is_bool($v)) return;
if ($this->_toUtfFailed || !is_scalar($v) || strpbrk($k, $this->_nonAsciiChars) !== false) {
$this->_toUtfFailed = true;
} else {
$v = $this->_unicodeConv($fromEnc, 'UTF-8', $v);
}
}
/**
* Decode all %uXXXX entities in string or array (recurrent).
* String must not contain %XX entities - they are ignored!
*/
function _ucs2EntitiesDecode($data)
{
if (is_array($data)) {
$d = array();
foreach ($data as $k=>$v) {
$d[$this->_ucs2EntitiesDecode($k)] = $this->_ucs2EntitiesDecode($v);
}
return $d;
} else {
if (strpos($data, '%u') !== false) { // improve speed
$data = preg_replace_callback('/%u([0-9A-F]{1,4})/si', array(&$this, '_ucs2EntitiesDecodeCallback'), $data);
}
return $data;
}
}
/**
* Decode one %uXXXX entity (RE callback).
*/
function _ucs2EntitiesDecodeCallback($p)
{
$hex = $p[1];
$dec = hexdec($hex);
if ($dec === "38" && $this->SCRIPT_DECODE_MODE == 'entities') {
// Process "&" separately in "entities" decode mode.
$c = "&amp;";
} else {
if ($this->_unicodeConvMethod) {
$c = @$this->_unicodeConv('UCS-2BE', $this->SCRIPT_ENCODING, pack('n', $dec));
} else {
$c = $this->_decUcs2Decode($dec, $this->SCRIPT_ENCODING);
}
if (!strlen($c)) {
if ($this->SCRIPT_DECODE_MODE == 'entities') {
$c = '&#' . $dec . ';';
} else {
$c = '?';
}
}
}
return $c;
}
/**
* Wrapper for iconv() or mb_convert_encoding() functions.
* This function will generate fatal error if none of these functons available!
*
* @see iconv()
*/
function _unicodeConv($fromEnc, $toEnc, $v)
{
if ($this->_unicodeConvMethod == 'iconv') {
return iconv($fromEnc, $toEnc, $v);
}
return mb_convert_encoding($v, $toEnc, $fromEnc);
}
/**
* If there is no ICONV, try to decode 1-byte characters and UTF-8 manually
* (for most popular charsets only).
*/
/**
* Convert from UCS-2BE decimal to $toEnc.
*/
function _decUcs2Decode($code, $toEnc)
{
// Little speedup by using array_flip($this->_encTables) and later hash access.
static $flippedTable = null;
if ($code < 128) return chr($code);
if (isset($this->_encTables[$toEnc])) {
if (!$flippedTable) $flippedTable = array_flip($this->_encTables[$toEnc]);
if (isset($flippedTable[$code])) return chr(128 + $flippedTable[$code]);
} else if ($toEnc == 'utf-8' || $toEnc == 'utf8') {
// UTF-8 conversion rules: http://www.cl.cam.ac.uk/~mgk25/unicode.html
if ($code < 0x800) {
return chr(0xC0 + ($code >> 6)) .
chr(0x80 + ($code & 0x3F));
} else { // if ($code <= 0xFFFF) -- it is almost always so for UCS2-BE
return chr(0xE0 + ($code >> 12)) .
chr(0x80 + (0x3F & ($code >> 6))) .
chr(0x80 + ($code & 0x3F));
}
}
return "";
}
/**
* UCS-2BE -> 1-byte encodings (from #128).
*/
var $_encTables = array(
'windows-1251' => array(
0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021,
0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F,
0x0452, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
0x0098, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F,
0x00A0, 0x040E, 0x045E, 0x0408, 0x00A4, 0x0490, 0x00A6, 0x00A7,
0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407,
0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, 0x00B6, 0x00B7,
0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457,
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F,
0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F,
0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F,
0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F,
),
'koi8-r' => array(
0x2500, 0x2502, 0x250C, 0x2510, 0x2514, 0x2518, 0x251C, 0x2524,
0x252C, 0x2534, 0x253C, 0x2580, 0x2584, 0x2588, 0x258C, 0x2590,
0x2591, 0x2592, 0x2593, 0x2320, 0x25A0, 0x2219, 0x221A, 0x2248,
0x2264, 0x2265, 0x00A0, 0x2321, 0x00B0, 0x00B2, 0x00B7, 0x00F7,
0x2550, 0x2551, 0x2552, 0x0451, 0x2553, 0x2554, 0x2555, 0x2556,
0x2557, 0x2558, 0x2559, 0x255A, 0x255B, 0x255C, 0x255d, 0x255E,
0x255F, 0x2560, 0x2561, 0x0401, 0x2562, 0x2563, 0x2564, 0x2565,
0x2566, 0x2567, 0x2568, 0x2569, 0x256A, 0x256B, 0x256C, 0x00A9,
0x044E, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433,
0x0445, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043d, 0x043E,
0x043F, 0x044F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432,
0x044C, 0x044B, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044A,
0x042E, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413,
0x0425, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041d, 0x041E,
0x041F, 0x042F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412,
0x042C, 0x042B, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042A
),
);
}

View file

@ -0,0 +1,54 @@
@echo off
perl -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
exit;
#!perl -w
#line 6
#########################################################################
my $debugDir = "debug";
my $miniDir = "mini";
my $orig = "$debugDir/JsHttpRequest.js";
my $minProg = "C:/Program Files/DojoMin/dojomin.bat";
my $source = readFile($orig);
my ($comment) = $source =~ m{^\s*(/\*.*?\*/)}s;
my %parts = reverse($source =~ m[(//\s*{{{ [ \t]* (\w*) .*? //[ \t]* }}})]sgx);
my $main = $parts{''}; delete $parts{''};
$parts{'script-xml'} = $parts{script} . "\n\n" . $parts{xml};
while (my ($k, $v) = each %parts) {
my $fname = "JsHttpRequest-$k.js";
my $newComment = $comment;
$newComment =~ s/\*\s*\w+[^\r\n]*/$& ($k support only!)/s;
writeFile($debugDir . '/' . $fname, $newComment . "\n" . $main . "\n\n" . $v);
minify($debugDir . '/' . $fname, $miniDir . '/' . $fname);
}
minify($orig, "JsHttpRequest.js");
minify($orig, $miniDir . "/JsHttpRequest.js");
sub minify {
my ($from, $to, $commentAdd) = @_;
my ($comment) = readFile($from) =~ m{^\s*(/\*.*?\*/)}s;
$comment =~ s/\*\s*\w+[^\r\n]*\s*\*/$& Minimized version: see debug directory for the complete one.\n */s;
system("\"$minProg\" $from > $to");
writeFile($to, $comment . "\n" . readFile($to));
}
sub readFile {
my ($name) = @_;
local $/;
open(local *F, $name);
return <F>;
}
sub writeFile {
my ($name, $data) = @_;
local $/;
open(local *F, ">", $name);
print F $data;
}

View file

@ -0,0 +1,611 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (form support only!)
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
// {{{
function JsHttpRequest() {
// Standard properties.
var t = this;
t.onreadystatechange = null;
t.readyState = 0;
t.responseText = null;
t.responseXML = null;
t.status = 200;
t.statusText = "OK";
// JavaScript response array/hash
t.responseJS = null;
// Additional properties.
t.caching = false; // need to use caching?
t.loader = null; // loader to use ('form', 'script', 'xml'; null - autodetect)
t.session_name = "PHPSESSID"; // set to SID cookie or GET parameter name
// Internals.
t._ldObj = null; // used loader object
t._reqHeaders = []; // collected request headers
t._openArgs = null; // parameters from open()
t._errors = {
inv_form_el: 'Invalid FORM element detected: name=%, tag=%',
must_be_single_el: 'If used, <form> must be a single HTML element in the list.',
js_invalid: 'JavaScript code generated by backend is invalid!\n%',
url_too_long: 'Cannot use so long query with GET request (URL is larger than % bytes)',
unk_loader: 'Unknown loader: %',
no_loaders: 'No loaders registered at all, please check JsHttpRequest.LOADERS array',
no_loader_matched: 'Cannot find a loader which may process the request. Notices are:\n%'
}
/**
* Aborts the request. Behaviour of this function for onreadystatechange()
* is identical to IE (most universal and common case). E.g., readyState -> 4
* on abort() after send().
*/
t.abort = function() { with (this) {
if (_ldObj && _ldObj.abort) _ldObj.abort();
_cleanup();
if (readyState == 0) {
// start->abort: no change of readyState (IE behaviour)
return;
}
if (readyState == 1 && !_ldObj) {
// open->abort: no onreadystatechange call, but change readyState to 0 (IE).
// send->abort: change state to 4 (_ldObj is not null when send() is called)
readyState = 0;
return;
}
_changeReadyState(4, true); // 4 in IE & FF on abort() call; Opera does not change to 4.
}}
/**
* Prepares the object for data loading.
* You may also pass URLs like "GET url" or "script.GET url".
*/
t.open = function(method, url, asyncFlag, username, password) { with (this) {
// Extract methor and loader from the URL (if present).
if (url.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)) {
this.loader = RegExp.$2? RegExp.$2 : null;
method = RegExp.$3;
url = RegExp.$4;
}
// Append SID to original URL. Use try...catch for security problems.
try {
if (
document.location.search.match(new RegExp('[&?]' + session_name + '=([^&?]*)'))
|| document.cookie.match(new RegExp('(?:;|^)\\s*' + session_name + '=([^;]*)'))
) {
url += (url.indexOf('?') >= 0? '&' : '?') + session_name + "=" + this.escape(RegExp.$1);
}
} catch (e) {}
// Store open arguments to hash.
_openArgs = {
method: (method || '').toUpperCase(),
url: url,
asyncFlag: asyncFlag,
username: username != null? username : '',
password: password != null? password : ''
}
_ldObj = null;
_changeReadyState(1, true); // compatibility with XMLHttpRequest
return true;
}}
/**
* Sends a request to a server.
*/
t.send = function(content) {
if (!this.readyState) {
// send without open or after abort: no action (IE behaviour).
return;
}
this._changeReadyState(1, true); // compatibility with XMLHttpRequest
this._ldObj = null;
// Prepare to build QUERY_STRING from query hash.
var queryText = [];
var queryElem = [];
if (!this._hash2query(content, null, queryText, queryElem)) return;
// Solve the query hashcode & return on cache hit.
var hash = null;
if (this.caching && !queryElem.length) {
hash = this._openArgs.username + ':' + this._openArgs.password + '@' + this._openArgs.url + '|' + queryText + "#" + this._openArgs.method;
var cache = JsHttpRequest.CACHE[hash];
if (cache) {
this._dataReady(cache[0], cache[1]);
return false;
}
}
// Try all the loaders.
var loader = (this.loader || '').toLowerCase();
if (loader && !JsHttpRequest.LOADERS[loader]) return this._error('unk_loader', loader);
var errors = [];
var lds = JsHttpRequest.LOADERS;
for (var tryLoader in lds) {
var ldr = lds[tryLoader].loader;
if (!ldr) continue; // exclude possibly derived prototype properties from "for .. in".
if (loader && tryLoader != loader) continue;
// Create sending context.
var ldObj = new ldr(this);
JsHttpRequest.extend(ldObj, this._openArgs);
JsHttpRequest.extend(ldObj, {
queryText: queryText.join('&'),
queryElem: queryElem,
id: (new Date().getTime()) + "" + JsHttpRequest.COUNT++,
hash: hash,
span: null
});
var error = ldObj.load();
if (!error) {
// Save loading script.
this._ldObj = ldObj;
JsHttpRequest.PENDING[ldObj.id] = this;
return true;
}
if (!loader) {
errors[errors.length] = '- ' + tryLoader.toUpperCase() + ': ' + this._l(error);
} else {
return this._error(error);
}
}
// If no loader matched, generate error message.
return tryLoader? this._error('no_loader_matched', errors.join('\n')) : this._error('no_loaders');
}
/**
* Returns all response headers (if supported).
*/
t.getAllResponseHeaders = function() { with (this) {
return _ldObj && _ldObj.getAllResponseHeaders? _ldObj.getAllResponseHeaders() : [];
}}
/**
* Returns one response header (if supported).
*/
t.getResponseHeader = function(label) { with (this) {
return _ldObj && _ldObj.getResponseHeader? _ldObj.getResponseHeader(label) : null;
}}
/**
* Adds a request header to a future query.
*/
t.setRequestHeader = function(label, value) { with (this) {
_reqHeaders[_reqHeaders.length] = [label, value];
}}
//
// Internal functions.
//
/**
* Do all the work when a data is ready.
*/
t._dataReady = function(text, js) { with (this) {
if (caching && _ldObj) JsHttpRequest.CACHE[_ldObj.hash] = [text, js];
responseText = responseXML = text;
responseJS = js;
if (js !== null) {
status = 200;
statusText = "OK";
} else {
status = 500;
statusText = "Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}}
/**
* Analog of sprintf(), but translates the first parameter by _errors.
*/
t._l = function(args) {
var i = 0, p = 0, msg = this._errors[args[0]];
// Cannot use replace() with a callback, because it is incompatible with IE5.
while ((p = msg.indexOf('%', p)) >= 0) {
var a = args[++i] + "";
msg = msg.substring(0, p) + a + msg.substring(p + 1, msg.length);
p += 1 + a.length;
}
return msg;
}
/**
* Called on error.
*/
t._error = function(msg) {
msg = this._l(typeof(msg) == 'string'? arguments : msg)
msg = "JsHttpRequest: " + msg;
if (!window.Error) {
// Very old browser...
throw msg;
} else if ((new Error(1, 'test')).description == "test") {
// We MUST (!!!) pass 2 parameters to the Error() constructor for IE5.
throw new Error(1, msg);
} else {
// Mozilla does not support two-parameter call style.
throw new Error(msg);
}
}
/**
* Convert hash to QUERY_STRING.
* If next value is scalar or hash, push it to queryText.
* If next value is form element, push [name, element] to queryElem.
*/
t._hash2query = function(content, prefix, queryText, queryElem) {
if (prefix == null) prefix = "";
if((''+typeof(content)).toLowerCase() == 'object') {
var formAdded = false;
if (content && content.parentNode && content.parentNode.appendChild && content.tagName && content.tagName.toUpperCase() == 'FORM') {
content = { form: content };
}
for (var k in content) {
var v = content[k];
if (v instanceof Function) continue;
var curPrefix = prefix? prefix + '[' + this.escape(k) + ']' : this.escape(k);
var isFormElement = v && v.parentNode && v.parentNode.appendChild && v.tagName;
if (isFormElement) {
var tn = v.tagName.toUpperCase();
if (tn == 'FORM') {
// FORM itself is passed.
formAdded = true;
} else if (tn == 'INPUT' || tn == 'TEXTAREA' || tn == 'SELECT') {
// This is a single form elemenent.
} else {
return this._error('inv_form_el', (v.name||''), v.tagName);
}
queryElem[queryElem.length] = { name: curPrefix, e: v };
} else if (v instanceof Object) {
this._hash2query(v, curPrefix, queryText, queryElem);
} else {
// We MUST skip NULL values, because there is no method
// to pass NULL's via GET or POST request in PHP.
if (v === null) continue;
// Convert JS boolean true and false to corresponding PHP values.
if (v === true) v = 1;
if (v === false) v = '';
queryText[queryText.length] = curPrefix + "=" + this.escape('' + v);
}
if (formAdded && queryElem.length > 1) {
return this._error('must_be_single_el');
}
}
} else {
queryText[queryText.length] = content;
}
return true;
}
/**
* Remove last used script element (clean memory).
*/
t._cleanup = function() {
var ldObj = this._ldObj;
if (!ldObj) return;
// Mark this loading as aborted.
JsHttpRequest.PENDING[ldObj.id] = false;
var span = ldObj.span;
if (!span) return;
// Do NOT use iframe.contentWindow.back() - it is incompatible with Opera 9!
ldObj.span = null;
var closure = function() {
span.parentNode.removeChild(span);
}
// IE5 crashes on setTimeout(function() {...}, ...) construction! Use tmp variable.
JsHttpRequest.setTimeout(closure, 50);
}
/**
* Change current readyState and call trigger method.
*/
t._changeReadyState = function(s, reset) { with (this) {
if (reset) {
status = statusText = responseJS = null;
responseText = '';
}
readyState = s;
if (onreadystatechange) onreadystatechange();
}}
/**
* JS escape() does not quote '+'.
*/
t.escape = function(s) {
return escape(s).replace(new RegExp('\\+','g'), '%2B');
}
}
// Global library variables.
JsHttpRequest.COUNT = 0; // unique ID; used while loading IDs generation
JsHttpRequest.MAX_URL_LEN = 2000; // maximum URL length
JsHttpRequest.CACHE = {}; // cached data
JsHttpRequest.PENDING = {}; // pending loadings
JsHttpRequest.LOADERS = {}; // list of supported data loaders (filled at the bottom of the file)
JsHttpRequest._dummy = function() {}; // avoid memory leaks
/**
* These functions are dirty hacks for IE 5.0 which does not increment a
* reference counter for an object passed via setTimeout(). So, if this
* object (closure function) is out of scope at the moment of timeout
* applying, IE 5.0 crashes.
*/
/**
* Timeout wrappers storage. Used to avoid zeroing of referece counts in IE 5.0.
* Please note that you MUST write "window.setTimeout", not "setTimeout", else
* IE 5.0 crashes again. Strange, very strange...
*/
JsHttpRequest.TIMEOUTS = { s: window.setTimeout, c: window.clearTimeout };
/**
* Wrapper for IE5 buggy setTimeout.
* Use this function instead of a usual setTimeout().
*/
JsHttpRequest.setTimeout = function(func, dt) {
// Always save inside the window object before a call (for FF)!
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.s;
if (typeof(func) == "string") {
id = window.JsHttpRequest_tmp(func, dt);
} else {
var id = null;
var mediator = function() {
func();
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
}
id = window.JsHttpRequest_tmp(mediator, dt);
// Store a reference to the mediator function to the global array
// (reference count >= 1); use timeout ID as an array key;
JsHttpRequest.TIMEOUTS[id] = mediator;
}
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return id;
}
/**
* Complimental wrapper for clearTimeout.
* Use this function instead of usual clearTimeout().
*/
JsHttpRequest.clearTimeout = function(id) {
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
var r = window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return r;
}
/**
* Global static function.
* Simple interface for most popular use-cases.
* You may also pass URLs like "GET url" or "script.GET url".
*/
JsHttpRequest.query = function(url, content, onready, nocache) {
var req = new this();
req.caching = !nocache;
req.onreadystatechange = function() {
if (req.readyState == 4) {
onready(req.responseJS, req.responseText);
}
}
req.open(null, url, true);
req.send(content);
}
/**
* Global static function.
* Called by server backend script on data load.
*/
JsHttpRequest.dataReady = function(d) {
var th = this.PENDING[d.id];
delete this.PENDING[d.id];
if (th) {
th._dataReady(d.text, d.js);
} else if (th !== false) {
throw "dataReady(): unknown pending id: " + d.id;
}
}
// Adds all the properties of src to dest.
JsHttpRequest.extend = function(dest, src) {
for (var k in src) dest[k] = src[k];
}
/**
* Each loader has the following properties which must be initialized:
* - method
* - url
* - asyncFlag (ignored)
* - username
* - password
* - queryText (string)
* - queryElem (array)
* - id
* - hash
* - span
*/
// }}}
// {{{ form
// Loader: FORM & IFRAME.
// [+] Supports file uploading.
// [+] GET and POST methods are supported.
// [+] Supports loading from different domains.
// [-] Uses a lot of system resources.
// [-] Backend data cannot be browser-cached.
// [-] Pollutes browser history on some old browsers.
//
JsHttpRequest.LOADERS.form = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
form_el_not_belong: 'Element "%" does not belong to any form!',
form_el_belong_diff: 'Element "%" belongs to a different form. All elements must belong to the same form!',
form_el_inv_enctype: 'Attribute "enctype" of the form must be "%" (for IE), "%" given.'
})
this.load = function() {
var th = this;
if (!th.method) th.method = 'POST';
th.url += (th.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + th.id + '-' + 'form';
// If GET, build full URL. Then copy QUERY_STRING to queryText.
if (th.method == 'GET') {
if (th.queryText) th.url += (th.url.indexOf('?') >= 0? '&' : '?') + th.queryText;
if (th.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
var p = th.url.split('?', 2);
th.url = p[0];
th.queryText = p[1] || '';
}
// Check if all form elements belong to same form.
var form = null;
var wholeFormSending = false;
if (th.queryElem.length) {
if (th.queryElem[0].e.tagName.toUpperCase() == 'FORM') {
// Whole FORM sending.
form = th.queryElem[0].e;
wholeFormSending = true;
th.queryElem = [];
} else {
// If we have at least one form element, we use its FORM as a POST container.
form = th.queryElem[0].e.form;
// Validate all the elements.
for (var i = 0; i < th.queryElem.length; i++) {
var e = th.queryElem[i].e;
if (!e.form) {
return ['form_el_not_belong', e.name];
}
if (e.form != form) {
return ['form_el_belong_diff', e.name];
}
}
}
// Check enctype of the form.
if (th.method == 'POST') {
var need = "multipart/form-data";
var given = (form.attributes.encType && form.attributes.encType.nodeValue) || (form.attributes.enctype && form.attributes.enctype.value) || form.enctype;
if (given != need) {
return ['form_el_inv_enctype', need, given];
}
}
}
// Create invisible IFRAME with temporary form (form is used on empty queryElem).
// We ALWAYS create th IFRAME in the document of the form - for Opera 7.20.
var d = form && (form.ownerDocument || form.document) || document;
var ifname = 'jshr_i_' + th.id;
var s = th.span = d.createElement('DIV');
s.style.position = 'absolute';
s.style.display = 'none';
s.style.visibility = 'hidden';
s.innerHTML =
(form? '' : '<form' + (th.method == 'POST'? ' enctype="multipart/form-data" method="post"' : '') + '></form>') + // stupid IE, MUST use innerHTML assignment :-(
'<iframe name="' + ifname + '" id="' + ifname + '" style="width:0px; height:0px; overflow:hidden; border:none"></iframe>'
if (!form) {
form = th.span.firstChild;
}
// Insert generated form inside the document.
// Be careful: don't forget to close FORM container in document body!
d.body.insertBefore(s, d.body.lastChild);
// Function to safely set the form attributes. Parameter attr is NOT a hash
// but an array, because "for ... in" may badly iterate over derived attributes.
var setAttributes = function(e, attr) {
var sv = [];
var form = e;
// This strange algorythm is needed, because form may contain element
// with name like 'action'. In IE for such attribute will be returned
// form element node, not form action. Workaround: copy all attributes
// to new empty form and work with it, then copy them back. This is
// THE ONLY working algorythm since a lot of bugs in IE5.0 (e.g.
// with e.attributes property: causes IE crash).
if (e.mergeAttributes) {
var form = d.createElement('form');
form.mergeAttributes(e, false);
}
for (var i = 0; i < attr.length; i++) {
var k = attr[i][0], v = attr[i][1];
// TODO: http://forum.dklab.ru/viewtopic.php?p=129059#129059
sv[sv.length] = [k, form.getAttribute(k)];
form.setAttribute(k, v);
}
if (e.mergeAttributes) {
e.mergeAttributes(form, false);
}
return sv;
}
// Run submit with delay - for old Opera: it needs some time to create IFRAME.
var closure = function() {
// Save JsHttpRequest object to new IFRAME.
top.JsHttpRequestGlobal = JsHttpRequest;
// Disable ALL the form elements.
var savedNames = [];
if (!wholeFormSending) {
for (var i = 0, n = form.elements.length; i < n; i++) {
savedNames[i] = form.elements[i].name;
form.elements[i].name = '';
}
}
// Insert hidden fields to the form.
var qt = th.queryText.split('&');
for (var i = qt.length - 1; i >= 0; i--) {
var pair = qt[i].split('=', 2);
var e = d.createElement('INPUT');
e.type = 'hidden';
e.name = unescape(pair[0]);
e.value = pair[1] != null? unescape(pair[1]) : '';
form.appendChild(e);
}
// Change names of along user-passed form elements.
for (var i = 0; i < th.queryElem.length; i++) {
th.queryElem[i].e.name = th.queryElem[i].name;
}
// Temporary modify form attributes, submit form, restore attributes back.
var sv = setAttributes(
form,
[
['action', th.url],
['method', th.method],
['onsubmit', null],
['target', ifname]
]
);
form.submit();
setAttributes(form, sv);
// Remove generated temporary hidden elements from the top of the form.
for (var i = 0; i < qt.length; i++) {
// Use "form.firstChild.parentNode", not "form", or IE5 crashes!
form.lastChild.parentNode.removeChild(form.lastChild);
}
// Enable all disabled elements back.
if (!wholeFormSending) {
for (var i = 0, n = form.elements.length; i < n; i++) {
form.elements[i].name = savedNames[i];
}
}
}
JsHttpRequest.setTimeout(closure, 100);
// Success.
return null;
}
}}
// }}}

View file

@ -0,0 +1,619 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (script-xml support only!)
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
// {{{
function JsHttpRequest() {
// Standard properties.
var t = this;
t.onreadystatechange = null;
t.readyState = 0;
t.responseText = null;
t.responseXML = null;
t.status = 200;
t.statusText = "OK";
// JavaScript response array/hash
t.responseJS = null;
// Additional properties.
t.caching = false; // need to use caching?
t.loader = null; // loader to use ('form', 'script', 'xml'; null - autodetect)
t.session_name = "PHPSESSID"; // set to SID cookie or GET parameter name
// Internals.
t._ldObj = null; // used loader object
t._reqHeaders = []; // collected request headers
t._openArgs = null; // parameters from open()
t._errors = {
inv_form_el: 'Invalid FORM element detected: name=%, tag=%',
must_be_single_el: 'If used, <form> must be a single HTML element in the list.',
js_invalid: 'JavaScript code generated by backend is invalid!\n%',
url_too_long: 'Cannot use so long query with GET request (URL is larger than % bytes)',
unk_loader: 'Unknown loader: %',
no_loaders: 'No loaders registered at all, please check JsHttpRequest.LOADERS array',
no_loader_matched: 'Cannot find a loader which may process the request. Notices are:\n%'
}
/**
* Aborts the request. Behaviour of this function for onreadystatechange()
* is identical to IE (most universal and common case). E.g., readyState -> 4
* on abort() after send().
*/
t.abort = function() { with (this) {
if (_ldObj && _ldObj.abort) _ldObj.abort();
_cleanup();
if (readyState == 0) {
// start->abort: no change of readyState (IE behaviour)
return;
}
if (readyState == 1 && !_ldObj) {
// open->abort: no onreadystatechange call, but change readyState to 0 (IE).
// send->abort: change state to 4 (_ldObj is not null when send() is called)
readyState = 0;
return;
}
_changeReadyState(4, true); // 4 in IE & FF on abort() call; Opera does not change to 4.
}}
/**
* Prepares the object for data loading.
* You may also pass URLs like "GET url" or "script.GET url".
*/
t.open = function(method, url, asyncFlag, username, password) { with (this) {
// Extract methor and loader from the URL (if present).
if (url.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)) {
this.loader = RegExp.$2? RegExp.$2 : null;
method = RegExp.$3;
url = RegExp.$4;
}
// Append SID to original URL. Use try...catch for security problems.
try {
if (
document.location.search.match(new RegExp('[&?]' + session_name + '=([^&?]*)'))
|| document.cookie.match(new RegExp('(?:;|^)\\s*' + session_name + '=([^;]*)'))
) {
url += (url.indexOf('?') >= 0? '&' : '?') + session_name + "=" + this.escape(RegExp.$1);
}
} catch (e) {}
// Store open arguments to hash.
_openArgs = {
method: (method || '').toUpperCase(),
url: url,
asyncFlag: asyncFlag,
username: username != null? username : '',
password: password != null? password : ''
}
_ldObj = null;
_changeReadyState(1, true); // compatibility with XMLHttpRequest
return true;
}}
/**
* Sends a request to a server.
*/
t.send = function(content) {
if (!this.readyState) {
// send without open or after abort: no action (IE behaviour).
return;
}
this._changeReadyState(1, true); // compatibility with XMLHttpRequest
this._ldObj = null;
// Prepare to build QUERY_STRING from query hash.
var queryText = [];
var queryElem = [];
if (!this._hash2query(content, null, queryText, queryElem)) return;
// Solve the query hashcode & return on cache hit.
var hash = null;
if (this.caching && !queryElem.length) {
hash = this._openArgs.username + ':' + this._openArgs.password + '@' + this._openArgs.url + '|' + queryText + "#" + this._openArgs.method;
var cache = JsHttpRequest.CACHE[hash];
if (cache) {
this._dataReady(cache[0], cache[1]);
return false;
}
}
// Try all the loaders.
var loader = (this.loader || '').toLowerCase();
if (loader && !JsHttpRequest.LOADERS[loader]) return this._error('unk_loader', loader);
var errors = [];
var lds = JsHttpRequest.LOADERS;
for (var tryLoader in lds) {
var ldr = lds[tryLoader].loader;
if (!ldr) continue; // exclude possibly derived prototype properties from "for .. in".
if (loader && tryLoader != loader) continue;
// Create sending context.
var ldObj = new ldr(this);
JsHttpRequest.extend(ldObj, this._openArgs);
JsHttpRequest.extend(ldObj, {
queryText: queryText.join('&'),
queryElem: queryElem,
id: (new Date().getTime()) + "" + JsHttpRequest.COUNT++,
hash: hash,
span: null
});
var error = ldObj.load();
if (!error) {
// Save loading script.
this._ldObj = ldObj;
JsHttpRequest.PENDING[ldObj.id] = this;
return true;
}
if (!loader) {
errors[errors.length] = '- ' + tryLoader.toUpperCase() + ': ' + this._l(error);
} else {
return this._error(error);
}
}
// If no loader matched, generate error message.
return tryLoader? this._error('no_loader_matched', errors.join('\n')) : this._error('no_loaders');
}
/**
* Returns all response headers (if supported).
*/
t.getAllResponseHeaders = function() { with (this) {
return _ldObj && _ldObj.getAllResponseHeaders? _ldObj.getAllResponseHeaders() : [];
}}
/**
* Returns one response header (if supported).
*/
t.getResponseHeader = function(label) { with (this) {
return _ldObj && _ldObj.getResponseHeader? _ldObj.getResponseHeader(label) : null;
}}
/**
* Adds a request header to a future query.
*/
t.setRequestHeader = function(label, value) { with (this) {
_reqHeaders[_reqHeaders.length] = [label, value];
}}
//
// Internal functions.
//
/**
* Do all the work when a data is ready.
*/
t._dataReady = function(text, js) { with (this) {
if (caching && _ldObj) JsHttpRequest.CACHE[_ldObj.hash] = [text, js];
responseText = responseXML = text;
responseJS = js;
if (js !== null) {
status = 200;
statusText = "OK";
} else {
status = 500;
statusText = "Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}}
/**
* Analog of sprintf(), but translates the first parameter by _errors.
*/
t._l = function(args) {
var i = 0, p = 0, msg = this._errors[args[0]];
// Cannot use replace() with a callback, because it is incompatible with IE5.
while ((p = msg.indexOf('%', p)) >= 0) {
var a = args[++i] + "";
msg = msg.substring(0, p) + a + msg.substring(p + 1, msg.length);
p += 1 + a.length;
}
return msg;
}
/**
* Called on error.
*/
t._error = function(msg) {
msg = this._l(typeof(msg) == 'string'? arguments : msg)
msg = "JsHttpRequest: " + msg;
if (!window.Error) {
// Very old browser...
throw msg;
} else if ((new Error(1, 'test')).description == "test") {
// We MUST (!!!) pass 2 parameters to the Error() constructor for IE5.
throw new Error(1, msg);
} else {
// Mozilla does not support two-parameter call style.
throw new Error(msg);
}
}
/**
* Convert hash to QUERY_STRING.
* If next value is scalar or hash, push it to queryText.
* If next value is form element, push [name, element] to queryElem.
*/
t._hash2query = function(content, prefix, queryText, queryElem) {
if (prefix == null) prefix = "";
if((''+typeof(content)).toLowerCase() == 'object') {
var formAdded = false;
if (content && content.parentNode && content.parentNode.appendChild && content.tagName && content.tagName.toUpperCase() == 'FORM') {
content = { form: content };
}
for (var k in content) {
var v = content[k];
if (v instanceof Function) continue;
var curPrefix = prefix? prefix + '[' + this.escape(k) + ']' : this.escape(k);
var isFormElement = v && v.parentNode && v.parentNode.appendChild && v.tagName;
if (isFormElement) {
var tn = v.tagName.toUpperCase();
if (tn == 'FORM') {
// FORM itself is passed.
formAdded = true;
} else if (tn == 'INPUT' || tn == 'TEXTAREA' || tn == 'SELECT') {
// This is a single form elemenent.
} else {
return this._error('inv_form_el', (v.name||''), v.tagName);
}
queryElem[queryElem.length] = { name: curPrefix, e: v };
} else if (v instanceof Object) {
this._hash2query(v, curPrefix, queryText, queryElem);
} else {
// We MUST skip NULL values, because there is no method
// to pass NULL's via GET or POST request in PHP.
if (v === null) continue;
// Convert JS boolean true and false to corresponding PHP values.
if (v === true) v = 1;
if (v === false) v = '';
queryText[queryText.length] = curPrefix + "=" + this.escape('' + v);
}
if (formAdded && queryElem.length > 1) {
return this._error('must_be_single_el');
}
}
} else {
queryText[queryText.length] = content;
}
return true;
}
/**
* Remove last used script element (clean memory).
*/
t._cleanup = function() {
var ldObj = this._ldObj;
if (!ldObj) return;
// Mark this loading as aborted.
JsHttpRequest.PENDING[ldObj.id] = false;
var span = ldObj.span;
if (!span) return;
// Do NOT use iframe.contentWindow.back() - it is incompatible with Opera 9!
ldObj.span = null;
var closure = function() {
span.parentNode.removeChild(span);
}
// IE5 crashes on setTimeout(function() {...}, ...) construction! Use tmp variable.
JsHttpRequest.setTimeout(closure, 50);
}
/**
* Change current readyState and call trigger method.
*/
t._changeReadyState = function(s, reset) { with (this) {
if (reset) {
status = statusText = responseJS = null;
responseText = '';
}
readyState = s;
if (onreadystatechange) onreadystatechange();
}}
/**
* JS escape() does not quote '+'.
*/
t.escape = function(s) {
return escape(s).replace(new RegExp('\\+','g'), '%2B');
}
}
// Global library variables.
JsHttpRequest.COUNT = 0; // unique ID; used while loading IDs generation
JsHttpRequest.MAX_URL_LEN = 2000; // maximum URL length
JsHttpRequest.CACHE = {}; // cached data
JsHttpRequest.PENDING = {}; // pending loadings
JsHttpRequest.LOADERS = {}; // list of supported data loaders (filled at the bottom of the file)
JsHttpRequest._dummy = function() {}; // avoid memory leaks
/**
* These functions are dirty hacks for IE 5.0 which does not increment a
* reference counter for an object passed via setTimeout(). So, if this
* object (closure function) is out of scope at the moment of timeout
* applying, IE 5.0 crashes.
*/
/**
* Timeout wrappers storage. Used to avoid zeroing of referece counts in IE 5.0.
* Please note that you MUST write "window.setTimeout", not "setTimeout", else
* IE 5.0 crashes again. Strange, very strange...
*/
JsHttpRequest.TIMEOUTS = { s: window.setTimeout, c: window.clearTimeout };
/**
* Wrapper for IE5 buggy setTimeout.
* Use this function instead of a usual setTimeout().
*/
JsHttpRequest.setTimeout = function(func, dt) {
// Always save inside the window object before a call (for FF)!
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.s;
if (typeof(func) == "string") {
id = window.JsHttpRequest_tmp(func, dt);
} else {
var id = null;
var mediator = function() {
func();
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
}
id = window.JsHttpRequest_tmp(mediator, dt);
// Store a reference to the mediator function to the global array
// (reference count >= 1); use timeout ID as an array key;
JsHttpRequest.TIMEOUTS[id] = mediator;
}
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return id;
}
/**
* Complimental wrapper for clearTimeout.
* Use this function instead of usual clearTimeout().
*/
JsHttpRequest.clearTimeout = function(id) {
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
var r = window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return r;
}
/**
* Global static function.
* Simple interface for most popular use-cases.
* You may also pass URLs like "GET url" or "script.GET url".
*/
JsHttpRequest.query = function(url, content, onready, nocache) {
var req = new this();
req.caching = !nocache;
req.onreadystatechange = function() {
if (req.readyState == 4) {
onready(req.responseJS, req.responseText);
}
}
req.open(null, url, true);
req.send(content);
}
/**
* Global static function.
* Called by server backend script on data load.
*/
JsHttpRequest.dataReady = function(d) {
var th = this.PENDING[d.id];
delete this.PENDING[d.id];
if (th) {
th._dataReady(d.text, d.js);
} else if (th !== false) {
throw "dataReady(): unknown pending id: " + d.id;
}
}
// Adds all the properties of src to dest.
JsHttpRequest.extend = function(dest, src) {
for (var k in src) dest[k] = src[k];
}
/**
* Each loader has the following properties which must be initialized:
* - method
* - url
* - asyncFlag (ignored)
* - username
* - password
* - queryText (string)
* - queryElem (array)
* - id
* - hash
* - span
*/
// }}}
// {{{ script
// Loader: SCRIPT tag.
// [+] Most cross-browser.
// [+] Supports loading from different domains.
// [-] Only GET method is supported.
// [-] No uploading support.
// [-] Backend data cannot be browser-cached.
//
JsHttpRequest.LOADERS.script = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
script_only_get: 'Cannot use SCRIPT loader: it supports only GET method',
script_no_form: 'Cannot use SCRIPT loader: direct form elements using and uploading are not implemented'
})
this.load = function() {
// Move GET parameters to the URL itself.
if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + this.id + '-' + 'script';
this.queryText = '';
if (!this.method) this.method = 'GET';
if (this.method !== 'GET') return ['script_only_get'];
if (this.queryElem.length) return ['script_no_form'];
if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
var th = this, d = document, s = null, b = d.body;
if (!window.opera) {
// Safari, IE, FF, Opera 7.20.
this.span = s = d.createElement('SCRIPT');
var closure = function() {
s.language = 'JavaScript';
if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
b.insertBefore(s, b.lastChild);
}
} else {
// Oh shit! Damned stupid Opera 7.23 does not allow to create SCRIPT
// element over createElement (in HEAD or BODY section or in nested SPAN -
// no matter): it is created deadly, and does not response the href assignment.
// So - always create SPAN.
this.span = s = d.createElement('SPAN');
s.style.display = 'none';
b.insertBefore(s, b.lastChild);
s.innerHTML = 'Workaround for IE.<s'+'cript></' + 'script>';
var closure = function() {
s = s.getElementsByTagName('SCRIPT')[0]; // get with timeout!
s.language = 'JavaScript';
if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
}
}
JsHttpRequest.setTimeout(closure, 10);
// Success.
return null;
}
}}
// }}}
// {{{ xml
// Loader: XMLHttpRequest or ActiveX.
// [+] GET and POST methods are supported.
// [+] Most native and memory-cheap method.
// [+] Backend data can be browser-cached.
// [-] Cannot work in IE without ActiveX.
// [-] No support for loading from different domains.
// [-] No uploading support.
//
JsHttpRequest.LOADERS.xml = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
xml_no: 'Cannot use XMLHttpRequest or ActiveX loader: not supported',
xml_no_diffdom: 'Cannot use XMLHttpRequest to load data from different domain %',
xml_no_headers: 'Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly',
xml_no_form_upl: 'Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented'
});
this.load = function() {
if (this.queryElem.length) return ['xml_no_form_upl'];
// XMLHttpRequest (and MS ActiveX'es) cannot work with different domains.
if (this.url.match(new RegExp('^([a-z]+://[^\\/]+)(.*)', 'i'))) {
// We MUST also check if protocols matched: cannot send from HTTP
// to HTTPS and vice versa.
if (RegExp.$1.toLowerCase() != document.location.protocol + '//' + document.location.hostname.toLowerCase()) {
return ['xml_no_diffdom', RegExp.$1];
}
}
// Try to obtain a loader.
var xr = null;
if (window.XMLHttpRequest) {
try { xr = new XMLHttpRequest() } catch(e) {}
} else if (window.ActiveXObject) {
try { xr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
if (!xr) try { xr = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
}
if (!xr) return ['xml_no'];
// Loading method detection. We cannot POST if we cannot set "octet-stream"
// header, because we need to process the encoded data in the backend manually.
var canSetHeaders = window.ActiveXObject || xr.setRequestHeader;
if (!this.method) this.method = canSetHeaders && this.queryText.length? 'POST' : 'GET';
// Build & validate the full URL.
if (this.method == 'GET') {
if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
this.queryText = '';
if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
} else if (this.method == 'POST' && !canSetHeaders) {
return ['xml_no_headers'];
}
// Add ID to the url if we need to disable the cache.
this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + (req.caching? '0' : this.id) + '-xml';
// Assign the result handler.
var id = this.id;
xr.onreadystatechange = function() {
if (xr.readyState != 4) return;
// Avoid memory leak by removing the closure.
xr.onreadystatechange = JsHttpRequest._dummy;
req.status = null;
try {
// In case of abort() call, xr.status is unavailable and generates exception.
// But xr.readyState equals to 4 in this case. Stupid behaviour. :-(
req.status = xr.status;
req.responseText = xr.responseText;
} catch (e) {}
if (!req.status) return;
try {
// Prepare generator function & catch syntax errors on this stage.
eval('JsHttpRequest._tmp = function(id) { var d = ' + req.responseText + '; d.id = id; JsHttpRequest.dataReady(d); }');
} catch (e) {
// Note that FF 2.0 does not throw any error from onreadystatechange handler.
return req._error('js_invalid', req.responseText)
}
// Call associated dataReady() outside the try-catch block
// to pass exceptions in onreadystatechange in usual manner.
JsHttpRequest._tmp(id);
JsHttpRequest._tmp = null;
};
// Open & send the request.
xr.open(this.method, this.url, true, this.username, this.password);
if (canSetHeaders) {
// Pass pending headers.
for (var i = 0; i < req._reqHeaders.length; i++) {
xr.setRequestHeader(req._reqHeaders[i][0], req._reqHeaders[i][1]);
}
// Set non-default Content-type. We cannot use
// "application/x-www-form-urlencoded" here, because
// in PHP variable HTTP_RAW_POST_DATA is accessible only when
// enctype is not default (e.g., "application/octet-stream"
// is a good start). We parse POST data manually in backend
// library code. Note that Safari sets by default "x-www-form-urlencoded"
// header, but FF sets "text/xml" by default.
xr.setRequestHeader('Content-Type', 'application/octet-stream');
}
xr.send(this.queryText);
// No SPAN is used for this loader.
this.span = null;
this.xr = xr; // save for later usage on abort()
// Success.
return null;
}
// Override req.getAllResponseHeaders method.
this.getAllResponseHeaders = function() {
return this.xr.getAllResponseHeaders();
}
// Override req.getResponseHeader method.
this.getResponseHeader = function(label) {
return this.xr.getResponseHeader(label);
}
this.abort = function() {
this.xr.abort();
this.xr = null;
}
}}
// }}}

View file

@ -0,0 +1,493 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (script support only!)
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
// {{{
function JsHttpRequest() {
// Standard properties.
var t = this;
t.onreadystatechange = null;
t.readyState = 0;
t.responseText = null;
t.responseXML = null;
t.status = 200;
t.statusText = "OK";
// JavaScript response array/hash
t.responseJS = null;
// Additional properties.
t.caching = false; // need to use caching?
t.loader = null; // loader to use ('form', 'script', 'xml'; null - autodetect)
t.session_name = "PHPSESSID"; // set to SID cookie or GET parameter name
// Internals.
t._ldObj = null; // used loader object
t._reqHeaders = []; // collected request headers
t._openArgs = null; // parameters from open()
t._errors = {
inv_form_el: 'Invalid FORM element detected: name=%, tag=%',
must_be_single_el: 'If used, <form> must be a single HTML element in the list.',
js_invalid: 'JavaScript code generated by backend is invalid!\n%',
url_too_long: 'Cannot use so long query with GET request (URL is larger than % bytes)',
unk_loader: 'Unknown loader: %',
no_loaders: 'No loaders registered at all, please check JsHttpRequest.LOADERS array',
no_loader_matched: 'Cannot find a loader which may process the request. Notices are:\n%'
}
/**
* Aborts the request. Behaviour of this function for onreadystatechange()
* is identical to IE (most universal and common case). E.g., readyState -> 4
* on abort() after send().
*/
t.abort = function() { with (this) {
if (_ldObj && _ldObj.abort) _ldObj.abort();
_cleanup();
if (readyState == 0) {
// start->abort: no change of readyState (IE behaviour)
return;
}
if (readyState == 1 && !_ldObj) {
// open->abort: no onreadystatechange call, but change readyState to 0 (IE).
// send->abort: change state to 4 (_ldObj is not null when send() is called)
readyState = 0;
return;
}
_changeReadyState(4, true); // 4 in IE & FF on abort() call; Opera does not change to 4.
}}
/**
* Prepares the object for data loading.
* You may also pass URLs like "GET url" or "script.GET url".
*/
t.open = function(method, url, asyncFlag, username, password) { with (this) {
// Extract methor and loader from the URL (if present).
if (url.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)) {
this.loader = RegExp.$2? RegExp.$2 : null;
method = RegExp.$3;
url = RegExp.$4;
}
// Append SID to original URL. Use try...catch for security problems.
try {
if (
document.location.search.match(new RegExp('[&?]' + session_name + '=([^&?]*)'))
|| document.cookie.match(new RegExp('(?:;|^)\\s*' + session_name + '=([^;]*)'))
) {
url += (url.indexOf('?') >= 0? '&' : '?') + session_name + "=" + this.escape(RegExp.$1);
}
} catch (e) {}
// Store open arguments to hash.
_openArgs = {
method: (method || '').toUpperCase(),
url: url,
asyncFlag: asyncFlag,
username: username != null? username : '',
password: password != null? password : ''
}
_ldObj = null;
_changeReadyState(1, true); // compatibility with XMLHttpRequest
return true;
}}
/**
* Sends a request to a server.
*/
t.send = function(content) {
if (!this.readyState) {
// send without open or after abort: no action (IE behaviour).
return;
}
this._changeReadyState(1, true); // compatibility with XMLHttpRequest
this._ldObj = null;
// Prepare to build QUERY_STRING from query hash.
var queryText = [];
var queryElem = [];
if (!this._hash2query(content, null, queryText, queryElem)) return;
// Solve the query hashcode & return on cache hit.
var hash = null;
if (this.caching && !queryElem.length) {
hash = this._openArgs.username + ':' + this._openArgs.password + '@' + this._openArgs.url + '|' + queryText + "#" + this._openArgs.method;
var cache = JsHttpRequest.CACHE[hash];
if (cache) {
this._dataReady(cache[0], cache[1]);
return false;
}
}
// Try all the loaders.
var loader = (this.loader || '').toLowerCase();
if (loader && !JsHttpRequest.LOADERS[loader]) return this._error('unk_loader', loader);
var errors = [];
var lds = JsHttpRequest.LOADERS;
for (var tryLoader in lds) {
var ldr = lds[tryLoader].loader;
if (!ldr) continue; // exclude possibly derived prototype properties from "for .. in".
if (loader && tryLoader != loader) continue;
// Create sending context.
var ldObj = new ldr(this);
JsHttpRequest.extend(ldObj, this._openArgs);
JsHttpRequest.extend(ldObj, {
queryText: queryText.join('&'),
queryElem: queryElem,
id: (new Date().getTime()) + "" + JsHttpRequest.COUNT++,
hash: hash,
span: null
});
var error = ldObj.load();
if (!error) {
// Save loading script.
this._ldObj = ldObj;
JsHttpRequest.PENDING[ldObj.id] = this;
return true;
}
if (!loader) {
errors[errors.length] = '- ' + tryLoader.toUpperCase() + ': ' + this._l(error);
} else {
return this._error(error);
}
}
// If no loader matched, generate error message.
return tryLoader? this._error('no_loader_matched', errors.join('\n')) : this._error('no_loaders');
}
/**
* Returns all response headers (if supported).
*/
t.getAllResponseHeaders = function() { with (this) {
return _ldObj && _ldObj.getAllResponseHeaders? _ldObj.getAllResponseHeaders() : [];
}}
/**
* Returns one response header (if supported).
*/
t.getResponseHeader = function(label) { with (this) {
return _ldObj && _ldObj.getResponseHeader? _ldObj.getResponseHeader(label) : null;
}}
/**
* Adds a request header to a future query.
*/
t.setRequestHeader = function(label, value) { with (this) {
_reqHeaders[_reqHeaders.length] = [label, value];
}}
//
// Internal functions.
//
/**
* Do all the work when a data is ready.
*/
t._dataReady = function(text, js) { with (this) {
if (caching && _ldObj) JsHttpRequest.CACHE[_ldObj.hash] = [text, js];
responseText = responseXML = text;
responseJS = js;
if (js !== null) {
status = 200;
statusText = "OK";
} else {
status = 500;
statusText = "Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}}
/**
* Analog of sprintf(), but translates the first parameter by _errors.
*/
t._l = function(args) {
var i = 0, p = 0, msg = this._errors[args[0]];
// Cannot use replace() with a callback, because it is incompatible with IE5.
while ((p = msg.indexOf('%', p)) >= 0) {
var a = args[++i] + "";
msg = msg.substring(0, p) + a + msg.substring(p + 1, msg.length);
p += 1 + a.length;
}
return msg;
}
/**
* Called on error.
*/
t._error = function(msg) {
msg = this._l(typeof(msg) == 'string'? arguments : msg)
msg = "JsHttpRequest: " + msg;
if (!window.Error) {
// Very old browser...
throw msg;
} else if ((new Error(1, 'test')).description == "test") {
// We MUST (!!!) pass 2 parameters to the Error() constructor for IE5.
throw new Error(1, msg);
} else {
// Mozilla does not support two-parameter call style.
throw new Error(msg);
}
}
/**
* Convert hash to QUERY_STRING.
* If next value is scalar or hash, push it to queryText.
* If next value is form element, push [name, element] to queryElem.
*/
t._hash2query = function(content, prefix, queryText, queryElem) {
if (prefix == null) prefix = "";
if((''+typeof(content)).toLowerCase() == 'object') {
var formAdded = false;
if (content && content.parentNode && content.parentNode.appendChild && content.tagName && content.tagName.toUpperCase() == 'FORM') {
content = { form: content };
}
for (var k in content) {
var v = content[k];
if (v instanceof Function) continue;
var curPrefix = prefix? prefix + '[' + this.escape(k) + ']' : this.escape(k);
var isFormElement = v && v.parentNode && v.parentNode.appendChild && v.tagName;
if (isFormElement) {
var tn = v.tagName.toUpperCase();
if (tn == 'FORM') {
// FORM itself is passed.
formAdded = true;
} else if (tn == 'INPUT' || tn == 'TEXTAREA' || tn == 'SELECT') {
// This is a single form elemenent.
} else {
return this._error('inv_form_el', (v.name||''), v.tagName);
}
queryElem[queryElem.length] = { name: curPrefix, e: v };
} else if (v instanceof Object) {
this._hash2query(v, curPrefix, queryText, queryElem);
} else {
// We MUST skip NULL values, because there is no method
// to pass NULL's via GET or POST request in PHP.
if (v === null) continue;
// Convert JS boolean true and false to corresponding PHP values.
if (v === true) v = 1;
if (v === false) v = '';
queryText[queryText.length] = curPrefix + "=" + this.escape('' + v);
}
if (formAdded && queryElem.length > 1) {
return this._error('must_be_single_el');
}
}
} else {
queryText[queryText.length] = content;
}
return true;
}
/**
* Remove last used script element (clean memory).
*/
t._cleanup = function() {
var ldObj = this._ldObj;
if (!ldObj) return;
// Mark this loading as aborted.
JsHttpRequest.PENDING[ldObj.id] = false;
var span = ldObj.span;
if (!span) return;
// Do NOT use iframe.contentWindow.back() - it is incompatible with Opera 9!
ldObj.span = null;
var closure = function() {
span.parentNode.removeChild(span);
}
// IE5 crashes on setTimeout(function() {...}, ...) construction! Use tmp variable.
JsHttpRequest.setTimeout(closure, 50);
}
/**
* Change current readyState and call trigger method.
*/
t._changeReadyState = function(s, reset) { with (this) {
if (reset) {
status = statusText = responseJS = null;
responseText = '';
}
readyState = s;
if (onreadystatechange) onreadystatechange();
}}
/**
* JS escape() does not quote '+'.
*/
t.escape = function(s) {
return escape(s).replace(new RegExp('\\+','g'), '%2B');
}
}
// Global library variables.
JsHttpRequest.COUNT = 0; // unique ID; used while loading IDs generation
JsHttpRequest.MAX_URL_LEN = 2000; // maximum URL length
JsHttpRequest.CACHE = {}; // cached data
JsHttpRequest.PENDING = {}; // pending loadings
JsHttpRequest.LOADERS = {}; // list of supported data loaders (filled at the bottom of the file)
JsHttpRequest._dummy = function() {}; // avoid memory leaks
/**
* These functions are dirty hacks for IE 5.0 which does not increment a
* reference counter for an object passed via setTimeout(). So, if this
* object (closure function) is out of scope at the moment of timeout
* applying, IE 5.0 crashes.
*/
/**
* Timeout wrappers storage. Used to avoid zeroing of referece counts in IE 5.0.
* Please note that you MUST write "window.setTimeout", not "setTimeout", else
* IE 5.0 crashes again. Strange, very strange...
*/
JsHttpRequest.TIMEOUTS = { s: window.setTimeout, c: window.clearTimeout };
/**
* Wrapper for IE5 buggy setTimeout.
* Use this function instead of a usual setTimeout().
*/
JsHttpRequest.setTimeout = function(func, dt) {
// Always save inside the window object before a call (for FF)!
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.s;
if (typeof(func) == "string") {
id = window.JsHttpRequest_tmp(func, dt);
} else {
var id = null;
var mediator = function() {
func();
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
}
id = window.JsHttpRequest_tmp(mediator, dt);
// Store a reference to the mediator function to the global array
// (reference count >= 1); use timeout ID as an array key;
JsHttpRequest.TIMEOUTS[id] = mediator;
}
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return id;
}
/**
* Complimental wrapper for clearTimeout.
* Use this function instead of usual clearTimeout().
*/
JsHttpRequest.clearTimeout = function(id) {
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
var r = window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return r;
}
/**
* Global static function.
* Simple interface for most popular use-cases.
* You may also pass URLs like "GET url" or "script.GET url".
*/
JsHttpRequest.query = function(url, content, onready, nocache) {
var req = new this();
req.caching = !nocache;
req.onreadystatechange = function() {
if (req.readyState == 4) {
onready(req.responseJS, req.responseText);
}
}
req.open(null, url, true);
req.send(content);
}
/**
* Global static function.
* Called by server backend script on data load.
*/
JsHttpRequest.dataReady = function(d) {
var th = this.PENDING[d.id];
delete this.PENDING[d.id];
if (th) {
th._dataReady(d.text, d.js);
} else if (th !== false) {
throw "dataReady(): unknown pending id: " + d.id;
}
}
// Adds all the properties of src to dest.
JsHttpRequest.extend = function(dest, src) {
for (var k in src) dest[k] = src[k];
}
/**
* Each loader has the following properties which must be initialized:
* - method
* - url
* - asyncFlag (ignored)
* - username
* - password
* - queryText (string)
* - queryElem (array)
* - id
* - hash
* - span
*/
// }}}
// {{{ script
// Loader: SCRIPT tag.
// [+] Most cross-browser.
// [+] Supports loading from different domains.
// [-] Only GET method is supported.
// [-] No uploading support.
// [-] Backend data cannot be browser-cached.
//
JsHttpRequest.LOADERS.script = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
script_only_get: 'Cannot use SCRIPT loader: it supports only GET method',
script_no_form: 'Cannot use SCRIPT loader: direct form elements using and uploading are not implemented'
})
this.load = function() {
// Move GET parameters to the URL itself.
if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + this.id + '-' + 'script';
this.queryText = '';
if (!this.method) this.method = 'GET';
if (this.method !== 'GET') return ['script_only_get'];
if (this.queryElem.length) return ['script_no_form'];
if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
var th = this, d = document, s = null, b = d.body;
if (!window.opera) {
// Safari, IE, FF, Opera 7.20.
this.span = s = d.createElement('SCRIPT');
var closure = function() {
s.language = 'JavaScript';
if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
b.insertBefore(s, b.lastChild);
}
} else {
// Oh shit! Damned stupid Opera 7.23 does not allow to create SCRIPT
// element over createElement (in HEAD or BODY section or in nested SPAN -
// no matter): it is created deadly, and does not response the href assignment.
// So - always create SPAN.
this.span = s = d.createElement('SPAN');
s.style.display = 'none';
b.insertBefore(s, b.lastChild);
s.innerHTML = 'Workaround for IE.<s'+'cript></' + 'script>';
var closure = function() {
s = s.getElementsByTagName('SCRIPT')[0]; // get with timeout!
s.language = 'JavaScript';
if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
}
}
JsHttpRequest.setTimeout(closure, 10);
// Success.
return null;
}
}}
// }}}

View file

@ -0,0 +1,562 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (xml support only!)
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
// {{{
function JsHttpRequest() {
// Standard properties.
var t = this;
t.onreadystatechange = null;
t.readyState = 0;
t.responseText = null;
t.responseXML = null;
t.status = 200;
t.statusText = "OK";
// JavaScript response array/hash
t.responseJS = null;
// Additional properties.
t.caching = false; // need to use caching?
t.loader = null; // loader to use ('form', 'script', 'xml'; null - autodetect)
t.session_name = "PHPSESSID"; // set to SID cookie or GET parameter name
// Internals.
t._ldObj = null; // used loader object
t._reqHeaders = []; // collected request headers
t._openArgs = null; // parameters from open()
t._errors = {
inv_form_el: 'Invalid FORM element detected: name=%, tag=%',
must_be_single_el: 'If used, <form> must be a single HTML element in the list.',
js_invalid: 'JavaScript code generated by backend is invalid!\n%',
url_too_long: 'Cannot use so long query with GET request (URL is larger than % bytes)',
unk_loader: 'Unknown loader: %',
no_loaders: 'No loaders registered at all, please check JsHttpRequest.LOADERS array',
no_loader_matched: 'Cannot find a loader which may process the request. Notices are:\n%'
}
/**
* Aborts the request. Behaviour of this function for onreadystatechange()
* is identical to IE (most universal and common case). E.g., readyState -> 4
* on abort() after send().
*/
t.abort = function() { with (this) {
if (_ldObj && _ldObj.abort) _ldObj.abort();
_cleanup();
if (readyState == 0) {
// start->abort: no change of readyState (IE behaviour)
return;
}
if (readyState == 1 && !_ldObj) {
// open->abort: no onreadystatechange call, but change readyState to 0 (IE).
// send->abort: change state to 4 (_ldObj is not null when send() is called)
readyState = 0;
return;
}
_changeReadyState(4, true); // 4 in IE & FF on abort() call; Opera does not change to 4.
}}
/**
* Prepares the object for data loading.
* You may also pass URLs like "GET url" or "script.GET url".
*/
t.open = function(method, url, asyncFlag, username, password) { with (this) {
// Extract methor and loader from the URL (if present).
if (url.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)) {
this.loader = RegExp.$2? RegExp.$2 : null;
method = RegExp.$3;
url = RegExp.$4;
}
// Append SID to original URL. Use try...catch for security problems.
try {
if (
document.location.search.match(new RegExp('[&?]' + session_name + '=([^&?]*)'))
|| document.cookie.match(new RegExp('(?:;|^)\\s*' + session_name + '=([^;]*)'))
) {
url += (url.indexOf('?') >= 0? '&' : '?') + session_name + "=" + this.escape(RegExp.$1);
}
} catch (e) {}
// Store open arguments to hash.
_openArgs = {
method: (method || '').toUpperCase(),
url: url,
asyncFlag: asyncFlag,
username: username != null? username : '',
password: password != null? password : ''
}
_ldObj = null;
_changeReadyState(1, true); // compatibility with XMLHttpRequest
return true;
}}
/**
* Sends a request to a server.
*/
t.send = function(content) {
if (!this.readyState) {
// send without open or after abort: no action (IE behaviour).
return;
}
this._changeReadyState(1, true); // compatibility with XMLHttpRequest
this._ldObj = null;
// Prepare to build QUERY_STRING from query hash.
var queryText = [];
var queryElem = [];
if (!this._hash2query(content, null, queryText, queryElem)) return;
// Solve the query hashcode & return on cache hit.
var hash = null;
if (this.caching && !queryElem.length) {
hash = this._openArgs.username + ':' + this._openArgs.password + '@' + this._openArgs.url + '|' + queryText + "#" + this._openArgs.method;
var cache = JsHttpRequest.CACHE[hash];
if (cache) {
this._dataReady(cache[0], cache[1]);
return false;
}
}
// Try all the loaders.
var loader = (this.loader || '').toLowerCase();
if (loader && !JsHttpRequest.LOADERS[loader]) return this._error('unk_loader', loader);
var errors = [];
var lds = JsHttpRequest.LOADERS;
for (var tryLoader in lds) {
var ldr = lds[tryLoader].loader;
if (!ldr) continue; // exclude possibly derived prototype properties from "for .. in".
if (loader && tryLoader != loader) continue;
// Create sending context.
var ldObj = new ldr(this);
JsHttpRequest.extend(ldObj, this._openArgs);
JsHttpRequest.extend(ldObj, {
queryText: queryText.join('&'),
queryElem: queryElem,
id: (new Date().getTime()) + "" + JsHttpRequest.COUNT++,
hash: hash,
span: null
});
var error = ldObj.load();
if (!error) {
// Save loading script.
this._ldObj = ldObj;
JsHttpRequest.PENDING[ldObj.id] = this;
return true;
}
if (!loader) {
errors[errors.length] = '- ' + tryLoader.toUpperCase() + ': ' + this._l(error);
} else {
return this._error(error);
}
}
// If no loader matched, generate error message.
return tryLoader? this._error('no_loader_matched', errors.join('\n')) : this._error('no_loaders');
}
/**
* Returns all response headers (if supported).
*/
t.getAllResponseHeaders = function() { with (this) {
return _ldObj && _ldObj.getAllResponseHeaders? _ldObj.getAllResponseHeaders() : [];
}}
/**
* Returns one response header (if supported).
*/
t.getResponseHeader = function(label) { with (this) {
return _ldObj && _ldObj.getResponseHeader? _ldObj.getResponseHeader(label) : null;
}}
/**
* Adds a request header to a future query.
*/
t.setRequestHeader = function(label, value) { with (this) {
_reqHeaders[_reqHeaders.length] = [label, value];
}}
//
// Internal functions.
//
/**
* Do all the work when a data is ready.
*/
t._dataReady = function(text, js) { with (this) {
if (caching && _ldObj) JsHttpRequest.CACHE[_ldObj.hash] = [text, js];
responseText = responseXML = text;
responseJS = js;
if (js !== null) {
status = 200;
statusText = "OK";
} else {
status = 500;
statusText = "Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}}
/**
* Analog of sprintf(), but translates the first parameter by _errors.
*/
t._l = function(args) {
var i = 0, p = 0, msg = this._errors[args[0]];
// Cannot use replace() with a callback, because it is incompatible with IE5.
while ((p = msg.indexOf('%', p)) >= 0) {
var a = args[++i] + "";
msg = msg.substring(0, p) + a + msg.substring(p + 1, msg.length);
p += 1 + a.length;
}
return msg;
}
/**
* Called on error.
*/
t._error = function(msg) {
msg = this._l(typeof(msg) == 'string'? arguments : msg)
msg = "JsHttpRequest: " + msg;
if (!window.Error) {
// Very old browser...
throw msg;
} else if ((new Error(1, 'test')).description == "test") {
// We MUST (!!!) pass 2 parameters to the Error() constructor for IE5.
throw new Error(1, msg);
} else {
// Mozilla does not support two-parameter call style.
throw new Error(msg);
}
}
/**
* Convert hash to QUERY_STRING.
* If next value is scalar or hash, push it to queryText.
* If next value is form element, push [name, element] to queryElem.
*/
t._hash2query = function(content, prefix, queryText, queryElem) {
if (prefix == null) prefix = "";
if((''+typeof(content)).toLowerCase() == 'object') {
var formAdded = false;
if (content && content.parentNode && content.parentNode.appendChild && content.tagName && content.tagName.toUpperCase() == 'FORM') {
content = { form: content };
}
for (var k in content) {
var v = content[k];
if (v instanceof Function) continue;
var curPrefix = prefix? prefix + '[' + this.escape(k) + ']' : this.escape(k);
var isFormElement = v && v.parentNode && v.parentNode.appendChild && v.tagName;
if (isFormElement) {
var tn = v.tagName.toUpperCase();
if (tn == 'FORM') {
// FORM itself is passed.
formAdded = true;
} else if (tn == 'INPUT' || tn == 'TEXTAREA' || tn == 'SELECT') {
// This is a single form elemenent.
} else {
return this._error('inv_form_el', (v.name||''), v.tagName);
}
queryElem[queryElem.length] = { name: curPrefix, e: v };
} else if (v instanceof Object) {
this._hash2query(v, curPrefix, queryText, queryElem);
} else {
// We MUST skip NULL values, because there is no method
// to pass NULL's via GET or POST request in PHP.
if (v === null) continue;
// Convert JS boolean true and false to corresponding PHP values.
if (v === true) v = 1;
if (v === false) v = '';
queryText[queryText.length] = curPrefix + "=" + this.escape('' + v);
}
if (formAdded && queryElem.length > 1) {
return this._error('must_be_single_el');
}
}
} else {
queryText[queryText.length] = content;
}
return true;
}
/**
* Remove last used script element (clean memory).
*/
t._cleanup = function() {
var ldObj = this._ldObj;
if (!ldObj) return;
// Mark this loading as aborted.
JsHttpRequest.PENDING[ldObj.id] = false;
var span = ldObj.span;
if (!span) return;
// Do NOT use iframe.contentWindow.back() - it is incompatible with Opera 9!
ldObj.span = null;
var closure = function() {
span.parentNode.removeChild(span);
}
// IE5 crashes on setTimeout(function() {...}, ...) construction! Use tmp variable.
JsHttpRequest.setTimeout(closure, 50);
}
/**
* Change current readyState and call trigger method.
*/
t._changeReadyState = function(s, reset) { with (this) {
if (reset) {
status = statusText = responseJS = null;
responseText = '';
}
readyState = s;
if (onreadystatechange) onreadystatechange();
}}
/**
* JS escape() does not quote '+'.
*/
t.escape = function(s) {
return escape(s).replace(new RegExp('\\+','g'), '%2B');
}
}
// Global library variables.
JsHttpRequest.COUNT = 0; // unique ID; used while loading IDs generation
JsHttpRequest.MAX_URL_LEN = 2000; // maximum URL length
JsHttpRequest.CACHE = {}; // cached data
JsHttpRequest.PENDING = {}; // pending loadings
JsHttpRequest.LOADERS = {}; // list of supported data loaders (filled at the bottom of the file)
JsHttpRequest._dummy = function() {}; // avoid memory leaks
/**
* These functions are dirty hacks for IE 5.0 which does not increment a
* reference counter for an object passed via setTimeout(). So, if this
* object (closure function) is out of scope at the moment of timeout
* applying, IE 5.0 crashes.
*/
/**
* Timeout wrappers storage. Used to avoid zeroing of referece counts in IE 5.0.
* Please note that you MUST write "window.setTimeout", not "setTimeout", else
* IE 5.0 crashes again. Strange, very strange...
*/
JsHttpRequest.TIMEOUTS = { s: window.setTimeout, c: window.clearTimeout };
/**
* Wrapper for IE5 buggy setTimeout.
* Use this function instead of a usual setTimeout().
*/
JsHttpRequest.setTimeout = function(func, dt) {
// Always save inside the window object before a call (for FF)!
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.s;
if (typeof(func) == "string") {
id = window.JsHttpRequest_tmp(func, dt);
} else {
var id = null;
var mediator = function() {
func();
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
}
id = window.JsHttpRequest_tmp(mediator, dt);
// Store a reference to the mediator function to the global array
// (reference count >= 1); use timeout ID as an array key;
JsHttpRequest.TIMEOUTS[id] = mediator;
}
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return id;
}
/**
* Complimental wrapper for clearTimeout.
* Use this function instead of usual clearTimeout().
*/
JsHttpRequest.clearTimeout = function(id) {
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
var r = window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return r;
}
/**
* Global static function.
* Simple interface for most popular use-cases.
* You may also pass URLs like "GET url" or "script.GET url".
*/
JsHttpRequest.query = function(url, content, onready, nocache) {
var req = new this();
req.caching = !nocache;
req.onreadystatechange = function() {
if (req.readyState == 4) {
onready(req.responseJS, req.responseText);
}
}
req.open(null, url, true);
req.send(content);
}
/**
* Global static function.
* Called by server backend script on data load.
*/
JsHttpRequest.dataReady = function(d) {
var th = this.PENDING[d.id];
delete this.PENDING[d.id];
if (th) {
th._dataReady(d.text, d.js);
} else if (th !== false) {
throw "dataReady(): unknown pending id: " + d.id;
}
}
// Adds all the properties of src to dest.
JsHttpRequest.extend = function(dest, src) {
for (var k in src) dest[k] = src[k];
}
/**
* Each loader has the following properties which must be initialized:
* - method
* - url
* - asyncFlag (ignored)
* - username
* - password
* - queryText (string)
* - queryElem (array)
* - id
* - hash
* - span
*/
// }}}
// {{{ xml
// Loader: XMLHttpRequest or ActiveX.
// [+] GET and POST methods are supported.
// [+] Most native and memory-cheap method.
// [+] Backend data can be browser-cached.
// [-] Cannot work in IE without ActiveX.
// [-] No support for loading from different domains.
// [-] No uploading support.
//
JsHttpRequest.LOADERS.xml = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
xml_no: 'Cannot use XMLHttpRequest or ActiveX loader: not supported',
xml_no_diffdom: 'Cannot use XMLHttpRequest to load data from different domain %',
xml_no_headers: 'Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly',
xml_no_form_upl: 'Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented'
});
this.load = function() {
if (this.queryElem.length) return ['xml_no_form_upl'];
// XMLHttpRequest (and MS ActiveX'es) cannot work with different domains.
if (this.url.match(new RegExp('^([a-z]+://[^\\/]+)(.*)', 'i'))) {
// We MUST also check if protocols matched: cannot send from HTTP
// to HTTPS and vice versa.
if (RegExp.$1.toLowerCase() != document.location.protocol + '//' + document.location.hostname.toLowerCase()) {
return ['xml_no_diffdom', RegExp.$1];
}
}
// Try to obtain a loader.
var xr = null;
if (window.XMLHttpRequest) {
try { xr = new XMLHttpRequest() } catch(e) {}
} else if (window.ActiveXObject) {
try { xr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
if (!xr) try { xr = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
}
if (!xr) return ['xml_no'];
// Loading method detection. We cannot POST if we cannot set "octet-stream"
// header, because we need to process the encoded data in the backend manually.
var canSetHeaders = window.ActiveXObject || xr.setRequestHeader;
if (!this.method) this.method = canSetHeaders && this.queryText.length? 'POST' : 'GET';
// Build & validate the full URL.
if (this.method == 'GET') {
if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
this.queryText = '';
if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
} else if (this.method == 'POST' && !canSetHeaders) {
return ['xml_no_headers'];
}
// Add ID to the url if we need to disable the cache.
this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + (req.caching? '0' : this.id) + '-xml';
// Assign the result handler.
var id = this.id;
xr.onreadystatechange = function() {
if (xr.readyState != 4) return;
// Avoid memory leak by removing the closure.
xr.onreadystatechange = JsHttpRequest._dummy;
req.status = null;
try {
// In case of abort() call, xr.status is unavailable and generates exception.
// But xr.readyState equals to 4 in this case. Stupid behaviour. :-(
req.status = xr.status;
req.responseText = xr.responseText;
} catch (e) {}
if (!req.status) return;
try {
// Prepare generator function & catch syntax errors on this stage.
eval('JsHttpRequest._tmp = function(id) { var d = ' + req.responseText + '; d.id = id; JsHttpRequest.dataReady(d); }');
} catch (e) {
// Note that FF 2.0 does not throw any error from onreadystatechange handler.
return req._error('js_invalid', req.responseText)
}
// Call associated dataReady() outside the try-catch block
// to pass exceptions in onreadystatechange in usual manner.
JsHttpRequest._tmp(id);
JsHttpRequest._tmp = null;
};
// Open & send the request.
xr.open(this.method, this.url, true, this.username, this.password);
if (canSetHeaders) {
// Pass pending headers.
for (var i = 0; i < req._reqHeaders.length; i++) {
xr.setRequestHeader(req._reqHeaders[i][0], req._reqHeaders[i][1]);
}
// Set non-default Content-type. We cannot use
// "application/x-www-form-urlencoded" here, because
// in PHP variable HTTP_RAW_POST_DATA is accessible only when
// enctype is not default (e.g., "application/octet-stream"
// is a good start). We parse POST data manually in backend
// library code. Note that Safari sets by default "x-www-form-urlencoded"
// header, but FF sets "text/xml" by default.
xr.setRequestHeader('Content-Type', 'application/octet-stream');
}
xr.send(this.queryText);
// No SPAN is used for this loader.
this.span = null;
this.xr = xr; // save for later usage on abort()
// Success.
return null;
}
// Override req.getAllResponseHeaders method.
this.getAllResponseHeaders = function() {
return this.xr.getAllResponseHeaders();
}
// Override req.getResponseHeader method.
this.getResponseHeader = function(label) {
return this.xr.getResponseHeader(label);
}
this.abort = function() {
this.xr.abort();
this.xr = null;
}
}}
// }}}

View file

@ -0,0 +1,798 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
// {{{
function JsHttpRequest() {
// Standard properties.
var t = this;
t.onreadystatechange = null;
t.readyState = 0;
t.responseText = null;
t.responseXML = null;
t.status = 200;
t.statusText = "OK";
// JavaScript response array/hash
t.responseJS = null;
// Additional properties.
t.caching = false; // need to use caching?
t.loader = null; // loader to use ('form', 'script', 'xml'; null - autodetect)
t.session_name = "PHPSESSID"; // set to SID cookie or GET parameter name
// Internals.
t._ldObj = null; // used loader object
t._reqHeaders = []; // collected request headers
t._openArgs = null; // parameters from open()
t._errors = {
inv_form_el: 'Invalid FORM element detected: name=%, tag=%',
must_be_single_el: 'If used, <form> must be a single HTML element in the list.',
js_invalid: 'JavaScript code generated by backend is invalid!\n%',
url_too_long: 'Cannot use so long query with GET request (URL is larger than % bytes)',
unk_loader: 'Unknown loader: %',
no_loaders: 'No loaders registered at all, please check JsHttpRequest.LOADERS array',
no_loader_matched: 'Cannot find a loader which may process the request. Notices are:\n%'
}
/**
* Aborts the request. Behaviour of this function for onreadystatechange()
* is identical to IE (most universal and common case). E.g., readyState -> 4
* on abort() after send().
*/
t.abort = function() { with (this) {
if (_ldObj && _ldObj.abort) _ldObj.abort();
_cleanup();
if (readyState == 0) {
// start->abort: no change of readyState (IE behaviour)
return;
}
if (readyState == 1 && !_ldObj) {
// open->abort: no onreadystatechange call, but change readyState to 0 (IE).
// send->abort: change state to 4 (_ldObj is not null when send() is called)
readyState = 0;
return;
}
_changeReadyState(4, true); // 4 in IE & FF on abort() call; Opera does not change to 4.
}}
/**
* Prepares the object for data loading.
* You may also pass URLs like "GET url" or "script.GET url".
*/
t.open = function(method, url, asyncFlag, username, password) { with (this) {
// Extract methor and loader from the URL (if present).
if (url.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)) {
this.loader = RegExp.$2? RegExp.$2 : null;
method = RegExp.$3;
url = RegExp.$4;
}
// Append SID to original URL. Use try...catch for security problems.
try {
if (
document.location.search.match(new RegExp('[&?]' + session_name + '=([^&?]*)'))
|| document.cookie.match(new RegExp('(?:;|^)\\s*' + session_name + '=([^;]*)'))
) {
url += (url.indexOf('?') >= 0? '&' : '?') + session_name + "=" + this.escape(RegExp.$1);
}
} catch (e) {}
// Store open arguments to hash.
_openArgs = {
method: (method || '').toUpperCase(),
url: url,
asyncFlag: asyncFlag,
username: username != null? username : '',
password: password != null? password : ''
}
_ldObj = null;
_changeReadyState(1, true); // compatibility with XMLHttpRequest
return true;
}}
/**
* Sends a request to a server.
*/
t.send = function(content) {
if (!this.readyState) {
// send without open or after abort: no action (IE behaviour).
return;
}
this._changeReadyState(1, true); // compatibility with XMLHttpRequest
this._ldObj = null;
// Prepare to build QUERY_STRING from query hash.
var queryText = [];
var queryElem = [];
if (!this._hash2query(content, null, queryText, queryElem)) return;
// Solve the query hashcode & return on cache hit.
var hash = null;
if (this.caching && !queryElem.length) {
hash = this._openArgs.username + ':' + this._openArgs.password + '@' + this._openArgs.url + '|' + queryText + "#" + this._openArgs.method;
var cache = JsHttpRequest.CACHE[hash];
if (cache) {
this._dataReady(cache[0], cache[1]);
return false;
}
}
// Try all the loaders.
var loader = (this.loader || '').toLowerCase();
if (loader && !JsHttpRequest.LOADERS[loader]) return this._error('unk_loader', loader);
var errors = [];
var lds = JsHttpRequest.LOADERS;
for (var tryLoader in lds) {
var ldr = lds[tryLoader].loader;
if (!ldr) continue; // exclude possibly derived prototype properties from "for .. in".
if (loader && tryLoader != loader) continue;
// Create sending context.
var ldObj = new ldr(this);
JsHttpRequest.extend(ldObj, this._openArgs);
JsHttpRequest.extend(ldObj, {
queryText: queryText.join('&'),
queryElem: queryElem,
id: (new Date().getTime()) + "" + JsHttpRequest.COUNT++,
hash: hash,
span: null
});
var error = ldObj.load();
if (!error) {
// Save loading script.
this._ldObj = ldObj;
JsHttpRequest.PENDING[ldObj.id] = this;
return true;
}
if (!loader) {
errors[errors.length] = '- ' + tryLoader.toUpperCase() + ': ' + this._l(error);
} else {
return this._error(error);
}
}
// If no loader matched, generate error message.
return tryLoader? this._error('no_loader_matched', errors.join('\n')) : this._error('no_loaders');
}
/**
* Returns all response headers (if supported).
*/
t.getAllResponseHeaders = function() { with (this) {
return _ldObj && _ldObj.getAllResponseHeaders? _ldObj.getAllResponseHeaders() : [];
}}
/**
* Returns one response header (if supported).
*/
t.getResponseHeader = function(label) { with (this) {
return _ldObj && _ldObj.getResponseHeader? _ldObj.getResponseHeader(label) : null;
}}
/**
* Adds a request header to a future query.
*/
t.setRequestHeader = function(label, value) { with (this) {
_reqHeaders[_reqHeaders.length] = [label, value];
}}
//
// Internal functions.
//
/**
* Do all the work when a data is ready.
*/
t._dataReady = function(text, js) { with (this) {
if (caching && _ldObj) JsHttpRequest.CACHE[_ldObj.hash] = [text, js];
responseText = responseXML = text;
responseJS = js;
if (js !== null) {
status = 200;
statusText = "OK";
} else {
status = 500;
statusText = "Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}}
/**
* Analog of sprintf(), but translates the first parameter by _errors.
*/
t._l = function(args) {
var i = 0, p = 0, msg = this._errors[args[0]];
// Cannot use replace() with a callback, because it is incompatible with IE5.
while ((p = msg.indexOf('%', p)) >= 0) {
var a = args[++i] + "";
msg = msg.substring(0, p) + a + msg.substring(p + 1, msg.length);
p += 1 + a.length;
}
return msg;
}
/**
* Called on error.
*/
t._error = function(msg) {
msg = this._l(typeof(msg) == 'string'? arguments : msg)
msg = "JsHttpRequest: " + msg;
if (!window.Error) {
// Very old browser...
throw msg;
} else if ((new Error(1, 'test')).description == "test") {
// We MUST (!!!) pass 2 parameters to the Error() constructor for IE5.
throw new Error(1, msg);
} else {
// Mozilla does not support two-parameter call style.
throw new Error(msg);
}
}
/**
* Convert hash to QUERY_STRING.
* If next value is scalar or hash, push it to queryText.
* If next value is form element, push [name, element] to queryElem.
*/
t._hash2query = function(content, prefix, queryText, queryElem) {
if (prefix == null) prefix = "";
if((''+typeof(content)).toLowerCase() == 'object') {
var formAdded = false;
if (content && content.parentNode && content.parentNode.appendChild && content.tagName && content.tagName.toUpperCase() == 'FORM') {
content = { form: content };
}
for (var k in content) {
var v = content[k];
if (v instanceof Function) continue;
var curPrefix = prefix? prefix + '[' + this.escape(k) + ']' : this.escape(k);
var isFormElement = v && v.parentNode && v.parentNode.appendChild && v.tagName;
if (isFormElement) {
var tn = v.tagName.toUpperCase();
if (tn == 'FORM') {
// FORM itself is passed.
formAdded = true;
} else if (tn == 'INPUT' || tn == 'TEXTAREA' || tn == 'SELECT') {
// This is a single form elemenent.
} else {
return this._error('inv_form_el', (v.name||''), v.tagName);
}
queryElem[queryElem.length] = { name: curPrefix, e: v };
} else if (v instanceof Object) {
this._hash2query(v, curPrefix, queryText, queryElem);
} else {
// We MUST skip NULL values, because there is no method
// to pass NULL's via GET or POST request in PHP.
if (v === null) continue;
// Convert JS boolean true and false to corresponding PHP values.
if (v === true) v = 1;
if (v === false) v = '';
queryText[queryText.length] = curPrefix + "=" + this.escape('' + v);
}
if (formAdded && queryElem.length > 1) {
return this._error('must_be_single_el');
}
}
} else {
queryText[queryText.length] = content;
}
return true;
}
/**
* Remove last used script element (clean memory).
*/
t._cleanup = function() {
var ldObj = this._ldObj;
if (!ldObj) return;
// Mark this loading as aborted.
JsHttpRequest.PENDING[ldObj.id] = false;
var span = ldObj.span;
if (!span) return;
// Do NOT use iframe.contentWindow.back() - it is incompatible with Opera 9!
ldObj.span = null;
var closure = function() {
span.parentNode.removeChild(span);
}
// IE5 crashes on setTimeout(function() {...}, ...) construction! Use tmp variable.
JsHttpRequest.setTimeout(closure, 50);
}
/**
* Change current readyState and call trigger method.
*/
t._changeReadyState = function(s, reset) { with (this) {
if (reset) {
status = statusText = responseJS = null;
responseText = '';
}
readyState = s;
if (onreadystatechange) onreadystatechange();
}}
/**
* JS escape() does not quote '+'.
*/
t.escape = function(s) {
return escape(s).replace(new RegExp('\\+','g'), '%2B');
}
}
// Global library variables.
JsHttpRequest.COUNT = 0; // unique ID; used while loading IDs generation
JsHttpRequest.MAX_URL_LEN = 2000; // maximum URL length
JsHttpRequest.CACHE = {}; // cached data
JsHttpRequest.PENDING = {}; // pending loadings
JsHttpRequest.LOADERS = {}; // list of supported data loaders (filled at the bottom of the file)
JsHttpRequest._dummy = function() {}; // avoid memory leaks
/**
* These functions are dirty hacks for IE 5.0 which does not increment a
* reference counter for an object passed via setTimeout(). So, if this
* object (closure function) is out of scope at the moment of timeout
* applying, IE 5.0 crashes.
*/
/**
* Timeout wrappers storage. Used to avoid zeroing of referece counts in IE 5.0.
* Please note that you MUST write "window.setTimeout", not "setTimeout", else
* IE 5.0 crashes again. Strange, very strange...
*/
JsHttpRequest.TIMEOUTS = { s: window.setTimeout, c: window.clearTimeout };
/**
* Wrapper for IE5 buggy setTimeout.
* Use this function instead of a usual setTimeout().
*/
JsHttpRequest.setTimeout = function(func, dt) {
// Always save inside the window object before a call (for FF)!
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.s;
if (typeof(func) == "string") {
id = window.JsHttpRequest_tmp(func, dt);
} else {
var id = null;
var mediator = function() {
func();
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
}
id = window.JsHttpRequest_tmp(mediator, dt);
// Store a reference to the mediator function to the global array
// (reference count >= 1); use timeout ID as an array key;
JsHttpRequest.TIMEOUTS[id] = mediator;
}
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return id;
}
/**
* Complimental wrapper for clearTimeout.
* Use this function instead of usual clearTimeout().
*/
JsHttpRequest.clearTimeout = function(id) {
window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
var r = window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
return r;
}
/**
* Global static function.
* Simple interface for most popular use-cases.
* You may also pass URLs like "GET url" or "script.GET url".
*/
JsHttpRequest.query = function(url, content, onready, nocache) {
var req = new this();
req.caching = !nocache;
req.onreadystatechange = function() {
if (req.readyState == 4) {
onready(req.responseJS, req.responseText);
}
}
req.open(null, url, true);
req.send(content);
}
/**
* Global static function.
* Called by server backend script on data load.
*/
JsHttpRequest.dataReady = function(d) {
var th = this.PENDING[d.id];
delete this.PENDING[d.id];
if (th) {
th._dataReady(d.text, d.js);
} else if (th !== false) {
throw "dataReady(): unknown pending id: " + d.id;
}
}
// Adds all the properties of src to dest.
JsHttpRequest.extend = function(dest, src) {
for (var k in src) dest[k] = src[k];
}
/**
* Each loader has the following properties which must be initialized:
* - method
* - url
* - asyncFlag (ignored)
* - username
* - password
* - queryText (string)
* - queryElem (array)
* - id
* - hash
* - span
*/
// }}}
// {{{ xml
// Loader: XMLHttpRequest or ActiveX.
// [+] GET and POST methods are supported.
// [+] Most native and memory-cheap method.
// [+] Backend data can be browser-cached.
// [-] Cannot work in IE without ActiveX.
// [-] No support for loading from different domains.
// [-] No uploading support.
//
JsHttpRequest.LOADERS.xml = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
xml_no: 'Cannot use XMLHttpRequest or ActiveX loader: not supported',
xml_no_diffdom: 'Cannot use XMLHttpRequest to load data from different domain %',
xml_no_headers: 'Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly',
xml_no_form_upl: 'Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented'
});
this.load = function() {
if (this.queryElem.length) return ['xml_no_form_upl'];
// XMLHttpRequest (and MS ActiveX'es) cannot work with different domains.
if (this.url.match(new RegExp('^([a-z]+://[^\\/]+)(.*)', 'i'))) {
// We MUST also check if protocols matched: cannot send from HTTP
// to HTTPS and vice versa.
if (RegExp.$1.toLowerCase() != document.location.protocol + '//' + document.location.hostname.toLowerCase()) {
return ['xml_no_diffdom', RegExp.$1];
}
}
// Try to obtain a loader.
var xr = null;
if (window.XMLHttpRequest) {
try { xr = new XMLHttpRequest() } catch(e) {}
} else if (window.ActiveXObject) {
try { xr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
if (!xr) try { xr = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
}
if (!xr) return ['xml_no'];
// Loading method detection. We cannot POST if we cannot set "octet-stream"
// header, because we need to process the encoded data in the backend manually.
var canSetHeaders = window.ActiveXObject || xr.setRequestHeader;
if (!this.method) this.method = canSetHeaders && this.queryText.length? 'POST' : 'GET';
// Build & validate the full URL.
if (this.method == 'GET') {
if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
this.queryText = '';
if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
} else if (this.method == 'POST' && !canSetHeaders) {
return ['xml_no_headers'];
}
// Add ID to the url if we need to disable the cache.
this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + (req.caching? '0' : this.id) + '-xml';
// Assign the result handler.
var id = this.id;
xr.onreadystatechange = function() {
if (xr.readyState != 4) return;
// Avoid memory leak by removing the closure.
xr.onreadystatechange = JsHttpRequest._dummy;
req.status = null;
try {
// In case of abort() call, xr.status is unavailable and generates exception.
// But xr.readyState equals to 4 in this case. Stupid behaviour. :-(
req.status = xr.status;
req.responseText = xr.responseText;
} catch (e) {}
if (!req.status) return;
try {
// Prepare generator function & catch syntax errors on this stage.
eval('JsHttpRequest._tmp = function(id) { var d = ' + req.responseText + '; d.id = id; JsHttpRequest.dataReady(d); }');
} catch (e) {
// Note that FF 2.0 does not throw any error from onreadystatechange handler.
return req._error('js_invalid', req.responseText)
}
// Call associated dataReady() outside the try-catch block
// to pass exceptions in onreadystatechange in usual manner.
JsHttpRequest._tmp(id);
JsHttpRequest._tmp = null;
};
// Open & send the request.
xr.open(this.method, this.url, true, this.username, this.password);
if (canSetHeaders) {
// Pass pending headers.
for (var i = 0; i < req._reqHeaders.length; i++) {
xr.setRequestHeader(req._reqHeaders[i][0], req._reqHeaders[i][1]);
}
// Set non-default Content-type. We cannot use
// "application/x-www-form-urlencoded" here, because
// in PHP variable HTTP_RAW_POST_DATA is accessible only when
// enctype is not default (e.g., "application/octet-stream"
// is a good start). We parse POST data manually in backend
// library code. Note that Safari sets by default "x-www-form-urlencoded"
// header, but FF sets "text/xml" by default.
xr.setRequestHeader('Content-Type', 'application/octet-stream');
}
xr.send(this.queryText);
// No SPAN is used for this loader.
this.span = null;
this.xr = xr; // save for later usage on abort()
// Success.
return null;
}
// Override req.getAllResponseHeaders method.
this.getAllResponseHeaders = function() {
return this.xr.getAllResponseHeaders();
}
// Override req.getResponseHeader method.
this.getResponseHeader = function(label) {
return this.xr.getResponseHeader(label);
}
this.abort = function() {
this.xr.abort();
this.xr = null;
}
}}
// }}}
// {{{ script
// Loader: SCRIPT tag.
// [+] Most cross-browser.
// [+] Supports loading from different domains.
// [-] Only GET method is supported.
// [-] No uploading support.
// [-] Backend data cannot be browser-cached.
//
JsHttpRequest.LOADERS.script = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
script_only_get: 'Cannot use SCRIPT loader: it supports only GET method',
script_no_form: 'Cannot use SCRIPT loader: direct form elements using and uploading are not implemented'
})
this.load = function() {
// Move GET parameters to the URL itself.
if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + this.id + '-' + 'script';
this.queryText = '';
if (!this.method) this.method = 'GET';
if (this.method !== 'GET') return ['script_only_get'];
if (this.queryElem.length) return ['script_no_form'];
if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
var th = this, d = document, s = null, b = d.body;
if (!window.opera) {
// Safari, IE, FF, Opera 7.20.
this.span = s = d.createElement('SCRIPT');
var closure = function() {
s.language = 'JavaScript';
if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
b.insertBefore(s, b.lastChild);
}
} else {
// Oh shit! Damned stupid Opera 7.23 does not allow to create SCRIPT
// element over createElement (in HEAD or BODY section or in nested SPAN -
// no matter): it is created deadly, and does not response the href assignment.
// So - always create SPAN.
this.span = s = d.createElement('SPAN');
s.style.display = 'none';
b.insertBefore(s, b.lastChild);
s.innerHTML = 'Workaround for IE.<s'+'cript></' + 'script>';
var closure = function() {
s = s.getElementsByTagName('SCRIPT')[0]; // get with timeout!
s.language = 'JavaScript';
if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
}
}
JsHttpRequest.setTimeout(closure, 10);
// Success.
return null;
}
}}
// }}}
// {{{ form
// Loader: FORM & IFRAME.
// [+] Supports file uploading.
// [+] GET and POST methods are supported.
// [+] Supports loading from different domains.
// [-] Uses a lot of system resources.
// [-] Backend data cannot be browser-cached.
// [-] Pollutes browser history on some old browsers.
//
JsHttpRequest.LOADERS.form = { loader: function(req) {
JsHttpRequest.extend(req._errors, {
form_el_not_belong: 'Element "%" does not belong to any form!',
form_el_belong_diff: 'Element "%" belongs to a different form. All elements must belong to the same form!',
form_el_inv_enctype: 'Attribute "enctype" of the form must be "%" (for IE), "%" given.'
})
this.load = function() {
var th = this;
if (!th.method) th.method = 'POST';
th.url += (th.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + th.id + '-' + 'form';
// If GET, build full URL. Then copy QUERY_STRING to queryText.
if (th.method == 'GET') {
if (th.queryText) th.url += (th.url.indexOf('?') >= 0? '&' : '?') + th.queryText;
if (th.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
var p = th.url.split('?', 2);
th.url = p[0];
th.queryText = p[1] || '';
}
// Check if all form elements belong to same form.
var form = null;
var wholeFormSending = false;
if (th.queryElem.length) {
if (th.queryElem[0].e.tagName.toUpperCase() == 'FORM') {
// Whole FORM sending.
form = th.queryElem[0].e;
wholeFormSending = true;
th.queryElem = [];
} else {
// If we have at least one form element, we use its FORM as a POST container.
form = th.queryElem[0].e.form;
// Validate all the elements.
for (var i = 0; i < th.queryElem.length; i++) {
var e = th.queryElem[i].e;
if (!e.form) {
return ['form_el_not_belong', e.name];
}
if (e.form != form) {
return ['form_el_belong_diff', e.name];
}
}
}
// Check enctype of the form.
if (th.method == 'POST') {
var need = "multipart/form-data";
var given = (form.attributes.encType && form.attributes.encType.nodeValue) || (form.attributes.enctype && form.attributes.enctype.value) || form.enctype;
if (given != need) {
return ['form_el_inv_enctype', need, given];
}
}
}
// Create invisible IFRAME with temporary form (form is used on empty queryElem).
// We ALWAYS create th IFRAME in the document of the form - for Opera 7.20.
var d = form && (form.ownerDocument || form.document) || document;
var ifname = 'jshr_i_' + th.id;
var s = th.span = d.createElement('DIV');
s.style.position = 'absolute';
s.style.display = 'none';
s.style.visibility = 'hidden';
s.innerHTML =
(form? '' : '<form' + (th.method == 'POST'? ' enctype="multipart/form-data" method="post"' : '') + '></form>') + // stupid IE, MUST use innerHTML assignment :-(
'<iframe name="' + ifname + '" id="' + ifname + '" style="width:0px; height:0px; overflow:hidden; border:none"></iframe>'
if (!form) {
form = th.span.firstChild;
}
// Insert generated form inside the document.
// Be careful: don't forget to close FORM container in document body!
d.body.insertBefore(s, d.body.lastChild);
// Function to safely set the form attributes. Parameter attr is NOT a hash
// but an array, because "for ... in" may badly iterate over derived attributes.
var setAttributes = function(e, attr) {
var sv = [];
var form = e;
// This strange algorythm is needed, because form may contain element
// with name like 'action'. In IE for such attribute will be returned
// form element node, not form action. Workaround: copy all attributes
// to new empty form and work with it, then copy them back. This is
// THE ONLY working algorythm since a lot of bugs in IE5.0 (e.g.
// with e.attributes property: causes IE crash).
if (e.mergeAttributes) {
var form = d.createElement('form');
form.mergeAttributes(e, false);
}
for (var i = 0; i < attr.length; i++) {
var k = attr[i][0], v = attr[i][1];
// TODO: http://forum.dklab.ru/viewtopic.php?p=129059#129059
sv[sv.length] = [k, form.getAttribute(k)];
form.setAttribute(k, v);
}
if (e.mergeAttributes) {
e.mergeAttributes(form, false);
}
return sv;
}
// Run submit with delay - for old Opera: it needs some time to create IFRAME.
var closure = function() {
// Save JsHttpRequest object to new IFRAME.
top.JsHttpRequestGlobal = JsHttpRequest;
// Disable ALL the form elements.
var savedNames = [];
if (!wholeFormSending) {
for (var i = 0, n = form.elements.length; i < n; i++) {
savedNames[i] = form.elements[i].name;
form.elements[i].name = '';
}
}
// Insert hidden fields to the form.
var qt = th.queryText.split('&');
for (var i = qt.length - 1; i >= 0; i--) {
var pair = qt[i].split('=', 2);
var e = d.createElement('INPUT');
e.type = 'hidden';
e.name = unescape(pair[0]);
e.value = pair[1] != null? unescape(pair[1]) : '';
form.appendChild(e);
}
// Change names of along user-passed form elements.
for (var i = 0; i < th.queryElem.length; i++) {
th.queryElem[i].e.name = th.queryElem[i].name;
}
// Temporary modify form attributes, submit form, restore attributes back.
var sv = setAttributes(
form,
[
['action', th.url],
['method', th.method],
['onsubmit', null],
['target', ifname]
]
);
form.submit();
setAttributes(form, sv);
// Remove generated temporary hidden elements from the top of the form.
for (var i = 0; i < qt.length; i++) {
// Use "form.firstChild.parentNode", not "form", or IE5 crashes!
form.lastChild.parentNode.removeChild(form.lastChild);
}
// Enable all disabled elements back.
if (!wholeFormSending) {
for (var i = 0, n = form.elements.length; i < n; i++) {
form.elements[i].name = savedNames[i];
}
}
}
JsHttpRequest.setTimeout(closure, 100);
// Success.
return null;
}
}}
// }}}

View file

@ -0,0 +1,422 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (form support only!)
* Minimized version: see debug directory for the complete one.
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
function JsHttpRequest(){
var t=this;
t.onreadystatechange=null;
t.readyState=0;
t.responseText=null;
t.responseXML=null;
t.status=200;
t.statusText="OK";
t.responseJS=null;
t.caching=false;
t.loader=null;
t.session_name="PHPSESSID";
t._ldObj=null;
t._reqHeaders=[];
t._openArgs=null;
t._errors={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%"};
t.abort=function(){
with(this){
if(_ldObj&&_ldObj.abort){
_ldObj.abort();
}
_cleanup();
if(readyState==0){
return;
}
if(readyState==1&&!_ldObj){
readyState=0;
return;
}
_changeReadyState(4,true);
}
};
t.open=function(_2,_3,_4,_5,_6){
with(this){
if(_3.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){
this.loader=RegExp.$2?RegExp.$2:null;
_2=RegExp.$3;
_3=RegExp.$4;
}
try{
if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){
_3+=(_3.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1);
}
}
catch(e){
}
_openArgs={method:(_2||"").toUpperCase(),url:_3,asyncFlag:_4,username:_5!=null?_5:"",password:_6!=null?_6:""};
_ldObj=null;
_changeReadyState(1,true);
return true;
}
};
t.send=function(_7){
if(!this.readyState){
return;
}
this._changeReadyState(1,true);
this._ldObj=null;
var _8=[];
var _9=[];
if(!this._hash2query(_7,null,_8,_9)){
return;
}
var _a=null;
if(this.caching&&!_9.length){
_a=this._openArgs.username+":"+this._openArgs.password+"@"+this._openArgs.url+"|"+_8+"#"+this._openArgs.method;
var _b=JsHttpRequest.CACHE[_a];
if(_b){
this._dataReady(_b[0],_b[1]);
return false;
}
}
var _c=(this.loader||"").toLowerCase();
if(_c&&!JsHttpRequest.LOADERS[_c]){
return this._error("unk_loader",_c);
}
var _d=[];
var _e=JsHttpRequest.LOADERS;
for(var _f in _e){
var ldr=_e[_f].loader;
if(!ldr){
continue;
}
if(_c&&_f!=_c){
continue;
}
var _11=new ldr(this);
JsHttpRequest.extend(_11,this._openArgs);
JsHttpRequest.extend(_11,{queryText:_8.join("&"),queryElem:_9,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:_a,span:null});
var _12=_11.load();
if(!_12){
this._ldObj=_11;
JsHttpRequest.PENDING[_11.id]=this;
return true;
}
if(!_c){
_d[_d.length]="- "+_f.toUpperCase()+": "+this._l(_12);
}else{
return this._error(_12);
}
}
return _f?this._error("no_loader_matched",_d.join("\n")):this._error("no_loaders");
};
t.getAllResponseHeaders=function(){
with(this){
return _ldObj&&_ldObj.getAllResponseHeaders?_ldObj.getAllResponseHeaders():[];
}
};
t.getResponseHeader=function(_13){
with(this){
return _ldObj&&_ldObj.getResponseHeader?_ldObj.getResponseHeader(_13):null;
}
};
t.setRequestHeader=function(_14,_15){
with(this){
_reqHeaders[_reqHeaders.length]=[_14,_15];
}
};
t._dataReady=function(_16,js){
with(this){
if(caching&&_ldObj){
JsHttpRequest.CACHE[_ldObj.hash]=[_16,js];
}
responseText=responseXML=_16;
responseJS=js;
if(js!==null){
status=200;
statusText="OK";
}else{
status=500;
statusText="Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}
};
t._l=function(_18){
var i=0,p=0,msg=this._errors[_18[0]];
while((p=msg.indexOf("%",p))>=0){
var a=_18[++i]+"";
msg=msg.substring(0,p)+a+msg.substring(p+1,msg.length);
p+=1+a.length;
}
return msg;
};
t._error=function(msg){
msg=this._l(typeof (msg)=="string"?arguments:msg);
msg="JsHttpRequest: "+msg;
if(!window.Error){
throw msg;
}else{
if((new Error(1,"test")).description=="test"){
throw new Error(1,msg);
}else{
throw new Error(msg);
}
}
};
t._hash2query=function(_1e,_1f,_20,_21){
if(_1f==null){
_1f="";
}
if((""+typeof (_1e)).toLowerCase()=="object"){
var _22=false;
if(_1e&&_1e.parentNode&&_1e.parentNode.appendChild&&_1e.tagName&&_1e.tagName.toUpperCase()=="FORM"){
_1e={form:_1e};
}
for(var k in _1e){
var v=_1e[k];
if(v instanceof Function){
continue;
}
var _25=_1f?_1f+"["+this.escape(k)+"]":this.escape(k);
var _26=v&&v.parentNode&&v.parentNode.appendChild&&v.tagName;
if(_26){
var tn=v.tagName.toUpperCase();
if(tn=="FORM"){
_22=true;
}else{
if(tn=="INPUT"||tn=="TEXTAREA"||tn=="SELECT"){
}else{
return this._error("inv_form_el",(v.name||""),v.tagName);
}
}
_21[_21.length]={name:_25,e:v};
}else{
if(v instanceof Object){
this._hash2query(v,_25,_20,_21);
}else{
if(v===null){
continue;
}
if(v===true){
v=1;
}
if(v===false){
v="";
}
_20[_20.length]=_25+"="+this.escape(""+v);
}
}
if(_22&&_21.length>1){
return this._error("must_be_single_el");
}
}
}else{
_20[_20.length]=_1e;
}
return true;
};
t._cleanup=function(){
var _28=this._ldObj;
if(!_28){
return;
}
JsHttpRequest.PENDING[_28.id]=false;
var _29=_28.span;
if(!_29){
return;
}
_28.span=null;
var _2a=function(){
_29.parentNode.removeChild(_29);
};
JsHttpRequest.setTimeout(_2a,50);
};
t._changeReadyState=function(s,_2c){
with(this){
if(_2c){
status=statusText=responseJS=null;
responseText="";
}
readyState=s;
if(onreadystatechange){
onreadystatechange();
}
}
};
t.escape=function(s){
return escape(s).replace(new RegExp("\\+","g"),"%2B");
};
}
JsHttpRequest.COUNT=0;
JsHttpRequest.MAX_URL_LEN=2000;
JsHttpRequest.CACHE={};
JsHttpRequest.PENDING={};
JsHttpRequest.LOADERS={};
JsHttpRequest._dummy=function(){
};
JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};
JsHttpRequest.setTimeout=function(_2e,dt){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;
if(typeof (_2e)=="string"){
id=window.JsHttpRequest_tmp(_2e,dt);
}else{
var id=null;
var _31=function(){
_2e();
delete JsHttpRequest.TIMEOUTS[id];
};
id=window.JsHttpRequest_tmp(_31,dt);
JsHttpRequest.TIMEOUTS[id]=_31;
}
window.JsHttpRequest_tmp=null;
return id;
};
JsHttpRequest.clearTimeout=function(id){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id];
var r=window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp=null;
return r;
};
JsHttpRequest.query=function(url,_35,_36,_37){
var req=new this();
req.caching=!_37;
req.onreadystatechange=function(){
if(req.readyState==4){
_36(req.responseJS,req.responseText);
}
};
req.open(null,url,true);
req.send(_35);
};
JsHttpRequest.dataReady=function(d){
var th=this.PENDING[d.id];
delete this.PENDING[d.id];
if(th){
th._dataReady(d.text,d.js);
}else{
if(th!==false){
throw "dataReady(): unknown pending id: "+d.id;
}
}
};
JsHttpRequest.extend=function(_3b,src){
for(var k in src){
_3b[k]=src[k];
}
};
JsHttpRequest.LOADERS.form={loader:function(req){
JsHttpRequest.extend(req._errors,{form_el_not_belong:"Element \"%\" does not belong to any form!",form_el_belong_diff:"Element \"%\" belongs to a different form. All elements must belong to the same form!",form_el_inv_enctype:"Attribute \"enctype\" of the form must be \"%\" (for IE), \"%\" given."});
this.load=function(){
var th=this;
if(!th.method){
th.method="POST";
}
th.url+=(th.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+th.id+"-"+"form";
if(th.method=="GET"){
if(th.queryText){
th.url+=(th.url.indexOf("?")>=0?"&":"?")+th.queryText;
}
if(th.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var p=th.url.split("?",2);
th.url=p[0];
th.queryText=p[1]||"";
}
var _41=null;
var _42=false;
if(th.queryElem.length){
if(th.queryElem[0].e.tagName.toUpperCase()=="FORM"){
_41=th.queryElem[0].e;
_42=true;
th.queryElem=[];
}else{
_41=th.queryElem[0].e.form;
for(var i=0;i<th.queryElem.length;i++){
var e=th.queryElem[i].e;
if(!e.form){
return ["form_el_not_belong",e.name];
}
if(e.form!=_41){
return ["form_el_belong_diff",e.name];
}
}
}
if(th.method=="POST"){
var _45="multipart/form-data";
var _46=(_41.attributes.encType&&_41.attributes.encType.nodeValue)||(_41.attributes.enctype&&_41.attributes.enctype.value)||_41.enctype;
if(_46!=_45){
return ["form_el_inv_enctype",_45,_46];
}
}
}
var d=_41&&(_41.ownerDocument||_41.document)||document;
var _48="jshr_i_"+th.id;
var s=th.span=d.createElement("DIV");
s.style.position="absolute";
s.style.display="none";
s.style.visibility="hidden";
s.innerHTML=(_41?"":"<form"+(th.method=="POST"?" enctype=\"multipart/form-data\" method=\"post\"":"")+"></form>")+"<iframe name=\""+_48+"\" id=\""+_48+"\" style=\"width:0px; height:0px; overflow:hidden; border:none\"></iframe>";
if(!_41){
_41=th.span.firstChild;
}
d.body.insertBefore(s,d.body.lastChild);
var _4a=function(e,_4c){
var sv=[];
var _4e=e;
if(e.mergeAttributes){
var _4e=d.createElement("form");
_4e.mergeAttributes(e,false);
}
for(var i=0;i<_4c.length;i++){
var k=_4c[i][0],v=_4c[i][1];
sv[sv.length]=[k,_4e.getAttribute(k)];
_4e.setAttribute(k,v);
}
if(e.mergeAttributes){
e.mergeAttributes(_4e,false);
}
return sv;
};
var _52=function(){
top.JsHttpRequestGlobal=JsHttpRequest;
var _53=[];
if(!_42){
for(var i=0,n=_41.elements.length;i<n;i++){
_53[i]=_41.elements[i].name;
_41.elements[i].name="";
}
}
var qt=th.queryText.split("&");
for(var i=qt.length-1;i>=0;i--){
var _57=qt[i].split("=",2);
var e=d.createElement("INPUT");
e.type="hidden";
e.name=unescape(_57[0]);
e.value=_57[1]!=null?unescape(_57[1]):"";
_41.appendChild(e);
}
for(var i=0;i<th.queryElem.length;i++){
th.queryElem[i].e.name=th.queryElem[i].name;
}
var sv=_4a(_41,[["action",th.url],["method",th.method],["onsubmit",null],["target",_48]]);
_41.submit();
_4a(_41,sv);
for(var i=0;i<qt.length;i++){
_41.lastChild.parentNode.removeChild(_41.lastChild);
}
if(!_42){
for(var i=0,n=_41.elements.length;i<n;i++){
_41.elements[i].name=_53[i];
}
}
};
JsHttpRequest.setTimeout(_52,100);
return null;
};
}};

View file

@ -0,0 +1,465 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (script-xml support only!)
* Minimized version: see debug directory for the complete one.
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
function JsHttpRequest(){
var t=this;
t.onreadystatechange=null;
t.readyState=0;
t.responseText=null;
t.responseXML=null;
t.status=200;
t.statusText="OK";
t.responseJS=null;
t.caching=false;
t.loader=null;
t.session_name="PHPSESSID";
t._ldObj=null;
t._reqHeaders=[];
t._openArgs=null;
t._errors={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%"};
t.abort=function(){
with(this){
if(_ldObj&&_ldObj.abort){
_ldObj.abort();
}
_cleanup();
if(readyState==0){
return;
}
if(readyState==1&&!_ldObj){
readyState=0;
return;
}
_changeReadyState(4,true);
}
};
t.open=function(_2,_3,_4,_5,_6){
with(this){
if(_3.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){
this.loader=RegExp.$2?RegExp.$2:null;
_2=RegExp.$3;
_3=RegExp.$4;
}
try{
if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){
_3+=(_3.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1);
}
}
catch(e){
}
_openArgs={method:(_2||"").toUpperCase(),url:_3,asyncFlag:_4,username:_5!=null?_5:"",password:_6!=null?_6:""};
_ldObj=null;
_changeReadyState(1,true);
return true;
}
};
t.send=function(_7){
if(!this.readyState){
return;
}
this._changeReadyState(1,true);
this._ldObj=null;
var _8=[];
var _9=[];
if(!this._hash2query(_7,null,_8,_9)){
return;
}
var _a=null;
if(this.caching&&!_9.length){
_a=this._openArgs.username+":"+this._openArgs.password+"@"+this._openArgs.url+"|"+_8+"#"+this._openArgs.method;
var _b=JsHttpRequest.CACHE[_a];
if(_b){
this._dataReady(_b[0],_b[1]);
return false;
}
}
var _c=(this.loader||"").toLowerCase();
if(_c&&!JsHttpRequest.LOADERS[_c]){
return this._error("unk_loader",_c);
}
var _d=[];
var _e=JsHttpRequest.LOADERS;
for(var _f in _e){
var ldr=_e[_f].loader;
if(!ldr){
continue;
}
if(_c&&_f!=_c){
continue;
}
var _11=new ldr(this);
JsHttpRequest.extend(_11,this._openArgs);
JsHttpRequest.extend(_11,{queryText:_8.join("&"),queryElem:_9,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:_a,span:null});
var _12=_11.load();
if(!_12){
this._ldObj=_11;
JsHttpRequest.PENDING[_11.id]=this;
return true;
}
if(!_c){
_d[_d.length]="- "+_f.toUpperCase()+": "+this._l(_12);
}else{
return this._error(_12);
}
}
return _f?this._error("no_loader_matched",_d.join("\n")):this._error("no_loaders");
};
t.getAllResponseHeaders=function(){
with(this){
return _ldObj&&_ldObj.getAllResponseHeaders?_ldObj.getAllResponseHeaders():[];
}
};
t.getResponseHeader=function(_13){
with(this){
return _ldObj&&_ldObj.getResponseHeader?_ldObj.getResponseHeader(_13):null;
}
};
t.setRequestHeader=function(_14,_15){
with(this){
_reqHeaders[_reqHeaders.length]=[_14,_15];
}
};
t._dataReady=function(_16,js){
with(this){
if(caching&&_ldObj){
JsHttpRequest.CACHE[_ldObj.hash]=[_16,js];
}
responseText=responseXML=_16;
responseJS=js;
if(js!==null){
status=200;
statusText="OK";
}else{
status=500;
statusText="Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}
};
t._l=function(_18){
var i=0,p=0,msg=this._errors[_18[0]];
while((p=msg.indexOf("%",p))>=0){
var a=_18[++i]+"";
msg=msg.substring(0,p)+a+msg.substring(p+1,msg.length);
p+=1+a.length;
}
return msg;
};
t._error=function(msg){
msg=this._l(typeof (msg)=="string"?arguments:msg);
msg="JsHttpRequest: "+msg;
if(!window.Error){
throw msg;
}else{
if((new Error(1,"test")).description=="test"){
throw new Error(1,msg);
}else{
throw new Error(msg);
}
}
};
t._hash2query=function(_1e,_1f,_20,_21){
if(_1f==null){
_1f="";
}
if((""+typeof (_1e)).toLowerCase()=="object"){
var _22=false;
if(_1e&&_1e.parentNode&&_1e.parentNode.appendChild&&_1e.tagName&&_1e.tagName.toUpperCase()=="FORM"){
_1e={form:_1e};
}
for(var k in _1e){
var v=_1e[k];
if(v instanceof Function){
continue;
}
var _25=_1f?_1f+"["+this.escape(k)+"]":this.escape(k);
var _26=v&&v.parentNode&&v.parentNode.appendChild&&v.tagName;
if(_26){
var tn=v.tagName.toUpperCase();
if(tn=="FORM"){
_22=true;
}else{
if(tn=="INPUT"||tn=="TEXTAREA"||tn=="SELECT"){
}else{
return this._error("inv_form_el",(v.name||""),v.tagName);
}
}
_21[_21.length]={name:_25,e:v};
}else{
if(v instanceof Object){
this._hash2query(v,_25,_20,_21);
}else{
if(v===null){
continue;
}
if(v===true){
v=1;
}
if(v===false){
v="";
}
_20[_20.length]=_25+"="+this.escape(""+v);
}
}
if(_22&&_21.length>1){
return this._error("must_be_single_el");
}
}
}else{
_20[_20.length]=_1e;
}
return true;
};
t._cleanup=function(){
var _28=this._ldObj;
if(!_28){
return;
}
JsHttpRequest.PENDING[_28.id]=false;
var _29=_28.span;
if(!_29){
return;
}
_28.span=null;
var _2a=function(){
_29.parentNode.removeChild(_29);
};
JsHttpRequest.setTimeout(_2a,50);
};
t._changeReadyState=function(s,_2c){
with(this){
if(_2c){
status=statusText=responseJS=null;
responseText="";
}
readyState=s;
if(onreadystatechange){
onreadystatechange();
}
}
};
t.escape=function(s){
return escape(s).replace(new RegExp("\\+","g"),"%2B");
};
}
JsHttpRequest.COUNT=0;
JsHttpRequest.MAX_URL_LEN=2000;
JsHttpRequest.CACHE={};
JsHttpRequest.PENDING={};
JsHttpRequest.LOADERS={};
JsHttpRequest._dummy=function(){
};
JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};
JsHttpRequest.setTimeout=function(_2e,dt){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;
if(typeof (_2e)=="string"){
id=window.JsHttpRequest_tmp(_2e,dt);
}else{
var id=null;
var _31=function(){
_2e();
delete JsHttpRequest.TIMEOUTS[id];
};
id=window.JsHttpRequest_tmp(_31,dt);
JsHttpRequest.TIMEOUTS[id]=_31;
}
window.JsHttpRequest_tmp=null;
return id;
};
JsHttpRequest.clearTimeout=function(id){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id];
var r=window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp=null;
return r;
};
JsHttpRequest.query=function(url,_35,_36,_37){
var req=new this();
req.caching=!_37;
req.onreadystatechange=function(){
if(req.readyState==4){
_36(req.responseJS,req.responseText);
}
};
req.open(null,url,true);
req.send(_35);
};
JsHttpRequest.dataReady=function(d){
var th=this.PENDING[d.id];
delete this.PENDING[d.id];
if(th){
th._dataReady(d.text,d.js);
}else{
if(th!==false){
throw "dataReady(): unknown pending id: "+d.id;
}
}
};
JsHttpRequest.extend=function(_3b,src){
for(var k in src){
_3b[k]=src[k];
}
};
JsHttpRequest.LOADERS.script={loader:function(req){
JsHttpRequest.extend(req._errors,{script_only_get:"Cannot use SCRIPT loader: it supports only GET method",script_no_form:"Cannot use SCRIPT loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+this.id+"-"+"script";
this.queryText="";
if(!this.method){
this.method="GET";
}
if(this.method!=="GET"){
return ["script_only_get"];
}
if(this.queryElem.length){
return ["script_no_form"];
}
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var th=this,d=document,s=null,b=d.body;
if(!window.opera){
this.span=s=d.createElement("SCRIPT");
var _43=function(){
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
b.insertBefore(s,b.lastChild);
};
}else{
this.span=s=d.createElement("SPAN");
s.style.display="none";
b.insertBefore(s,b.lastChild);
s.innerHTML="Workaround for IE.<s"+"cript></"+"script>";
var _43=function(){
s=s.getElementsByTagName("SCRIPT")[0];
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
};
}
JsHttpRequest.setTimeout(_43,10);
return null;
};
}};
JsHttpRequest.LOADERS.xml={loader:function(req){
JsHttpRequest.extend(req._errors,{xml_no:"Cannot use XMLHttpRequest or ActiveX loader: not supported",xml_no_diffdom:"Cannot use XMLHttpRequest to load data from different domain %",xml_no_headers:"Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly",xml_no_form_upl:"Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryElem.length){
return ["xml_no_form_upl"];
}
if(this.url.match(new RegExp("^([a-z]+://[^\\/]+)(.*)","i"))){
if(RegExp.$1.toLowerCase()!=document.location.protocol+"//"+document.location.hostname.toLowerCase()){
return ["xml_no_diffdom",RegExp.$1];
}
}
var xr=null;
if(window.XMLHttpRequest){
try{
xr=new XMLHttpRequest();
}
catch(e){
}
}else{
if(window.ActiveXObject){
try{
xr=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
if(!xr){
try{
xr=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
}
}
}
}
if(!xr){
return ["xml_no"];
}
var _46=window.ActiveXObject||xr.setRequestHeader;
if(!this.method){
this.method=_46&&this.queryText.length?"POST":"GET";
}
if(this.method=="GET"){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.queryText="";
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
}else{
if(this.method=="POST"&&!_46){
return ["xml_no_headers"];
}
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+(req.caching?"0":this.id)+"-xml";
var id=this.id;
xr.onreadystatechange=function(){
if(xr.readyState!=4){
return;
}
xr.onreadystatechange=JsHttpRequest._dummy;
req.status=null;
try{
req.status=xr.status;
req.responseText=xr.responseText;
}
catch(e){
}
if(!req.status){
return;
}
try{
eval("JsHttpRequest._tmp = function(id) { var d = "+req.responseText+"; d.id = id; JsHttpRequest.dataReady(d); }");
}
catch(e){
return req._error("js_invalid",req.responseText);
}
JsHttpRequest._tmp(id);
JsHttpRequest._tmp=null;
};
xr.open(this.method,this.url,true,this.username,this.password);
if(_46){
for(var i=0;i<req._reqHeaders.length;i++){
xr.setRequestHeader(req._reqHeaders[i][0],req._reqHeaders[i][1]);
}
xr.setRequestHeader("Content-Type","application/octet-stream");
}
xr.send(this.queryText);
this.span=null;
this.xr=xr;
return null;
};
this.getAllResponseHeaders=function(){
return this.xr.getAllResponseHeaders();
};
this.getResponseHeader=function(_49){
return this.xr.getResponseHeader(_49);
};
this.abort=function(){
this.xr.abort();
this.xr=null;
};
}};

View file

@ -0,0 +1,362 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (script support only!)
* Minimized version: see debug directory for the complete one.
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
function JsHttpRequest(){
var t=this;
t.onreadystatechange=null;
t.readyState=0;
t.responseText=null;
t.responseXML=null;
t.status=200;
t.statusText="OK";
t.responseJS=null;
t.caching=false;
t.loader=null;
t.session_name="PHPSESSID";
t._ldObj=null;
t._reqHeaders=[];
t._openArgs=null;
t._errors={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%"};
t.abort=function(){
with(this){
if(_ldObj&&_ldObj.abort){
_ldObj.abort();
}
_cleanup();
if(readyState==0){
return;
}
if(readyState==1&&!_ldObj){
readyState=0;
return;
}
_changeReadyState(4,true);
}
};
t.open=function(_2,_3,_4,_5,_6){
with(this){
if(_3.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){
this.loader=RegExp.$2?RegExp.$2:null;
_2=RegExp.$3;
_3=RegExp.$4;
}
try{
if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){
_3+=(_3.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1);
}
}
catch(e){
}
_openArgs={method:(_2||"").toUpperCase(),url:_3,asyncFlag:_4,username:_5!=null?_5:"",password:_6!=null?_6:""};
_ldObj=null;
_changeReadyState(1,true);
return true;
}
};
t.send=function(_7){
if(!this.readyState){
return;
}
this._changeReadyState(1,true);
this._ldObj=null;
var _8=[];
var _9=[];
if(!this._hash2query(_7,null,_8,_9)){
return;
}
var _a=null;
if(this.caching&&!_9.length){
_a=this._openArgs.username+":"+this._openArgs.password+"@"+this._openArgs.url+"|"+_8+"#"+this._openArgs.method;
var _b=JsHttpRequest.CACHE[_a];
if(_b){
this._dataReady(_b[0],_b[1]);
return false;
}
}
var _c=(this.loader||"").toLowerCase();
if(_c&&!JsHttpRequest.LOADERS[_c]){
return this._error("unk_loader",_c);
}
var _d=[];
var _e=JsHttpRequest.LOADERS;
for(var _f in _e){
var ldr=_e[_f].loader;
if(!ldr){
continue;
}
if(_c&&_f!=_c){
continue;
}
var _11=new ldr(this);
JsHttpRequest.extend(_11,this._openArgs);
JsHttpRequest.extend(_11,{queryText:_8.join("&"),queryElem:_9,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:_a,span:null});
var _12=_11.load();
if(!_12){
this._ldObj=_11;
JsHttpRequest.PENDING[_11.id]=this;
return true;
}
if(!_c){
_d[_d.length]="- "+_f.toUpperCase()+": "+this._l(_12);
}else{
return this._error(_12);
}
}
return _f?this._error("no_loader_matched",_d.join("\n")):this._error("no_loaders");
};
t.getAllResponseHeaders=function(){
with(this){
return _ldObj&&_ldObj.getAllResponseHeaders?_ldObj.getAllResponseHeaders():[];
}
};
t.getResponseHeader=function(_13){
with(this){
return _ldObj&&_ldObj.getResponseHeader?_ldObj.getResponseHeader(_13):null;
}
};
t.setRequestHeader=function(_14,_15){
with(this){
_reqHeaders[_reqHeaders.length]=[_14,_15];
}
};
t._dataReady=function(_16,js){
with(this){
if(caching&&_ldObj){
JsHttpRequest.CACHE[_ldObj.hash]=[_16,js];
}
responseText=responseXML=_16;
responseJS=js;
if(js!==null){
status=200;
statusText="OK";
}else{
status=500;
statusText="Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}
};
t._l=function(_18){
var i=0,p=0,msg=this._errors[_18[0]];
while((p=msg.indexOf("%",p))>=0){
var a=_18[++i]+"";
msg=msg.substring(0,p)+a+msg.substring(p+1,msg.length);
p+=1+a.length;
}
return msg;
};
t._error=function(msg){
msg=this._l(typeof (msg)=="string"?arguments:msg);
msg="JsHttpRequest: "+msg;
if(!window.Error){
throw msg;
}else{
if((new Error(1,"test")).description=="test"){
throw new Error(1,msg);
}else{
throw new Error(msg);
}
}
};
t._hash2query=function(_1e,_1f,_20,_21){
if(_1f==null){
_1f="";
}
if((""+typeof (_1e)).toLowerCase()=="object"){
var _22=false;
if(_1e&&_1e.parentNode&&_1e.parentNode.appendChild&&_1e.tagName&&_1e.tagName.toUpperCase()=="FORM"){
_1e={form:_1e};
}
for(var k in _1e){
var v=_1e[k];
if(v instanceof Function){
continue;
}
var _25=_1f?_1f+"["+this.escape(k)+"]":this.escape(k);
var _26=v&&v.parentNode&&v.parentNode.appendChild&&v.tagName;
if(_26){
var tn=v.tagName.toUpperCase();
if(tn=="FORM"){
_22=true;
}else{
if(tn=="INPUT"||tn=="TEXTAREA"||tn=="SELECT"){
}else{
return this._error("inv_form_el",(v.name||""),v.tagName);
}
}
_21[_21.length]={name:_25,e:v};
}else{
if(v instanceof Object){
this._hash2query(v,_25,_20,_21);
}else{
if(v===null){
continue;
}
if(v===true){
v=1;
}
if(v===false){
v="";
}
_20[_20.length]=_25+"="+this.escape(""+v);
}
}
if(_22&&_21.length>1){
return this._error("must_be_single_el");
}
}
}else{
_20[_20.length]=_1e;
}
return true;
};
t._cleanup=function(){
var _28=this._ldObj;
if(!_28){
return;
}
JsHttpRequest.PENDING[_28.id]=false;
var _29=_28.span;
if(!_29){
return;
}
_28.span=null;
var _2a=function(){
_29.parentNode.removeChild(_29);
};
JsHttpRequest.setTimeout(_2a,50);
};
t._changeReadyState=function(s,_2c){
with(this){
if(_2c){
status=statusText=responseJS=null;
responseText="";
}
readyState=s;
if(onreadystatechange){
onreadystatechange();
}
}
};
t.escape=function(s){
return escape(s).replace(new RegExp("\\+","g"),"%2B");
};
}
JsHttpRequest.COUNT=0;
JsHttpRequest.MAX_URL_LEN=2000;
JsHttpRequest.CACHE={};
JsHttpRequest.PENDING={};
JsHttpRequest.LOADERS={};
JsHttpRequest._dummy=function(){
};
JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};
JsHttpRequest.setTimeout=function(_2e,dt){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;
if(typeof (_2e)=="string"){
id=window.JsHttpRequest_tmp(_2e,dt);
}else{
var id=null;
var _31=function(){
_2e();
delete JsHttpRequest.TIMEOUTS[id];
};
id=window.JsHttpRequest_tmp(_31,dt);
JsHttpRequest.TIMEOUTS[id]=_31;
}
window.JsHttpRequest_tmp=null;
return id;
};
JsHttpRequest.clearTimeout=function(id){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id];
var r=window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp=null;
return r;
};
JsHttpRequest.query=function(url,_35,_36,_37){
var req=new this();
req.caching=!_37;
req.onreadystatechange=function(){
if(req.readyState==4){
_36(req.responseJS,req.responseText);
}
};
req.open(null,url,true);
req.send(_35);
};
JsHttpRequest.dataReady=function(d){
var th=this.PENDING[d.id];
delete this.PENDING[d.id];
if(th){
th._dataReady(d.text,d.js);
}else{
if(th!==false){
throw "dataReady(): unknown pending id: "+d.id;
}
}
};
JsHttpRequest.extend=function(_3b,src){
for(var k in src){
_3b[k]=src[k];
}
};
JsHttpRequest.LOADERS.script={loader:function(req){
JsHttpRequest.extend(req._errors,{script_only_get:"Cannot use SCRIPT loader: it supports only GET method",script_no_form:"Cannot use SCRIPT loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+this.id+"-"+"script";
this.queryText="";
if(!this.method){
this.method="GET";
}
if(this.method!=="GET"){
return ["script_only_get"];
}
if(this.queryElem.length){
return ["script_no_form"];
}
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var th=this,d=document,s=null,b=d.body;
if(!window.opera){
this.span=s=d.createElement("SCRIPT");
var _43=function(){
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
b.insertBefore(s,b.lastChild);
};
}else{
this.span=s=d.createElement("SPAN");
s.style.display="none";
b.insertBefore(s,b.lastChild);
s.innerHTML="Workaround for IE.<s"+"cript></"+"script>";
var _43=function(){
s=s.getElementsByTagName("SCRIPT")[0];
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
};
}
JsHttpRequest.setTimeout(_43,10);
return null;
};
}};

View file

@ -0,0 +1,414 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader (xml support only!)
* Minimized version: see debug directory for the complete one.
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
function JsHttpRequest(){
var t=this;
t.onreadystatechange=null;
t.readyState=0;
t.responseText=null;
t.responseXML=null;
t.status=200;
t.statusText="OK";
t.responseJS=null;
t.caching=false;
t.loader=null;
t.session_name="PHPSESSID";
t._ldObj=null;
t._reqHeaders=[];
t._openArgs=null;
t._errors={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%"};
t.abort=function(){
with(this){
if(_ldObj&&_ldObj.abort){
_ldObj.abort();
}
_cleanup();
if(readyState==0){
return;
}
if(readyState==1&&!_ldObj){
readyState=0;
return;
}
_changeReadyState(4,true);
}
};
t.open=function(_2,_3,_4,_5,_6){
with(this){
if(_3.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){
this.loader=RegExp.$2?RegExp.$2:null;
_2=RegExp.$3;
_3=RegExp.$4;
}
try{
if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){
_3+=(_3.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1);
}
}
catch(e){
}
_openArgs={method:(_2||"").toUpperCase(),url:_3,asyncFlag:_4,username:_5!=null?_5:"",password:_6!=null?_6:""};
_ldObj=null;
_changeReadyState(1,true);
return true;
}
};
t.send=function(_7){
if(!this.readyState){
return;
}
this._changeReadyState(1,true);
this._ldObj=null;
var _8=[];
var _9=[];
if(!this._hash2query(_7,null,_8,_9)){
return;
}
var _a=null;
if(this.caching&&!_9.length){
_a=this._openArgs.username+":"+this._openArgs.password+"@"+this._openArgs.url+"|"+_8+"#"+this._openArgs.method;
var _b=JsHttpRequest.CACHE[_a];
if(_b){
this._dataReady(_b[0],_b[1]);
return false;
}
}
var _c=(this.loader||"").toLowerCase();
if(_c&&!JsHttpRequest.LOADERS[_c]){
return this._error("unk_loader",_c);
}
var _d=[];
var _e=JsHttpRequest.LOADERS;
for(var _f in _e){
var ldr=_e[_f].loader;
if(!ldr){
continue;
}
if(_c&&_f!=_c){
continue;
}
var _11=new ldr(this);
JsHttpRequest.extend(_11,this._openArgs);
JsHttpRequest.extend(_11,{queryText:_8.join("&"),queryElem:_9,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:_a,span:null});
var _12=_11.load();
if(!_12){
this._ldObj=_11;
JsHttpRequest.PENDING[_11.id]=this;
return true;
}
if(!_c){
_d[_d.length]="- "+_f.toUpperCase()+": "+this._l(_12);
}else{
return this._error(_12);
}
}
return _f?this._error("no_loader_matched",_d.join("\n")):this._error("no_loaders");
};
t.getAllResponseHeaders=function(){
with(this){
return _ldObj&&_ldObj.getAllResponseHeaders?_ldObj.getAllResponseHeaders():[];
}
};
t.getResponseHeader=function(_13){
with(this){
return _ldObj&&_ldObj.getResponseHeader?_ldObj.getResponseHeader(_13):null;
}
};
t.setRequestHeader=function(_14,_15){
with(this){
_reqHeaders[_reqHeaders.length]=[_14,_15];
}
};
t._dataReady=function(_16,js){
with(this){
if(caching&&_ldObj){
JsHttpRequest.CACHE[_ldObj.hash]=[_16,js];
}
responseText=responseXML=_16;
responseJS=js;
if(js!==null){
status=200;
statusText="OK";
}else{
status=500;
statusText="Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}
};
t._l=function(_18){
var i=0,p=0,msg=this._errors[_18[0]];
while((p=msg.indexOf("%",p))>=0){
var a=_18[++i]+"";
msg=msg.substring(0,p)+a+msg.substring(p+1,msg.length);
p+=1+a.length;
}
return msg;
};
t._error=function(msg){
msg=this._l(typeof (msg)=="string"?arguments:msg);
msg="JsHttpRequest: "+msg;
if(!window.Error){
throw msg;
}else{
if((new Error(1,"test")).description=="test"){
throw new Error(1,msg);
}else{
throw new Error(msg);
}
}
};
t._hash2query=function(_1e,_1f,_20,_21){
if(_1f==null){
_1f="";
}
if((""+typeof (_1e)).toLowerCase()=="object"){
var _22=false;
if(_1e&&_1e.parentNode&&_1e.parentNode.appendChild&&_1e.tagName&&_1e.tagName.toUpperCase()=="FORM"){
_1e={form:_1e};
}
for(var k in _1e){
var v=_1e[k];
if(v instanceof Function){
continue;
}
var _25=_1f?_1f+"["+this.escape(k)+"]":this.escape(k);
var _26=v&&v.parentNode&&v.parentNode.appendChild&&v.tagName;
if(_26){
var tn=v.tagName.toUpperCase();
if(tn=="FORM"){
_22=true;
}else{
if(tn=="INPUT"||tn=="TEXTAREA"||tn=="SELECT"){
}else{
return this._error("inv_form_el",(v.name||""),v.tagName);
}
}
_21[_21.length]={name:_25,e:v};
}else{
if(v instanceof Object){
this._hash2query(v,_25,_20,_21);
}else{
if(v===null){
continue;
}
if(v===true){
v=1;
}
if(v===false){
v="";
}
_20[_20.length]=_25+"="+this.escape(""+v);
}
}
if(_22&&_21.length>1){
return this._error("must_be_single_el");
}
}
}else{
_20[_20.length]=_1e;
}
return true;
};
t._cleanup=function(){
var _28=this._ldObj;
if(!_28){
return;
}
JsHttpRequest.PENDING[_28.id]=false;
var _29=_28.span;
if(!_29){
return;
}
_28.span=null;
var _2a=function(){
_29.parentNode.removeChild(_29);
};
JsHttpRequest.setTimeout(_2a,50);
};
t._changeReadyState=function(s,_2c){
with(this){
if(_2c){
status=statusText=responseJS=null;
responseText="";
}
readyState=s;
if(onreadystatechange){
onreadystatechange();
}
}
};
t.escape=function(s){
return escape(s).replace(new RegExp("\\+","g"),"%2B");
};
}
JsHttpRequest.COUNT=0;
JsHttpRequest.MAX_URL_LEN=2000;
JsHttpRequest.CACHE={};
JsHttpRequest.PENDING={};
JsHttpRequest.LOADERS={};
JsHttpRequest._dummy=function(){
};
JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};
JsHttpRequest.setTimeout=function(_2e,dt){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;
if(typeof (_2e)=="string"){
id=window.JsHttpRequest_tmp(_2e,dt);
}else{
var id=null;
var _31=function(){
_2e();
delete JsHttpRequest.TIMEOUTS[id];
};
id=window.JsHttpRequest_tmp(_31,dt);
JsHttpRequest.TIMEOUTS[id]=_31;
}
window.JsHttpRequest_tmp=null;
return id;
};
JsHttpRequest.clearTimeout=function(id){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id];
var r=window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp=null;
return r;
};
JsHttpRequest.query=function(url,_35,_36,_37){
var req=new this();
req.caching=!_37;
req.onreadystatechange=function(){
if(req.readyState==4){
_36(req.responseJS,req.responseText);
}
};
req.open(null,url,true);
req.send(_35);
};
JsHttpRequest.dataReady=function(d){
var th=this.PENDING[d.id];
delete this.PENDING[d.id];
if(th){
th._dataReady(d.text,d.js);
}else{
if(th!==false){
throw "dataReady(): unknown pending id: "+d.id;
}
}
};
JsHttpRequest.extend=function(_3b,src){
for(var k in src){
_3b[k]=src[k];
}
};
JsHttpRequest.LOADERS.xml={loader:function(req){
JsHttpRequest.extend(req._errors,{xml_no:"Cannot use XMLHttpRequest or ActiveX loader: not supported",xml_no_diffdom:"Cannot use XMLHttpRequest to load data from different domain %",xml_no_headers:"Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly",xml_no_form_upl:"Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryElem.length){
return ["xml_no_form_upl"];
}
if(this.url.match(new RegExp("^([a-z]+://[^\\/]+)(.*)","i"))){
if(RegExp.$1.toLowerCase()!=document.location.protocol+"//"+document.location.hostname.toLowerCase()){
return ["xml_no_diffdom",RegExp.$1];
}
}
var xr=null;
if(window.XMLHttpRequest){
try{
xr=new XMLHttpRequest();
}
catch(e){
}
}else{
if(window.ActiveXObject){
try{
xr=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
if(!xr){
try{
xr=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
}
}
}
}
if(!xr){
return ["xml_no"];
}
var _40=window.ActiveXObject||xr.setRequestHeader;
if(!this.method){
this.method=_40&&this.queryText.length?"POST":"GET";
}
if(this.method=="GET"){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.queryText="";
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
}else{
if(this.method=="POST"&&!_40){
return ["xml_no_headers"];
}
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+(req.caching?"0":this.id)+"-xml";
var id=this.id;
xr.onreadystatechange=function(){
if(xr.readyState!=4){
return;
}
xr.onreadystatechange=JsHttpRequest._dummy;
req.status=null;
try{
req.status=xr.status;
req.responseText=xr.responseText;
}
catch(e){
}
if(!req.status){
return;
}
try{
eval("JsHttpRequest._tmp = function(id) { var d = "+req.responseText+"; d.id = id; JsHttpRequest.dataReady(d); }");
}
catch(e){
return req._error("js_invalid",req.responseText);
}
JsHttpRequest._tmp(id);
JsHttpRequest._tmp=null;
};
xr.open(this.method,this.url,true,this.username,this.password);
if(_40){
for(var i=0;i<req._reqHeaders.length;i++){
xr.setRequestHeader(req._reqHeaders[i][0],req._reqHeaders[i][1]);
}
xr.setRequestHeader("Content-Type","application/octet-stream");
}
xr.send(this.queryText);
this.span=null;
this.xr=xr;
return null;
};
this.getAllResponseHeaders=function(){
return this.xr.getAllResponseHeaders();
};
this.getResponseHeader=function(_43){
return this.xr.getResponseHeader(_43);
};
this.abort=function(){
this.xr.abort();
this.xr=null;
};
}};

View file

@ -0,0 +1,576 @@
/**
* JsHttpRequest: JavaScript "AJAX" data loader
* Minimized version: see debug directory for the complete one.
*
* @license LGPL
* @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
* @version 5.x $Id$
*/
function JsHttpRequest(){
var t=this;
t.onreadystatechange=null;
t.readyState=0;
t.responseText=null;
t.responseXML=null;
t.status=200;
t.statusText="OK";
t.responseJS=null;
t.caching=false;
t.loader=null;
t.session_name="PHPSESSID";
t._ldObj=null;
t._reqHeaders=[];
t._openArgs=null;
t._errors={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%"};
t.abort=function(){
with(this){
if(_ldObj&&_ldObj.abort){
_ldObj.abort();
}
_cleanup();
if(readyState==0){
return;
}
if(readyState==1&&!_ldObj){
readyState=0;
return;
}
_changeReadyState(4,true);
}
};
t.open=function(_2,_3,_4,_5,_6){
with(this){
if(_3.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){
this.loader=RegExp.$2?RegExp.$2:null;
_2=RegExp.$3;
_3=RegExp.$4;
}
try{
if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){
_3+=(_3.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1);
}
}
catch(e){
}
_openArgs={method:(_2||"").toUpperCase(),url:_3,asyncFlag:_4,username:_5!=null?_5:"",password:_6!=null?_6:""};
_ldObj=null;
_changeReadyState(1,true);
return true;
}
};
t.send=function(_7){
if(!this.readyState){
return;
}
this._changeReadyState(1,true);
this._ldObj=null;
var _8=[];
var _9=[];
if(!this._hash2query(_7,null,_8,_9)){
return;
}
var _a=null;
if(this.caching&&!_9.length){
_a=this._openArgs.username+":"+this._openArgs.password+"@"+this._openArgs.url+"|"+_8+"#"+this._openArgs.method;
var _b=JsHttpRequest.CACHE[_a];
if(_b){
this._dataReady(_b[0],_b[1]);
return false;
}
}
var _c=(this.loader||"").toLowerCase();
if(_c&&!JsHttpRequest.LOADERS[_c]){
return this._error("unk_loader",_c);
}
var _d=[];
var _e=JsHttpRequest.LOADERS;
for(var _f in _e){
var ldr=_e[_f].loader;
if(!ldr){
continue;
}
if(_c&&_f!=_c){
continue;
}
var _11=new ldr(this);
JsHttpRequest.extend(_11,this._openArgs);
JsHttpRequest.extend(_11,{queryText:_8.join("&"),queryElem:_9,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:_a,span:null});
var _12=_11.load();
if(!_12){
this._ldObj=_11;
JsHttpRequest.PENDING[_11.id]=this;
return true;
}
if(!_c){
_d[_d.length]="- "+_f.toUpperCase()+": "+this._l(_12);
}else{
return this._error(_12);
}
}
return _f?this._error("no_loader_matched",_d.join("\n")):this._error("no_loaders");
};
t.getAllResponseHeaders=function(){
with(this){
return _ldObj&&_ldObj.getAllResponseHeaders?_ldObj.getAllResponseHeaders():[];
}
};
t.getResponseHeader=function(_13){
with(this){
return _ldObj&&_ldObj.getResponseHeader?_ldObj.getResponseHeader(_13):null;
}
};
t.setRequestHeader=function(_14,_15){
with(this){
_reqHeaders[_reqHeaders.length]=[_14,_15];
}
};
t._dataReady=function(_16,js){
with(this){
if(caching&&_ldObj){
JsHttpRequest.CACHE[_ldObj.hash]=[_16,js];
}
responseText=responseXML=_16;
responseJS=js;
if(js!==null){
status=200;
statusText="OK";
}else{
status=500;
statusText="Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}
};
t._l=function(_18){
var i=0,p=0,msg=this._errors[_18[0]];
while((p=msg.indexOf("%",p))>=0){
var a=_18[++i]+"";
msg=msg.substring(0,p)+a+msg.substring(p+1,msg.length);
p+=1+a.length;
}
return msg;
};
t._error=function(msg){
msg=this._l(typeof (msg)=="string"?arguments:msg);
msg="JsHttpRequest: "+msg;
if(!window.Error){
throw msg;
}else{
if((new Error(1,"test")).description=="test"){
throw new Error(1,msg);
}else{
throw new Error(msg);
}
}
};
t._hash2query=function(_1e,_1f,_20,_21){
if(_1f==null){
_1f="";
}
if((""+typeof (_1e)).toLowerCase()=="object"){
var _22=false;
if(_1e&&_1e.parentNode&&_1e.parentNode.appendChild&&_1e.tagName&&_1e.tagName.toUpperCase()=="FORM"){
_1e={form:_1e};
}
for(var k in _1e){
var v=_1e[k];
if(v instanceof Function){
continue;
}
var _25=_1f?_1f+"["+this.escape(k)+"]":this.escape(k);
var _26=v&&v.parentNode&&v.parentNode.appendChild&&v.tagName;
if(_26){
var tn=v.tagName.toUpperCase();
if(tn=="FORM"){
_22=true;
}else{
if(tn=="INPUT"||tn=="TEXTAREA"||tn=="SELECT"){
}else{
return this._error("inv_form_el",(v.name||""),v.tagName);
}
}
_21[_21.length]={name:_25,e:v};
}else{
if(v instanceof Object){
this._hash2query(v,_25,_20,_21);
}else{
if(v===null){
continue;
}
if(v===true){
v=1;
}
if(v===false){
v="";
}
_20[_20.length]=_25+"="+this.escape(""+v);
}
}
if(_22&&_21.length>1){
return this._error("must_be_single_el");
}
}
}else{
_20[_20.length]=_1e;
}
return true;
};
t._cleanup=function(){
var _28=this._ldObj;
if(!_28){
return;
}
JsHttpRequest.PENDING[_28.id]=false;
var _29=_28.span;
if(!_29){
return;
}
_28.span=null;
var _2a=function(){
_29.parentNode.removeChild(_29);
};
JsHttpRequest.setTimeout(_2a,50);
};
t._changeReadyState=function(s,_2c){
with(this){
if(_2c){
status=statusText=responseJS=null;
responseText="";
}
readyState=s;
if(onreadystatechange){
onreadystatechange();
}
}
};
t.escape=function(s){
return escape(s).replace(new RegExp("\\+","g"),"%2B");
};
}
JsHttpRequest.COUNT=0;
JsHttpRequest.MAX_URL_LEN=2000;
JsHttpRequest.CACHE={};
JsHttpRequest.PENDING={};
JsHttpRequest.LOADERS={};
JsHttpRequest._dummy=function(){
};
JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};
JsHttpRequest.setTimeout=function(_2e,dt){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;
if(typeof (_2e)=="string"){
id=window.JsHttpRequest_tmp(_2e,dt);
}else{
var id=null;
var _31=function(){
_2e();
delete JsHttpRequest.TIMEOUTS[id];
};
id=window.JsHttpRequest_tmp(_31,dt);
JsHttpRequest.TIMEOUTS[id]=_31;
}
window.JsHttpRequest_tmp=null;
return id;
};
JsHttpRequest.clearTimeout=function(id){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id];
var r=window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp=null;
return r;
};
JsHttpRequest.query=function(url,_35,_36,_37){
var req=new this();
req.caching=!_37;
req.onreadystatechange=function(){
if(req.readyState==4){
_36(req.responseJS,req.responseText);
}
};
req.open(null,url,true);
req.send(_35);
};
JsHttpRequest.dataReady=function(d){
var th=this.PENDING[d.id];
delete this.PENDING[d.id];
if(th){
th._dataReady(d.text,d.js);
}else{
if(th!==false){
throw "dataReady(): unknown pending id: "+d.id;
}
}
};
JsHttpRequest.extend=function(_3b,src){
for(var k in src){
_3b[k]=src[k];
}
};
JsHttpRequest.LOADERS.xml={loader:function(req){
JsHttpRequest.extend(req._errors,{xml_no:"Cannot use XMLHttpRequest or ActiveX loader: not supported",xml_no_diffdom:"Cannot use XMLHttpRequest to load data from different domain %",xml_no_headers:"Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly",xml_no_form_upl:"Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryElem.length){
return ["xml_no_form_upl"];
}
if(this.url.match(new RegExp("^([a-z]+://[^\\/]+)(.*)","i"))){
if(RegExp.$1.toLowerCase()!=document.location.protocol+"//"+document.location.hostname.toLowerCase()){
return ["xml_no_diffdom",RegExp.$1];
}
}
var xr=null;
if(window.XMLHttpRequest){
try{
xr=new XMLHttpRequest();
}
catch(e){
}
}else{
if(window.ActiveXObject){
try{
xr=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
if(!xr){
try{
xr=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
}
}
}
}
if(!xr){
return ["xml_no"];
}
var _40=window.ActiveXObject||xr.setRequestHeader;
if(!this.method){
this.method=_40&&this.queryText.length?"POST":"GET";
}
if(this.method=="GET"){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.queryText="";
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
}else{
if(this.method=="POST"&&!_40){
return ["xml_no_headers"];
}
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+(req.caching?"0":this.id)+"-xml";
var id=this.id;
xr.onreadystatechange=function(){
if(xr.readyState!=4){
return;
}
xr.onreadystatechange=JsHttpRequest._dummy;
req.status=null;
try{
req.status=xr.status;
req.responseText=xr.responseText;
}
catch(e){
}
if(!req.status){
return;
}
try{
eval("JsHttpRequest._tmp = function(id) { var d = "+req.responseText+"; d.id = id; JsHttpRequest.dataReady(d); }");
}
catch(e){
return req._error("js_invalid",req.responseText);
}
JsHttpRequest._tmp(id);
JsHttpRequest._tmp=null;
};
xr.open(this.method,this.url,true,this.username,this.password);
if(_40){
for(var i=0;i<req._reqHeaders.length;i++){
xr.setRequestHeader(req._reqHeaders[i][0],req._reqHeaders[i][1]);
}
xr.setRequestHeader("Content-Type","application/octet-stream");
}
xr.send(this.queryText);
this.span=null;
this.xr=xr;
return null;
};
this.getAllResponseHeaders=function(){
return this.xr.getAllResponseHeaders();
};
this.getResponseHeader=function(_43){
return this.xr.getResponseHeader(_43);
};
this.abort=function(){
this.xr.abort();
this.xr=null;
};
}};
JsHttpRequest.LOADERS.script={loader:function(req){
JsHttpRequest.extend(req._errors,{script_only_get:"Cannot use SCRIPT loader: it supports only GET method",script_no_form:"Cannot use SCRIPT loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+this.id+"-"+"script";
this.queryText="";
if(!this.method){
this.method="GET";
}
if(this.method!=="GET"){
return ["script_only_get"];
}
if(this.queryElem.length){
return ["script_no_form"];
}
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var th=this,d=document,s=null,b=d.body;
if(!window.opera){
this.span=s=d.createElement("SCRIPT");
var _49=function(){
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
b.insertBefore(s,b.lastChild);
};
}else{
this.span=s=d.createElement("SPAN");
s.style.display="none";
b.insertBefore(s,b.lastChild);
s.innerHTML="Workaround for IE.<s"+"cript></"+"script>";
var _49=function(){
s=s.getElementsByTagName("SCRIPT")[0];
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
};
}
JsHttpRequest.setTimeout(_49,10);
return null;
};
}};
JsHttpRequest.LOADERS.form={loader:function(req){
JsHttpRequest.extend(req._errors,{form_el_not_belong:"Element \"%\" does not belong to any form!",form_el_belong_diff:"Element \"%\" belongs to a different form. All elements must belong to the same form!",form_el_inv_enctype:"Attribute \"enctype\" of the form must be \"%\" (for IE), \"%\" given."});
this.load=function(){
var th=this;
if(!th.method){
th.method="POST";
}
th.url+=(th.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+th.id+"-"+"form";
if(th.method=="GET"){
if(th.queryText){
th.url+=(th.url.indexOf("?")>=0?"&":"?")+th.queryText;
}
if(th.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var p=th.url.split("?",2);
th.url=p[0];
th.queryText=p[1]||"";
}
var _4d=null;
var _4e=false;
if(th.queryElem.length){
if(th.queryElem[0].e.tagName.toUpperCase()=="FORM"){
_4d=th.queryElem[0].e;
_4e=true;
th.queryElem=[];
}else{
_4d=th.queryElem[0].e.form;
for(var i=0;i<th.queryElem.length;i++){
var e=th.queryElem[i].e;
if(!e.form){
return ["form_el_not_belong",e.name];
}
if(e.form!=_4d){
return ["form_el_belong_diff",e.name];
}
}
}
if(th.method=="POST"){
var _51="multipart/form-data";
var _52=(_4d.attributes.encType&&_4d.attributes.encType.nodeValue)||(_4d.attributes.enctype&&_4d.attributes.enctype.value)||_4d.enctype;
if(_52!=_51){
return ["form_el_inv_enctype",_51,_52];
}
}
}
var d=_4d&&(_4d.ownerDocument||_4d.document)||document;
var _54="jshr_i_"+th.id;
var s=th.span=d.createElement("DIV");
s.style.position="absolute";
s.style.display="none";
s.style.visibility="hidden";
s.innerHTML=(_4d?"":"<form"+(th.method=="POST"?" enctype=\"multipart/form-data\" method=\"post\"":"")+"></form>")+"<iframe name=\""+_54+"\" id=\""+_54+"\" style=\"width:0px; height:0px; overflow:hidden; border:none\"></iframe>";
if(!_4d){
_4d=th.span.firstChild;
}
d.body.insertBefore(s,d.body.lastChild);
var _56=function(e,_58){
var sv=[];
var _5a=e;
if(e.mergeAttributes){
var _5a=d.createElement("form");
_5a.mergeAttributes(e,false);
}
for(var i=0;i<_58.length;i++){
var k=_58[i][0],v=_58[i][1];
sv[sv.length]=[k,_5a.getAttribute(k)];
_5a.setAttribute(k,v);
}
if(e.mergeAttributes){
e.mergeAttributes(_5a,false);
}
return sv;
};
var _5e=function(){
top.JsHttpRequestGlobal=JsHttpRequest;
var _5f=[];
if(!_4e){
for(var i=0,n=_4d.elements.length;i<n;i++){
_5f[i]=_4d.elements[i].name;
_4d.elements[i].name="";
}
}
var qt=th.queryText.split("&");
for(var i=qt.length-1;i>=0;i--){
var _63=qt[i].split("=",2);
var e=d.createElement("INPUT");
e.type="hidden";
e.name=unescape(_63[0]);
e.value=_63[1]!=null?unescape(_63[1]):"";
_4d.appendChild(e);
}
for(var i=0;i<th.queryElem.length;i++){
th.queryElem[i].e.name=th.queryElem[i].name;
}
var sv=_56(_4d,[["action",th.url],["method",th.method],["onsubmit",null],["target",_54]]);
_4d.submit();
_56(_4d,sv);
for(var i=0;i<qt.length;i++){
_4d.lastChild.parentNode.removeChild(_4d.lastChild);
}
if(!_4e){
for(var i=0,n=_4d.elements.length;i<n;i++){
_4d.elements[i].name=_5f[i];
}
}
};
JsHttpRequest.setTimeout(_5e,100);
return null;
};
}};

View file

@ -0,0 +1,163 @@
JsHttpRequest: JavaScript "AJAX" data loader
@license LGPL
@author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
@version 5.x $Id$
This document describes the protocol used by JsHttpRequest library.
Backend -> Frontend
-------------------
JsHttpRequest library uses 3 slightly different version of output protocol
depending on the loader used.
- SCRIPT loader:
Content-type: text/javascript; charset=...
JsHttpRequest.dataReady({ id: ..., js: ..., text: ...})
The charset is always set equal to the base backend charset.
- XML loader:
Content-type: text/plain; charset=...
{ id: ..., js: ..., text: ...}
The charset may be UTF-8 (of the backend supports JSON conversion
functions) or the base backend charset. We have to use text/plain
because of some Opera 8 bugs.
- FORM loader:
Content-type: text/html; charset=...
<script type="text/javascript" language="JavaScript"><!--
top && top.JsHttpRequestGlobal &&
top.JsHttpRequestGlobal.dataReady({ id: ..., js: ..., text: ...})
//--></script>
The charset is always set equal to the base backend charset. Note
that we use text/html Content-type, because the result is loaded
into dynamically created IFRAME and must be valid HTML.
(Note that you may always use a fixed charset in your backends,
e.g. UTF-8. The frontend is a fully Unicode supporting library.)
The common part of all these constructions is always represented as
a plain JavaScript object:
{
id: <loading ID>,
js: <JavaScript resulting object>,
text: <text data, e.g. - debug STDOUT content>
}
Meanings of object properties are:
- id: ID of the loading passed by a frontend. This ID is used to
associate the resulting data with corresponding onreadystatechange
handler and generated automatically.
- js: a JavaScript object representing multi-dimensional array
passed from the backend to a frontend. If null is passed here,
we treat it as 500 Internal Server Error in the frontend.
- text: other backend data (usually captured STDOUT).
Note that for XML the loader ID is always equals to 0, because we
do not need an explicit binding between a result data and a loader:
binding is performed automatically by ActiveX or XMLHttpRequest.
ATTENTION! If you want to create your own backend, you should guarantee
that the following formats are satisfied, else you may get a JavaScript
backend exception. E.g., if your script dies with some error, it should
pass the message to the "text" property, not write it to the output
directly. In PHP backend it is done via ob_start() handlers.
Frontend -> Backend
-------------------
The protocol is very simple and fully compatible with standard PHP's features.
Frontend passes to backend a list of key=value pairs using GET or POST method.
1. Auxiliary information
Each loading process is supplied with a piece of information appended to the
end of QUERY_STRING:
PHPSESSID=<sid>&JsHttpRequest=<id>-<loader>
- PHPSESSID=<sid> is the session information. (Of course you may use another
name instead of PHPSESSID, it is tuned inside the JsHttpRequest object.)
Here <sid> is the session identifier extracted from document cookies or
from the current document URL. This method is fully comatible with PHP
sessions support.
- <loader> is the name of a loader used. E.g.: "xml", "script", "form".
- <id> is the loading ID. It is generated automatically and unique for
each of the loading process. (Exception is the XML loader: it always
uses zero ID.) This ID is passed back by a backend to determine which
result is binded to which callback action (see above).
2. Character conversions
Each character of a key/value is encoded by JavaScript standard escape()
function (with exception for "+": it is converted to "%2B"). That means:
- Unicode non-ASCII character (e.g. with code 0x1234) is encoded to e.g. %u1234.
- Character "+" is converted to "%2B".
- URL-allowed characters (e.g. letters, digits etc.) remain unchanged.
- Other ASCII character (e.g. 0x15) is converted to e.g. %15.
Samples:
- "ïðîáà" -> "%u043F%u0440%u043E%u0431%u0430"
- "abcde" -> "abcde"
- "a[x]" -> "a%5Bx%5D"
- "a+b" -> "a%2Bb"
3. Array conversions
JsHttpRequest supports multi-dimensional associative arrays created from
standard JavaScript objects. Each key of the key=value pair is created
based on all parents of the corresponding object property. PHP notation
of multi-dimensional arrays is used.
Samples:
- JavaScript: { a: 123, b: { c: 456, d: 789 } }
- GET/POST data: a=123&b[c]=456&b[d]=789
- PHP's array: array('a' => 123, 'b' => array('c' => 456, 'd' => 789))
- JavaScript: { a: 123, b: [4, 5] }
- GET/POST data: a=123&b[]=4&b[]=5
- PHP's array: array('a' => 123, 'b' => array(4, 5))
You see that JavaScript objects are 1:1 converted to PHP's arrays, and
an array encoding format is compatible with such behaviour.
4. Content-type header
Available Content-type headers generated by a frontend depend on a loader
and a method used.
Samples (format: <loader>.<method>):
- application/x-www-form-urlencoded: script.*, xml.GET, form.GET
- multipart/form-data: form.POST
- application/octet-stream: xml.POST
Please note that xml.POST generates application/octet-stream, but
NOT application/x-www-form-urlencoded. It is needed to avoid the standard
PHP behavior of POST data parsing, because we have to process the
data encoding manually (PHP does not support JavaScript escape() encoding
directly).
Also note that multipart/form-data format used for FORM loader, because
this is the only way to support file uploads.

View file

@ -0,0 +1,341 @@
//MooTools, <http://mootools.net>, My Object Oriented (JavaScript) Tools. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.
var MooTools={version:"1.2.0",build:""};var Native=function(J){J=J||{};var F=J.afterImplement||function(){};var G=J.generics;G=(G!==false);var H=J.legacy;
var E=J.initialize;var B=J.protect;var A=J.name;var C=E||H;C.constructor=Native;C.$family={name:"native"};if(H&&E){C.prototype=H.prototype;}C.prototype.constructor=C;
if(A){var D=A.toLowerCase();C.prototype.$family={name:D};Native.typize(C,D);}var I=function(M,K,N,L){if(!B||L||!M.prototype[K]){M.prototype[K]=N;}if(G){Native.genericize(M,K,B);
}F.call(M,K,N);return M;};C.implement=function(L,K,N){if(typeof L=="string"){return I(this,L,K,N);}for(var M in L){I(this,M,L[M],K);}return this;};C.alias=function(M,K,N){if(typeof M=="string"){M=this.prototype[M];
if(M){I(this,K,M,N);}}else{for(var L in M){this.alias(L,M[L],K);}}return this;};return C;};Native.implement=function(D,C){for(var B=0,A=D.length;B<A;B++){D[B].implement(C);
}};Native.genericize=function(B,C,A){if((!A||!B[C])&&typeof B.prototype[C]=="function"){B[C]=function(){var D=Array.prototype.slice.call(arguments);return B.prototype[C].apply(D.shift(),D);
};}};Native.typize=function(A,B){if(!A.type){A.type=function(C){return($type(C)===B);};}};Native.alias=function(E,B,A,F){for(var D=0,C=E.length;D<C;D++){E[D].alias(B,A,F);
}};(function(B){for(var A in B){Native.typize(B[A],A);}})({"boolean":Boolean,"native":Native,object:Object});(function(B){for(var A in B){new Native({name:A,initialize:B[A],protect:true});
}})({String:String,Function:Function,Number:Number,Array:Array,RegExp:RegExp,Date:Date});(function(B,A){for(var C=A.length;C--;C){Native.genericize(B,A[C],true);
}return arguments.callee;})(Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","toString","valueOf","indexOf","lastIndexOf"])(String,["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]);
function $chk(A){return !!(A||A===0);}function $clear(A){clearTimeout(A);clearInterval(A);return null;}function $defined(A){return(A!=undefined);}function $empty(){}function $arguments(A){return function(){return arguments[A];
};}function $lambda(A){return(typeof A=="function")?A:function(){return A;};}function $extend(C,A){for(var B in (A||{})){C[B]=A[B];}return C;}function $unlink(C){var B;
switch($type(C)){case"object":B={};for(var E in C){B[E]=$unlink(C[E]);}break;case"hash":B=$unlink(C.getClean());break;case"array":B=[];for(var D=0,A=C.length;
D<A;D++){B[D]=$unlink(C[D]);}break;default:return C;}return B;}function $merge(){var E={};for(var D=0,A=arguments.length;D<A;D++){var B=arguments[D];if($type(B)!="object"){continue;
}for(var C in B){var G=B[C],F=E[C];E[C]=(F&&$type(G)=="object"&&$type(F)=="object")?$merge(F,G):$unlink(G);}}return E;}function $pick(){for(var B=0,A=arguments.length;
B<A;B++){if(arguments[B]!=undefined){return arguments[B];}}return null;}function $random(B,A){return Math.floor(Math.random()*(A-B+1)+B);}function $splat(B){var A=$type(B);
return(A)?((A!="array"&&A!="arguments")?[B]:B):[];}var $time=Date.now||function(){return new Date().getTime();};function $try(){for(var B=0,A=arguments.length;
B<A;B++){try{return arguments[B]();}catch(C){}}return null;}function $type(A){if(A==undefined){return false;}if(A.$family){return(A.$family.name=="number"&&!isFinite(A))?false:A.$family.name;
}if(A.nodeName){switch(A.nodeType){case 1:return"element";case 3:return(/\S/).test(A.nodeValue)?"textnode":"whitespace";}}else{if(typeof A.length=="number"){if(A.callee){return"arguments";
}else{if(A.item){return"collection";}}}}return typeof A;}var Hash=new Native({name:"Hash",initialize:function(A){if($type(A)=="hash"){A=$unlink(A.getClean());
}for(var B in A){this[B]=A[B];}return this;}});Hash.implement({getLength:function(){var B=0;for(var A in this){if(this.hasOwnProperty(A)){B++;}}return B;
},forEach:function(B,C){for(var A in this){if(this.hasOwnProperty(A)){B.call(C,this[A],A,this);}}},getClean:function(){var B={};for(var A in this){if(this.hasOwnProperty(A)){B[A]=this[A];
}}return B;}});Hash.alias("forEach","each");function $H(A){return new Hash(A);}Array.implement({forEach:function(C,D){for(var B=0,A=this.length;B<A;B++){C.call(D,this[B],B,this);
}}});Array.alias("forEach","each");function $A(C){if(C.item){var D=[];for(var B=0,A=C.length;B<A;B++){D[B]=C[B];}return D;}return Array.prototype.slice.call(C);
}function $each(C,B,D){var A=$type(C);((A=="arguments"||A=="collection"||A=="array")?Array:Hash).each(C,B,D);}var Browser=new Hash({Engine:{name:"unknown",version:""},Platform:{name:(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase()},Features:{xpath:!!(document.evaluate),air:!!(window.runtime)},Plugins:{}});
if(window.opera){Browser.Engine={name:"presto",version:(document.getElementsByClassName)?950:925};}else{if(window.ActiveXObject){Browser.Engine={name:"trident",version:(window.XMLHttpRequest)?5:4};
}else{if(!navigator.taintEnabled){Browser.Engine={name:"webkit",version:(Browser.Features.xpath)?420:419};}else{if(document.getBoxObjectFor!=null){Browser.Engine={name:"gecko",version:(document.getElementsByClassName)?19:18};
}}}}Browser.Engine[Browser.Engine.name]=Browser.Engine[Browser.Engine.name+Browser.Engine.version]=true;if(window.orientation!=undefined){Browser.Platform.name="ipod";
}Browser.Platform[Browser.Platform.name]=true;Browser.Request=function(){return $try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject("MSXML2.XMLHTTP");
});};Browser.Features.xhr=!!(Browser.Request());Browser.Plugins.Flash=(function(){var A=($try(function(){return navigator.plugins["Shockwave Flash"].description;
},function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);return{version:parseInt(A[0]||0+"."+A[1]||0),build:parseInt(A[2]||0)};
})();function $exec(B){if(!B){return B;}if(window.execScript){window.execScript(B);}else{var A=document.createElement("script");A.setAttribute("type","text/javascript");
A.text=B;document.head.appendChild(A);document.head.removeChild(A);}return B;}Native.UID=1;var $uid=(Browser.Engine.trident)?function(A){return(A.uid||(A.uid=[Native.UID++]))[0];
}:function(A){return A.uid||(A.uid=Native.UID++);};var Window=new Native({name:"Window",legacy:(Browser.Engine.trident)?null:window.Window,initialize:function(A){$uid(A);
if(!A.Element){A.Element=$empty;if(Browser.Engine.webkit){A.document.createElement("iframe");}A.Element.prototype=(Browser.Engine.webkit)?window["[[DOMElement.prototype]]"]:{};
}return $extend(A,Window.Prototype);},afterImplement:function(B,A){window[B]=Window.Prototype[B]=A;}});Window.Prototype={$family:{name:"window"}};new Window(window);
var Document=new Native({name:"Document",legacy:(Browser.Engine.trident)?null:window.Document,initialize:function(A){$uid(A);A.head=A.getElementsByTagName("head")[0];
A.html=A.getElementsByTagName("html")[0];A.window=A.defaultView||A.parentWindow;if(Browser.Engine.trident4){$try(function(){A.execCommand("BackgroundImageCache",false,true);
});}return $extend(A,Document.Prototype);},afterImplement:function(B,A){document[B]=Document.Prototype[B]=A;}});Document.Prototype={$family:{name:"document"}};
new Document(document);Array.implement({every:function(C,D){for(var B=0,A=this.length;B<A;B++){if(!C.call(D,this[B],B,this)){return false;}}return true;
},filter:function(D,E){var C=[];for(var B=0,A=this.length;B<A;B++){if(D.call(E,this[B],B,this)){C.push(this[B]);}}return C;},clean:function(){return this.filter($defined);
},indexOf:function(C,D){var A=this.length;for(var B=(D<0)?Math.max(0,A+D):D||0;B<A;B++){if(this[B]===C){return B;}}return -1;},map:function(D,E){var C=[];
for(var B=0,A=this.length;B<A;B++){C[B]=D.call(E,this[B],B,this);}return C;},some:function(C,D){for(var B=0,A=this.length;B<A;B++){if(C.call(D,this[B],B,this)){return true;
}}return false;},associate:function(C){var D={},B=Math.min(this.length,C.length);for(var A=0;A<B;A++){D[C[A]]=this[A];}return D;},link:function(C){var A={};
for(var E=0,B=this.length;E<B;E++){for(var D in C){if(C[D](this[E])){A[D]=this[E];delete C[D];break;}}}return A;},contains:function(A,B){return this.indexOf(A,B)!=-1;
},extend:function(C){for(var B=0,A=C.length;B<A;B++){this.push(C[B]);}return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[$random(0,this.length-1)]:null;
},include:function(A){if(!this.contains(A)){this.push(A);}return this;},combine:function(C){for(var B=0,A=C.length;B<A;B++){this.include(C[B]);}return this;
},erase:function(B){for(var A=this.length;A--;A){if(this[A]===B){this.splice(A,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var D=[];
for(var B=0,A=this.length;B<A;B++){var C=$type(this[B]);if(!C){continue;}D=D.concat((C=="array"||C=="collection"||C=="arguments")?Array.flatten(this[B]):this[B]);
}return D;},hexToRgb:function(B){if(this.length!=3){return null;}var A=this.map(function(C){if(C.length==1){C+=C;}return C.toInt(16);});return(B)?A:"rgb("+A+")";
},rgbToHex:function(D){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!D){return"transparent";}var B=[];for(var A=0;A<3;A++){var C=(this[A]-0).toString(16);
B.push((C.length==1)?"0"+C:C);}return(D)?B:"#"+B.join("");}});Function.implement({extend:function(A){for(var B in A){this[B]=A[B];}return this;},create:function(B){var A=this;
B=B||{};return function(D){var C=B.arguments;C=(C!=undefined)?$splat(C):Array.slice(arguments,(B.event)?1:0);if(B.event){C=[D||window.event].extend(C);
}var E=function(){return A.apply(B.bind||null,C);};if(B.delay){return setTimeout(E,B.delay);}if(B.periodical){return setInterval(E,B.periodical);}if(B.attempt){return $try(E);
}return E();};},pass:function(A,B){return this.create({arguments:A,bind:B});},attempt:function(A,B){return this.create({arguments:A,bind:B,attempt:true})();
},bind:function(B,A){return this.create({bind:B,arguments:A});},bindWithEvent:function(B,A){return this.create({bind:B,event:true,arguments:A});},delay:function(B,C,A){return this.create({delay:B,bind:C,arguments:A})();
},periodical:function(A,C,B){return this.create({periodical:A,bind:C,arguments:B})();},run:function(A,B){return this.apply(B,$splat(A));}});Number.implement({limit:function(B,A){return Math.min(A,Math.max(B,this));
},round:function(A){A=Math.pow(10,A||0);return Math.round(this*A)/A;},times:function(B,C){for(var A=0;A<this;A++){B.call(C,A,this);}},toFloat:function(){return parseFloat(this);
},toInt:function(A){return parseInt(this,A||10);}});Number.alias("times","each");(function(B){var A={};B.each(function(C){if(!Number[C]){A[C]=function(){return Math[C].apply(null,[this].concat($A(arguments)));
};}});Number.implement(A);})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);String.implement({test:function(A,B){return((typeof A=="string")?new RegExp(A,B):A).test(this);
},contains:function(A,B){return(B)?(B+this+B).indexOf(B+A+B)>-1:this.indexOf(A)>-1;},trim:function(){return this.replace(/^\s+|\s+$/g,"");},clean:function(){return this.replace(/\s+/g," ").trim();
},camelCase:function(){return this.replace(/-\D/g,function(A){return A.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/[A-Z]/g,function(A){return("-"+A.charAt(0).toLowerCase());
});},capitalize:function(){return this.replace(/\b[a-z]/g,function(A){return A.toUpperCase();});},escapeRegExp:function(){return this.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1");
},toInt:function(A){return parseInt(this,A||10);},toFloat:function(){return parseFloat(this);},hexToRgb:function(B){var A=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return(A)?A.slice(1).hexToRgb(B):null;},rgbToHex:function(B){var A=this.match(/\d{1,3}/g);return(A)?A.rgbToHex(B):null;},stripScripts:function(B){var A="";
var C=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(){A+=arguments[1]+"\n";return"";});if(B===true){$exec(A);}else{if($type(B)=="function"){B(A,C);
}}return C;},substitute:function(A,B){return this.replace(B||(/\\?\{([^}]+)\}/g),function(D,C){if(D.charAt(0)=="\\"){return D.slice(1);}return(A[C]!=undefined)?A[C]:"";
});}});Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(B){for(var A in this){if(this.hasOwnProperty(A)&&this[A]===B){return A;}}return null;
},hasValue:function(A){return(Hash.keyOf(this,A)!==null);},extend:function(A){Hash.each(A,function(C,B){Hash.set(this,B,C);},this);return this;},combine:function(A){Hash.each(A,function(C,B){Hash.include(this,B,C);
},this);return this;},erase:function(A){if(this.hasOwnProperty(A)){delete this[A];}return this;},get:function(A){return(this.hasOwnProperty(A))?this[A]:null;
},set:function(A,B){if(!this[A]||this.hasOwnProperty(A)){this[A]=B;}return this;},empty:function(){Hash.each(this,function(B,A){delete this[A];},this);
return this;},include:function(B,C){var A=this[B];if(A==undefined){this[B]=C;}return this;},map:function(B,C){var A=new Hash;Hash.each(this,function(E,D){A.set(D,B.call(C,E,D,this));
},this);return A;},filter:function(B,C){var A=new Hash;Hash.each(this,function(E,D){if(B.call(C,E,D,this)){A.set(D,E);}},this);return A;},every:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&!B.call(C,this[A],A)){return false;
}}return true;},some:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&B.call(C,this[A],A)){return true;}}return false;},getKeys:function(){var A=[];
Hash.each(this,function(C,B){A.push(B);});return A;},getValues:function(){var A=[];Hash.each(this,function(B){A.push(B);});return A;},toQueryString:function(A){var B=[];
Hash.each(this,function(F,E){if(A){E=A+"["+E+"]";}var D;switch($type(F)){case"object":D=Hash.toQueryString(F,E);break;case"array":var C={};F.each(function(H,G){C[G]=H;
});D=Hash.toQueryString(C,E);break;default:D=E+"="+encodeURIComponent(F);}if(F!=undefined){B.push(D);}});return B.join("&");}});Hash.alias({keyOf:"indexOf",hasValue:"contains"});
var Event=new Native({name:"Event",initialize:function(A,F){F=F||window;var K=F.document;A=A||F.event;if(A.$extended){return A;}this.$extended=true;var J=A.type;
var G=A.target||A.srcElement;while(G&&G.nodeType==3){G=G.parentNode;}if(J.test(/key/)){var B=A.which||A.keyCode;var M=Event.Keys.keyOf(B);if(J=="keydown"){var D=B-111;
if(D>0&&D<13){M="f"+D;}}M=M||String.fromCharCode(B).toLowerCase();}else{if(J.match(/(click|mouse|menu)/i)){K=(!K.compatMode||K.compatMode=="CSS1Compat")?K.html:K.body;
var I={x:A.pageX||A.clientX+K.scrollLeft,y:A.pageY||A.clientY+K.scrollTop};var C={x:(A.pageX)?A.pageX-F.pageXOffset:A.clientX,y:(A.pageY)?A.pageY-F.pageYOffset:A.clientY};
if(J.match(/DOMMouseScroll|mousewheel/)){var H=(A.wheelDelta)?A.wheelDelta/120:-(A.detail||0)/3;}var E=(A.which==3)||(A.button==2);var L=null;if(J.match(/over|out/)){switch(J){case"mouseover":L=A.relatedTarget||A.fromElement;
break;case"mouseout":L=A.relatedTarget||A.toElement;}if(!(function(){while(L&&L.nodeType==3){L=L.parentNode;}return true;}).create({attempt:Browser.Engine.gecko})()){L=false;
}}}}return $extend(this,{event:A,type:J,page:I,client:C,rightClick:E,wheel:H,relatedTarget:L,target:G,code:B,key:M,shift:A.shiftKey,control:A.ctrlKey,alt:A.altKey,meta:A.metaKey});
}});Event.Keys=new Hash({enter:13,up:38,down:40,left:37,right:39,esc:27,space:32,backspace:8,tab:9,"delete":46});Event.implement({stop:function(){return this.stopPropagation().preventDefault();
},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault();
}else{this.event.returnValue=false;}return this;}});var Class=new Native({name:"Class",initialize:function(B){B=B||{};var A=function(E){for(var D in this){this[D]=$unlink(this[D]);
}for(var F in Class.Mutators){if(!this[F]){continue;}Class.Mutators[F](this,this[F]);delete this[F];}this.constructor=A;if(E===$empty){return this;}var C=(this.initialize)?this.initialize.apply(this,arguments):this;
if(this.options&&this.options.initialize){this.options.initialize.call(this);}return C;};$extend(A,this);A.constructor=Class;A.prototype=B;return A;}});
Class.implement({implement:function(){Class.Mutators.Implements(this.prototype,Array.slice(arguments));return this;}});Class.Mutators={Implements:function(A,B){$splat(B).each(function(C){$extend(A,($type(C)=="class")?new C($empty):C);
});},Extends:function(self,klass){var instance=new klass($empty);delete instance.parent;delete instance.parentOf;for(var key in instance){var current=self[key],previous=instance[key];
if(current==undefined){self[key]=previous;continue;}var ctype=$type(current),ptype=$type(previous);if(ctype!=ptype){continue;}switch(ctype){case"function":if(!arguments.callee.caller){self[key]=eval("("+String(current).replace(/\bthis\.parent\(\s*(\))?/g,function(full,close){return"arguments.callee._parent_.call(this"+(close||", ");
})+")");}self[key]._parent_=previous;break;case"object":self[key]=$merge(previous,current);}}self.parent=function(){return arguments.callee.caller._parent_.apply(this,arguments);
};self.parentOf=function(descendant){return descendant._parent_.apply(this,Array.slice(arguments,1));};}};var Chain=new Class({chain:function(){this.$chain=(this.$chain||[]).extend(arguments);
return this;},callChain:function(){return(this.$chain&&this.$chain.length)?this.$chain.shift().apply(this,arguments):false;},clearChain:function(){if(this.$chain){this.$chain.empty();
}return this;}});var Events=new Class({addEvent:function(C,B,A){C=Events.removeOn(C);if(B!=$empty){this.$events=this.$events||{};this.$events[C]=this.$events[C]||[];
this.$events[C].include(B);if(A){B.internal=true;}}return this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);}return this;},fireEvent:function(C,B,A){C=Events.removeOn(C);
if(!this.$events||!this.$events[C]){return this;}this.$events[C].each(function(D){D.create({bind:this,delay:A,"arguments":B})();},this);return this;},removeEvent:function(B,A){B=Events.removeOn(B);
if(!this.$events||!this.$events[B]){return this;}if(!A.internal){this.$events[B].erase(A);}return this;},removeEvents:function(C){for(var D in this.$events){if(C&&C!=D){continue;
}var B=this.$events[D];for(var A=B.length;A--;A){this.removeEvent(D,B[A]);}}return this;}});Events.removeOn=function(A){return A.replace(/^on([A-Z])/,function(B,C){return C.toLowerCase();
});};var Options=new Class({setOptions:function(){this.options=$merge.run([this.options].extend(arguments));if(!this.addEvent){return this;}for(var A in this.options){if($type(this.options[A])!="function"||!(/^on[A-Z]/).test(A)){continue;
}this.addEvent(A,this.options[A]);delete this.options[A];}return this;}});Document.implement({newElement:function(A,B){if(Browser.Engine.trident&&B){["name","type","checked"].each(function(C){if(!B[C]){return ;
}A+=" "+C+'="'+B[C]+'"';if(C!="checked"){delete B[C];}});A="<"+A+">";}return $.element(this.createElement(A)).set(B);},newTextNode:function(A){return this.createTextNode(A);
},getDocument:function(){return this;},getWindow:function(){return this.defaultView||this.parentWindow;},purge:function(){var C=this.getElementsByTagName("*");
for(var B=0,A=C.length;B<A;B++){Browser.freeMem(C[B]);}}});var Element=new Native({name:"Element",legacy:window.Element,initialize:function(A,B){var C=Element.Constructors.get(A);
if(C){return C(B);}if(typeof A=="string"){return document.newElement(A,B);}return $(A).set(B);},afterImplement:function(A,B){if(!Array[A]){Elements.implement(A,Elements.multi(A));
}Element.Prototype[A]=B;}});Element.Prototype={$family:{name:"element"}};Element.Constructors=new Hash;var IFrame=new Native({name:"IFrame",generics:false,initialize:function(){var E=Array.link(arguments,{properties:Object.type,iframe:$defined});
var C=E.properties||{};var B=$(E.iframe)||false;var D=C.onload||$empty;delete C.onload;C.id=C.name=$pick(C.id,C.name,B.id,B.name,"IFrame_"+$time());B=new Element(B||"iframe",C);
var A=function(){var F=$try(function(){return B.contentWindow.location.host;});if(F&&F==window.location.host){var H=new Window(B.contentWindow);var G=new Document(B.contentWindow.document);
$extend(H.Element.prototype,Element.Prototype);}D.call(B.contentWindow,B.contentWindow.document);};(!window.frames[C.id])?B.addListener("load",A):A();return B;
}});var Elements=new Native({initialize:function(F,B){B=$extend({ddup:true,cash:true},B);F=F||[];if(B.ddup||B.cash){var G={},E=[];for(var C=0,A=F.length;
C<A;C++){var D=$.element(F[C],!B.cash);if(B.ddup){if(G[D.uid]){continue;}G[D.uid]=true;}E.push(D);}F=E;}return(B.cash)?$extend(F,this):F;}});Elements.implement({filter:function(A,B){if(!A){return this;
}return new Elements(Array.filter(this,(typeof A=="string")?function(C){return C.match(A);}:A,B));}});Elements.multi=function(A){return function(){var B=[];
var F=true;for(var D=0,C=this.length;D<C;D++){var E=this[D][A].apply(this[D],arguments);B.push(E);if(F){F=($type(E)=="element");}}return(F)?new Elements(B):B;
};};Window.implement({$:function(B,C){if(B&&B.$family&&B.uid){return B;}var A=$type(B);return($[A])?$[A](B,C,this.document):null;},$$:function(A){if(arguments.length==1&&typeof A=="string"){return this.document.getElements(A);
}var F=[];var C=Array.flatten(arguments);for(var D=0,B=C.length;D<B;D++){var E=C[D];switch($type(E)){case"element":E=[E];break;case"string":E=this.document.getElements(E,true);
break;default:E=false;}if(E){F.extend(E);}}return new Elements(F);},getDocument:function(){return this.document;},getWindow:function(){return this;}});
$.string=function(C,B,A){C=A.getElementById(C);return(C)?$.element(C,B):null;};$.element=function(A,D){$uid(A);if(!D&&!A.$family&&!(/^object|embed$/i).test(A.tagName)){var B=Element.Prototype;
for(var C in B){A[C]=B[C];}}return A;};$.object=function(B,C,A){if(B.toElement){return $.element(B.toElement(A),C);}return null;};$.textnode=$.whitespace=$.window=$.document=$arguments(0);
Native.implement([Element,Document],{getElement:function(A,B){return $(this.getElements(A,true)[0]||null,B);},getElements:function(A,D){A=A.split(",");
var C=[];var B=(A.length>1);A.each(function(E){var F=this.getElementsByTagName(E.trim());(B)?C.extend(F):C=F;},this);return new Elements(C,{ddup:B,cash:!D});
}});Element.Storage={get:function(A){return(this[A]||(this[A]={}));}};Element.Inserters=new Hash({before:function(B,A){if(A.parentNode){A.parentNode.insertBefore(B,A);
}},after:function(B,A){if(!A.parentNode){return ;}var C=A.nextSibling;(C)?A.parentNode.insertBefore(B,C):A.parentNode.appendChild(B);},bottom:function(B,A){A.appendChild(B);
},top:function(B,A){var C=A.firstChild;(C)?A.insertBefore(B,C):A.appendChild(B);}});Element.Inserters.inside=Element.Inserters.bottom;Element.Inserters.each(function(C,B){var A=B.capitalize();
Element.implement("inject"+A,function(D){C(this,$(D,true));return this;});Element.implement("grab"+A,function(D){C($(D,true),this);return this;});});Element.implement({getDocument:function(){return this.ownerDocument;
},getWindow:function(){return this.ownerDocument.getWindow();},getElementById:function(D,C){var B=this.ownerDocument.getElementById(D);if(!B){return null;
}for(var A=B.parentNode;A!=this;A=A.parentNode){if(!A){return null;}}return $.element(B,C);},set:function(D,B){switch($type(D)){case"object":for(var C in D){this.set(C,D[C]);
}break;case"string":var A=Element.Properties.get(D);(A&&A.set)?A.set.apply(this,Array.slice(arguments,1)):this.setProperty(D,B);}return this;},get:function(B){var A=Element.Properties.get(B);
return(A&&A.get)?A.get.apply(this,Array.slice(arguments,1)):this.getProperty(B);},erase:function(B){var A=Element.Properties.get(B);(A&&A.erase)?A.erase.apply(this,Array.slice(arguments,1)):this.removeProperty(B);
return this;},match:function(A){return(!A||Element.get(this,"tag")==A);},inject:function(B,A){Element.Inserters.get(A||"bottom")(this,$(B,true));return this;
},wraps:function(B,A){B=$(B,true);return this.replaces(B).grab(B,A);},grab:function(B,A){Element.Inserters.get(A||"bottom")($(B,true),this);return this;
},appendText:function(B,A){return this.grab(this.getDocument().newTextNode(B),A);},adopt:function(){Array.flatten(arguments).each(function(A){A=$(A,true);
if(A){this.appendChild(A);}},this);return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this;},clone:function(D,C){switch($type(this)){case"element":var H={};
for(var G=0,E=this.attributes.length;G<E;G++){var B=this.attributes[G],L=B.nodeName.toLowerCase();if(Browser.Engine.trident&&(/input/i).test(this.tagName)&&(/width|height/).test(L)){continue;
}var K=(L=="style"&&this.style)?this.style.cssText:B.nodeValue;if(!$chk(K)||L=="uid"||(L=="id"&&!C)){continue;}if(K!="inherit"&&["string","number"].contains($type(K))){H[L]=K;
}}var J=new Element(this.nodeName.toLowerCase(),H);if(D!==false){for(var I=0,F=this.childNodes.length;I<F;I++){var A=Element.clone(this.childNodes[I],true,C);
if(A){J.grab(A);}}}return J;case"textnode":return document.newTextNode(this.nodeValue);}return null;},replaces:function(A){A=$(A,true);A.parentNode.replaceChild(this,A);
return this;},hasClass:function(A){return this.className.contains(A," ");},addClass:function(A){if(!this.hasClass(A)){this.className=(this.className+" "+A).clean();
}return this;},removeClass:function(A){this.className=this.className.replace(new RegExp("(^|\\s)"+A+"(?:\\s|$)"),"$1").clean();return this;},toggleClass:function(A){return this.hasClass(A)?this.removeClass(A):this.addClass(A);
},getComputedStyle:function(B){if(this.currentStyle){return this.currentStyle[B.camelCase()];}var A=this.getWindow().getComputedStyle(this,null);return(A)?A.getPropertyValue([B.hyphenate()]):null;
},empty:function(){$A(this.childNodes).each(function(A){Browser.freeMem(A);Element.empty(A);Element.dispose(A);},this);return this;},destroy:function(){Browser.freeMem(this.empty().dispose());
return null;},getSelected:function(){return new Elements($A(this.options).filter(function(A){return A.selected;}));},toQueryString:function(){var A=[];
this.getElements("input, select, textarea").each(function(B){if(!B.name||B.disabled){return ;}var C=(B.tagName.toLowerCase()=="select")?Element.getSelected(B).map(function(D){return D.value;
}):((B.type=="radio"||B.type=="checkbox")&&!B.checked)?null:B.value;$splat(C).each(function(D){if(D){A.push(B.name+"="+encodeURIComponent(D));}});});return A.join("&");
},getProperty:function(C){var B=Element.Attributes,A=B.Props[C];var D=(A)?this[A]:this.getAttribute(C,2);return(B.Bools[C])?!!D:(A)?D:D||null;},getProperties:function(){var A=$A(arguments);
return A.map(function(B){return this.getProperty(B);},this).associate(A);},setProperty:function(D,E){var C=Element.Attributes,B=C.Props[D],A=$defined(E);
if(B&&C.Bools[D]){E=(E||!A)?true:false;}else{if(!A){return this.removeProperty(D);}}(B)?this[B]=E:this.setAttribute(D,E);return this;},setProperties:function(A){for(var B in A){this.setProperty(B,A[B]);
}return this;},removeProperty:function(D){var C=Element.Attributes,B=C.Props[D],A=(B&&C.Bools[D]);(B)?this[B]=(A)?false:"":this.removeAttribute(D);return this;
},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this;}});(function(){var A=function(D,B,I,C,F,H){var E=D[I||B];var G=[];
while(E){if(E.nodeType==1&&(!C||Element.match(E,C))){G.push(E);if(!F){break;}}E=E[B];}return(F)?new Elements(G,{ddup:false,cash:!H}):$(G[0],H);};Element.implement({getPrevious:function(B,C){return A(this,"previousSibling",null,B,false,C);
},getAllPrevious:function(B,C){return A(this,"previousSibling",null,B,true,C);},getNext:function(B,C){return A(this,"nextSibling",null,B,false,C);},getAllNext:function(B,C){return A(this,"nextSibling",null,B,true,C);
},getFirst:function(B,C){return A(this,"nextSibling","firstChild",B,false,C);},getLast:function(B,C){return A(this,"previousSibling","lastChild",B,false,C);
},getParent:function(B,C){return A(this,"parentNode",null,B,false,C);},getParents:function(B,C){return A(this,"parentNode",null,B,true,C);},getChildren:function(B,C){return A(this,"nextSibling","firstChild",B,true,C);
},hasChild:function(B){B=$(B,true);return(!!B&&$A(this.getElementsByTagName(B.tagName)).contains(B));}});})();Element.Properties=new Hash;Element.Properties.style={set:function(A){this.style.cssText=A;
},get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase();
}};Element.Properties.href={get:function(){return(!this.href)?null:this.href.replace(new RegExp("^"+document.location.protocol+"//"+document.location.host),"");
}};Element.Properties.html={set:function(){return this.innerHTML=Array.flatten(arguments).join("");}};Native.implement([Element,Window,Document],{addListener:function(B,A){if(this.addEventListener){this.addEventListener(B,A,false);
}else{this.attachEvent("on"+B,A);}return this;},removeListener:function(B,A){if(this.removeEventListener){this.removeEventListener(B,A,false);}else{this.detachEvent("on"+B,A);
}return this;},retrieve:function(B,A){var D=Element.Storage.get(this.uid);var C=D[B];if($defined(A)&&!$defined(C)){C=D[B]=A;}return $pick(C);},store:function(B,A){var C=Element.Storage.get(this.uid);
C[B]=A;return this;},eliminate:function(A){var B=Element.Storage.get(this.uid);delete B[A];return this;}});Element.Attributes=new Hash({Props:{html:"innerHTML","class":"className","for":"htmlFor",text:(Browser.Engine.trident)?"innerText":"textContent"},Bools:["compact","nowrap","ismap","declare","noshade","checked","disabled","readonly","multiple","selected","noresize","defer"],Camels:["value","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","maxLength","readOnly","rowSpan","tabIndex","useMap"]});
Browser.freeMem=function(A){if(!A){return ;}if(Browser.Engine.trident&&(/object/i).test(A.tagName)){for(var B in A){if(typeof A[B]=="function"){A[B]=$empty;
}}Element.dispose(A);}if(A.uid&&A.removeEvents){A.removeEvents();}};(function(B){var C=B.Bools,A=B.Camels;B.Bools=C=C.associate(C);Hash.extend(Hash.combine(B.Props,C),A.associate(A.map(function(D){return D.toLowerCase();
})));B.erase("Camels");})(Element.Attributes);window.addListener("unload",function(){window.removeListener("unload",arguments.callee);document.purge();
if(Browser.Engine.trident){CollectGarbage();}});Element.Properties.events={set:function(A){this.addEvents(A);}};Native.implement([Element,Window,Document],{addEvent:function(E,G){var H=this.retrieve("events",{});
H[E]=H[E]||{keys:[],values:[]};if(H[E].keys.contains(G)){return this;}H[E].keys.push(G);var F=E,A=Element.Events.get(E),C=G,I=this;if(A){if(A.onAdd){A.onAdd.call(this,G);
}if(A.condition){C=function(J){if(A.condition.call(this,J)){return G.call(this,J);}return false;};}F=A.base||F;}var D=function(){return G.call(I);};var B=Element.NativeEvents[F]||0;
if(B){if(B==2){D=function(J){J=new Event(J,I.getWindow());if(C.call(I,J)===false){J.stop();}};}this.addListener(F,D);}H[E].values.push(D);return this;},removeEvent:function(D,C){var B=this.retrieve("events");
if(!B||!B[D]){return this;}var G=B[D].keys.indexOf(C);if(G==-1){return this;}var A=B[D].keys.splice(G,1)[0];var F=B[D].values.splice(G,1)[0];var E=Element.Events.get(D);
if(E){if(E.onRemove){E.onRemove.call(this,C);}D=E.base||D;}return(Element.NativeEvents[D])?this.removeListener(D,F):this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);
}return this;},removeEvents:function(B){var A=this.retrieve("events");if(!A){return this;}if(!B){for(var C in A){this.removeEvents(C);}A=null;}else{if(A[B]){while(A[B].keys[0]){this.removeEvent(B,A[B].keys[0]);
}A[B]=null;}}return this;},fireEvent:function(D,B,A){var C=this.retrieve("events");if(!C||!C[D]){return this;}C[D].keys.each(function(E){E.create({bind:this,delay:A,"arguments":B})();
},this);return this;},cloneEvents:function(D,A){D=$(D);var C=D.retrieve("events");if(!C){return this;}if(!A){for(var B in C){this.cloneEvents(D,B);}}else{if(C[A]){C[A].keys.each(function(E){this.addEvent(A,E);
},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1};
(function(){var A=function(B){var C=B.relatedTarget;if(C==undefined){return true;}if(C===false){return false;}return($type(this)!="document"&&C!=this&&C.prefix!="xul"&&!this.hasChild(C));
};Element.Events=new Hash({mouseenter:{base:"mouseover",condition:A},mouseleave:{base:"mouseout",condition:A},mousewheel:{base:(Browser.Engine.gecko)?"DOMMouseScroll":"mousewheel"}});
})();Element.Properties.styles={set:function(A){this.setStyles(A);}};Element.Properties.opacity={set:function(A,B){if(!B){if(A==0){if(this.style.visibility!="hidden"){this.style.visibility="hidden";
}}else{if(this.style.visibility!="visible"){this.style.visibility="visible";}}}if(!this.currentStyle||!this.currentStyle.hasLayout){this.style.zoom=1;}if(Browser.Engine.trident){this.style.filter=(A==1)?"":"alpha(opacity="+A*100+")";
}this.style.opacity=A;this.store("opacity",A);},get:function(){return this.retrieve("opacity",1);}};Element.implement({setOpacity:function(A){return this.set("opacity",A,true);
},getOpacity:function(){return this.get("opacity");},setStyle:function(B,A){switch(B){case"opacity":return this.set("opacity",parseFloat(A));case"float":B=(Browser.Engine.trident)?"styleFloat":"cssFloat";
}B=B.camelCase();if($type(A)!="string"){var C=(Element.Styles.get(B)||"@").split(" ");A=$splat(A).map(function(E,D){if(!C[D]){return"";}return($type(E)=="number")?C[D].replace("@",Math.round(E)):E;
}).join(" ");}else{if(A==String(Number(A))){A=Math.round(A);}}this.style[B]=A;return this;},getStyle:function(G){switch(G){case"opacity":return this.get("opacity");
case"float":G=(Browser.Engine.trident)?"styleFloat":"cssFloat";}G=G.camelCase();var A=this.style[G];if(!$chk(A)){A=[];for(var F in Element.ShortStyles){if(G!=F){continue;
}for(var E in Element.ShortStyles[F]){A.push(this.getStyle(E));}return A.join(" ");}A=this.getComputedStyle(G);}if(A){A=String(A);var C=A.match(/rgba?\([\d\s,]+\)/);
if(C){A=A.replace(C[0],C[0].rgbToHex());}}if(Browser.Engine.presto||(Browser.Engine.trident&&!$chk(parseInt(A)))){if(G.test(/^(height|width)$/)){var B=(G=="width")?["left","right"]:["top","bottom"],D=0;
B.each(function(H){D+=this.getStyle("border-"+H+"-width").toInt()+this.getStyle("padding-"+H).toInt();},this);return this["offset"+G.capitalize()]-D+"px";
}if(Browser.Engine.presto&&String(A).test("px")){return A;}if(G.test(/(border(.+)Width|margin|padding)/)){return"0px";}}return A;},setStyles:function(B){for(var A in B){this.setStyle(A,B[A]);
}return this;},getStyles:function(){var A={};Array.each(arguments,function(B){A[B]=this.getStyle(B);},this);return A;}});Element.Styles=new Hash({left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"});
Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};["Top","Right","Bottom","Left"].each(function(G){var F=Element.ShortStyles;
var B=Element.Styles;["margin","padding"].each(function(H){var I=H+G;F[H][I]=B[I]="@px";});var E="border"+G;F.border[E]=B[E]="@px @ rgb(@, @, @)";var D=E+"Width",A=E+"Style",C=E+"Color";
F[E]={};F.borderWidth[D]=F[E][D]=B[D]="@px";F.borderStyle[A]=F[E][A]=B[A]="@";F.borderColor[C]=F[E][C]=B[C]="rgb(@, @, @)";});(function(){Element.implement({scrollTo:function(H,I){if(B(this)){this.getWindow().scrollTo(H,I);
}else{this.scrollLeft=H;this.scrollTop=I;}return this;},getSize:function(){if(B(this)){return this.getWindow().getSize();}return{x:this.offsetWidth,y:this.offsetHeight};
},getScrollSize:function(){if(B(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};},getScroll:function(){if(B(this)){return this.getWindow().getScroll();
}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var I=this,H={x:0,y:0};while(I&&!B(I)){H.x+=I.scrollLeft;H.y+=I.scrollTop;I=I.parentNode;
}return H;},getOffsetParent:function(){var H=this;if(B(H)){return null;}if(!Browser.Engine.trident){return H.offsetParent;}while((H=H.parentNode)&&!B(H)){if(D(H,"position")!="static"){return H;
}}return null;},getOffsets:function(){var I=this,H={x:0,y:0};if(B(this)){return H;}while(I&&!B(I)){H.x+=I.offsetLeft;H.y+=I.offsetTop;if(Browser.Engine.gecko){if(!F(I)){H.x+=C(I);
H.y+=G(I);}var J=I.parentNode;if(J&&D(J,"overflow")!="visible"){H.x+=C(J);H.y+=G(J);}}else{if(I!=this&&(Browser.Engine.trident||Browser.Engine.webkit)){H.x+=C(I);
H.y+=G(I);}}I=I.offsetParent;if(Browser.Engine.trident){while(I&&!I.currentStyle.hasLayout){I=I.offsetParent;}}}if(Browser.Engine.gecko&&!F(this)){H.x-=C(this);
H.y-=G(this);}return H;},getPosition:function(K){if(B(this)){return{x:0,y:0};}var L=this.getOffsets(),I=this.getScrolls();var H={x:L.x-I.x,y:L.y-I.y};var J=(K&&(K=$(K)))?K.getPosition():{x:0,y:0};
return{x:H.x-J.x,y:H.y-J.y};},getCoordinates:function(J){if(B(this)){return this.getWindow().getCoordinates();}var H=this.getPosition(J),I=this.getSize();
var K={left:H.x,top:H.y,width:I.x,height:I.y};K.right=K.left+K.width;K.bottom=K.top+K.height;return K;},computePosition:function(H){return{left:H.x-E(this,"margin-left"),top:H.y-E(this,"margin-top")};
},position:function(H){return this.setStyles(this.computePosition(H));}});Native.implement([Document,Window],{getSize:function(){var I=this.getWindow();
if(Browser.Engine.presto||Browser.Engine.webkit){return{x:I.innerWidth,y:I.innerHeight};}var H=A(this);return{x:H.clientWidth,y:H.clientHeight};},getScroll:function(){var I=this.getWindow();
var H=A(this);return{x:I.pageXOffset||H.scrollLeft,y:I.pageYOffset||H.scrollTop};},getScrollSize:function(){var I=A(this);var H=this.getSize();return{x:Math.max(I.scrollWidth,H.x),y:Math.max(I.scrollHeight,H.y)};
},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var H=this.getSize();return{top:0,left:0,bottom:H.y,right:H.x,height:H.y,width:H.x};
}});var D=Element.getComputedStyle;function E(H,I){return D(H,I).toInt()||0;}function F(H){return D(H,"-moz-box-sizing")=="border-box";}function G(H){return E(H,"border-top-width");
}function C(H){return E(H,"border-left-width");}function B(H){return(/^(?:body|html)$/i).test(H.tagName);}function A(H){var I=H.getDocument();return(!I.compatMode||I.compatMode=="CSS1Compat")?I.html:I.body;
}})();Native.implement([Window,Document,Element],{getHeight:function(){return this.getSize().y;},getWidth:function(){return this.getSize().x;},getScrollTop:function(){return this.getScroll().y;
},getScrollLeft:function(){return this.getScroll().x;},getScrollHeight:function(){return this.getScrollSize().y;},getScrollWidth:function(){return this.getScrollSize().x;
},getTop:function(){return this.getPosition().y;},getLeft:function(){return this.getPosition().x;}});Native.implement([Document,Element],{getElements:function(H,G){H=H.split(",");
var C,E={};for(var D=0,B=H.length;D<B;D++){var A=H[D],F=Selectors.Utils.search(this,A,E);if(D!=0&&F.item){F=$A(F);}C=(D==0)?F:(C.item)?$A(C).concat(F):C.concat(F);
}return new Elements(C,{ddup:(H.length>1),cash:!G});}});Element.implement({match:function(B){if(!B){return true;}var D=Selectors.Utils.parseTagAndID(B);
var A=D[0],E=D[1];if(!Selectors.Filters.byID(this,E)||!Selectors.Filters.byTag(this,A)){return false;}var C=Selectors.Utils.parseSelector(B);return(C)?Selectors.Utils.filter(this,C,{}):true;
}});var Selectors={Cache:{nth:{},parsed:{}}};Selectors.RegExps={id:(/#([\w-]+)/),tag:(/^(\w+|\*)/),quick:(/^(\w+|\*)$/),splitter:(/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),combined:(/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)["']?(.*?)["']?)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)};
Selectors.Utils={chk:function(B,C){if(!C){return true;}var A=$uid(B);if(!C[A]){return C[A]=true;}return false;},parseNthArgument:function(F){if(Selectors.Cache.nth[F]){return Selectors.Cache.nth[F];
}var C=F.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);if(!C){return false;}var E=parseInt(C[1]);var B=(E||E===0)?E:1;var D=C[2]||false;var A=parseInt(C[3])||0;
if(B!=0){A--;while(A<1){A+=B;}while(A>=B){A-=B;}}else{B=A;D="index";}switch(D){case"n":C={a:B,b:A,special:"n"};break;case"odd":C={a:2,b:0,special:"n"};
break;case"even":C={a:2,b:1,special:"n"};break;case"first":C={a:0,special:"index"};break;case"last":C={special:"last-child"};break;case"only":C={special:"only-child"};
break;default:C={a:(B-1),special:"index"};}return Selectors.Cache.nth[F]=C;},parseSelector:function(E){if(Selectors.Cache.parsed[E]){return Selectors.Cache.parsed[E];
}var D,H={classes:[],pseudos:[],attributes:[]};while((D=Selectors.RegExps.combined.exec(E))){var I=D[1],G=D[2],F=D[3],B=D[4],C=D[5],J=D[6];if(I){H.classes.push(I);
}else{if(C){var A=Selectors.Pseudo.get(C);if(A){H.pseudos.push({parser:A,argument:J});}else{H.attributes.push({name:C,operator:"=",value:J});}}else{if(G){H.attributes.push({name:G,operator:F,value:B});
}}}}if(!H.classes.length){delete H.classes;}if(!H.attributes.length){delete H.attributes;}if(!H.pseudos.length){delete H.pseudos;}if(!H.classes&&!H.attributes&&!H.pseudos){H=null;
}return Selectors.Cache.parsed[E]=H;},parseTagAndID:function(B){var A=B.match(Selectors.RegExps.tag);var C=B.match(Selectors.RegExps.id);return[(A)?A[1]:"*",(C)?C[1]:false];
},filter:function(F,C,E){var D;if(C.classes){for(D=C.classes.length;D--;D){var G=C.classes[D];if(!Selectors.Filters.byClass(F,G)){return false;}}}if(C.attributes){for(D=C.attributes.length;
D--;D){var B=C.attributes[D];if(!Selectors.Filters.byAttribute(F,B.name,B.operator,B.value)){return false;}}}if(C.pseudos){for(D=C.pseudos.length;D--;D){var A=C.pseudos[D];
if(!Selectors.Filters.byPseudo(F,A.parser,A.argument,E)){return false;}}}return true;},getByTagAndID:function(B,A,D){if(D){var C=(B.getElementById)?B.getElementById(D,true):Element.getElementById(B,D,true);
return(C&&Selectors.Filters.byTag(C,A))?[C]:[];}else{return B.getElementsByTagName(A);}},search:function(J,I,O){var B=[];var C=I.trim().replace(Selectors.RegExps.splitter,function(Z,Y,X){B.push(Y);
return":)"+X;}).split(":)");var K,F,E,V;for(var U=0,Q=C.length;U<Q;U++){var T=C[U];if(U==0&&Selectors.RegExps.quick.test(T)){K=J.getElementsByTagName(T);
continue;}var A=B[U-1];var L=Selectors.Utils.parseTagAndID(T);var W=L[0],M=L[1];if(U==0){K=Selectors.Utils.getByTagAndID(J,W,M);}else{var D={},H=[];for(var S=0,R=K.length;
S<R;S++){H=Selectors.Getters[A](H,K[S],W,M,D);}K=H;}var G=Selectors.Utils.parseSelector(T);if(G){E=[];for(var P=0,N=K.length;P<N;P++){V=K[P];if(Selectors.Utils.filter(V,G,O)){E.push(V);
}}K=E;}}return K;}};Selectors.Getters={" ":function(H,G,I,A,E){var D=Selectors.Utils.getByTagAndID(G,I,A);for(var C=0,B=D.length;C<B;C++){var F=D[C];if(Selectors.Utils.chk(F,E)){H.push(F);
}}return H;},">":function(H,G,I,A,F){var C=Selectors.Utils.getByTagAndID(G,I,A);for(var E=0,D=C.length;E<D;E++){var B=C[E];if(B.parentNode==G&&Selectors.Utils.chk(B,F)){H.push(B);
}}return H;},"+":function(C,B,A,E,D){while((B=B.nextSibling)){if(B.nodeType==1){if(Selectors.Utils.chk(B,D)&&Selectors.Filters.byTag(B,A)&&Selectors.Filters.byID(B,E)){C.push(B);
}break;}}return C;},"~":function(C,B,A,E,D){while((B=B.nextSibling)){if(B.nodeType==1){if(!Selectors.Utils.chk(B,D)){break;}if(Selectors.Filters.byTag(B,A)&&Selectors.Filters.byID(B,E)){C.push(B);
}}}return C;}};Selectors.Filters={byTag:function(B,A){return(A=="*"||(B.tagName&&B.tagName.toLowerCase()==A));},byID:function(A,B){return(!B||(A.id&&A.id==B));
},byClass:function(B,A){return(B.className&&B.className.contains(A," "));},byPseudo:function(A,D,C,B){return D.call(A,C,B);},byAttribute:function(C,D,B,E){var A=Element.prototype.getProperty.call(C,D);
if(!A){return false;}if(!B||E==undefined){return true;}switch(B){case"=":return(A==E);case"*=":return(A.contains(E));case"^=":return(A.substr(0,E.length)==E);
case"$=":return(A.substr(A.length-E.length)==E);case"!=":return(A!=E);case"~=":return A.contains(E," ");case"|=":return A.contains(E,"-");}return false;
}};Selectors.Pseudo=new Hash({empty:function(){return !(this.innerText||this.textContent||"").length;},not:function(A){return !Element.match(this,A);},contains:function(A){return(this.innerText||this.textContent||"").contains(A);
},"first-child":function(){return Selectors.Pseudo.index.call(this,0);},"last-child":function(){var A=this;while((A=A.nextSibling)){if(A.nodeType==1){return false;
}}return true;},"only-child":function(){var B=this;while((B=B.previousSibling)){if(B.nodeType==1){return false;}}var A=this;while((A=A.nextSibling)){if(A.nodeType==1){return false;
}}return true;},"nth-child":function(G,E){G=(G==undefined)?"n":G;var C=Selectors.Utils.parseNthArgument(G);if(C.special!="n"){return Selectors.Pseudo[C.special].call(this,C.a,E);
}var F=0;E.positions=E.positions||{};var D=$uid(this);if(!E.positions[D]){var B=this;while((B=B.previousSibling)){if(B.nodeType!=1){continue;}F++;var A=E.positions[$uid(B)];
if(A!=undefined){F=A+F;break;}}E.positions[D]=F;}return(E.positions[D]%C.a==C.b);},index:function(A){var B=this,C=0;while((B=B.previousSibling)){if(B.nodeType==1&&++C>A){return false;
}}return(C==A);},even:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n+1",A);},odd:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n",A);
}});Element.Events.domready={onAdd:function(A){if(Browser.loaded){A.call(this);}}};(function(){var B=function(){if(Browser.loaded){return ;}Browser.loaded=true;
window.fireEvent("domready");document.fireEvent("domready");};switch(Browser.Engine.name){case"webkit":(function(){(["loaded","complete"].contains(document.readyState))?B():arguments.callee.delay(50);
})();break;case"trident":var A=document.createElement("div");(function(){($try(function(){A.doScroll("left");return $(A).inject(document.body).set("html","temp").dispose();
}))?B():arguments.callee.delay(50);})();break;default:window.addEvent("load",B);document.addEvent("DOMContentLoaded",B);}})();var JSON=new Hash({encode:function(B){switch($type(B)){case"string":return'"'+B.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';
case"array":return"["+String(B.map(JSON.encode).filter($defined))+"]";case"object":case"hash":var A=[];Hash.each(B,function(E,D){var C=JSON.encode(E);if(C){A.push(JSON.encode(D)+":"+C);
}});return"{"+A+"}";case"number":case"boolean":return String(B);case false:return"null";}return null;},$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(A){return JSON.$specialChars[A]||"\\u00"+Math.floor(A.charCodeAt()/16).toString(16)+(A.charCodeAt()%16).toString(16);
},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null;
}return eval("("+string+")");}});Native.implement([Hash,Array,String,Number],{toJSON:function(){return JSON.encode(this);}});var Cookie=new Class({Implements:Options,options:{path:false,domain:false,duration:false,secure:false,document:document},initialize:function(B,A){this.key=B;
this.setOptions(A);},write:function(B){B=encodeURIComponent(B);if(this.options.domain){B+="; domain="+this.options.domain;}if(this.options.path){B+="; path="+this.options.path;
}if(this.options.duration){var A=new Date();A.setTime(A.getTime()+this.options.duration*24*60*60*1000);B+="; expires="+A.toGMTString();}if(this.options.secure){B+="; secure";
}this.options.document.cookie=this.key+"="+B;return this;},read:function(){var A=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)");
return(A)?decodeURIComponent(A[1]):null;},dispose:function(){new Cookie(this.key,$merge(this.options,{duration:-1})).write("");return this;}});Cookie.write=function(B,C,A){return new Cookie(B,A).write(C);
};Cookie.read=function(A){return new Cookie(A).read();};Cookie.dispose=function(B,A){return new Cookie(B,A).dispose();};var Swiff=new Class({Implements:[Options],options:{id:null,height:1,width:1,container:null,properties:{},params:{quality:"high",allowScriptAccess:"always",wMode:"transparent",swLiveConnect:true},callBacks:{},vars:{}},toElement:function(){return this.object;
},initialize:function(L,M){this.instance="Swiff_"+$time();this.setOptions(M);M=this.options;var B=this.id=M.id||this.instance;var A=$(M.container);Swiff.CallBacks[this.instance]={};
var E=M.params,G=M.vars,F=M.callBacks;var H=$extend({height:M.height,width:M.width},M.properties);var K=this;for(var D in F){Swiff.CallBacks[this.instance][D]=(function(N){return function(){return N.apply(K.object,arguments);
};})(F[D]);G[D]="Swiff.CallBacks."+this.instance+"."+D;}E.flashVars=Hash.toQueryString(G);if(Browser.Engine.trident){H.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
E.movie=L;}else{H.type="application/x-shockwave-flash";H.data=L;}var J='<object id="'+B+'"';for(var I in H){J+=" "+I+'="'+H[I]+'"';}J+=">";for(var C in E){if(E[C]){J+='<param name="'+C+'" value="'+E[C]+'" />';
}}J+="</object>";this.object=((A)?A.empty():new Element("div")).set("html",J).firstChild;},replaces:function(A){A=$(A,true);A.parentNode.replaceChild(this.toElement(),A);
return this;},inject:function(A){$(A,true).appendChild(this.toElement());return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].extend(arguments));
}});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction('<invoke name="'+fn+'" returntype="javascript">'+__flash__argumentsToXML(arguments,2)+"</invoke>");
return eval(rs);};var Fx=new Class({Implements:[Chain,Events,Options],options:{fps:50,unit:false,duration:500,link:"ignore",transition:function(A){return -(Math.cos(Math.PI*A)-1)/2;
}},initialize:function(A){this.subject=this.subject||this;this.setOptions(A);this.options.duration=Fx.Durations[this.options.duration]||this.options.duration.toInt();
var B=this.options.wait;if(B===false){this.options.link="cancel";}},step:function(){var A=$time();if(A<this.time+this.options.duration){var B=this.options.transition((A-this.time)/this.options.duration);
this.set(this.compute(this.from,this.to,B));}else{this.set(this.compute(this.from,this.to,1));this.complete();}},set:function(A){return A;},compute:function(C,B,A){return Fx.compute(C,B,A);
},check:function(A){if(!this.timer){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(A.bind(this,Array.slice(arguments,1)));
return false;}return false;},start:function(B,A){if(!this.check(arguments.callee,B,A)){return this;}this.from=B;this.to=A;this.time=0;this.startTimer();
this.onStart();return this;},complete:function(){if(this.stopTimer()){this.onComplete();}return this;},cancel:function(){if(this.stopTimer()){this.onCancel();
}return this;},onStart:function(){this.fireEvent("start",this.subject);},onComplete:function(){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject);
}},onCancel:function(){this.fireEvent("cancel",this.subject).clearChain();},pause:function(){this.stopTimer();return this;},resume:function(){this.startTimer();
return this;},stopTimer:function(){if(!this.timer){return false;}this.time=$time()-this.time;this.timer=$clear(this.timer);return true;},startTimer:function(){if(this.timer){return false;
}this.time=$time()-this.time;this.timer=this.step.periodical(Math.round(1000/this.options.fps),this);return true;}});Fx.compute=function(C,B,A){return(B-C)*A+C;
};Fx.Durations={"short":250,normal:500,"long":1000};Fx.CSS=new Class({Extends:Fx,prepare:function(D,E,B){B=$splat(B);var C=B[1];if(!$chk(C)){B[1]=B[0];
B[0]=D.getStyle(E);}var A=B.map(this.parse);return{from:A[0],to:A[1]};},parse:function(A){A=$lambda(A)();A=(typeof A=="string")?A.split(" "):$splat(A);
return A.map(function(C){C=String(C);var B=false;Fx.CSS.Parsers.each(function(F,E){if(B){return ;}var D=F.parse(C);if($chk(D)){B={value:D,parser:F};}});
B=B||{value:C,parser:Fx.CSS.Parsers.String};return B;});},compute:function(D,C,B){var A=[];(Math.min(D.length,C.length)).times(function(E){A.push({value:D[E].parser.compute(D[E].value,C[E].value,B),parser:D[E].parser});
});A.$family={name:"fx:css:value"};return A;},serve:function(C,B){if($type(C)!="fx:css:value"){C=this.parse(C);}var A=[];C.each(function(D){A=A.concat(D.parser.serve(D.value,B));
});return A;},render:function(A,D,C,B){A.setStyle(D,this.serve(C,B));},search:function(A){if(Fx.CSS.Cache[A]){return Fx.CSS.Cache[A];}var B={};Array.each(document.styleSheets,function(E,D){var C=E.href;
if(C&&C.contains("://")&&!C.contains(document.domain)){return ;}var F=E.rules||E.cssRules;Array.each(F,function(I,G){if(!I.style){return ;}var H=(I.selectorText)?I.selectorText.replace(/^\w+/,function(J){return J.toLowerCase();
}):null;if(!H||!H.test("^"+A+"$")){return ;}Element.Styles.each(function(K,J){if(!I.style[J]||Element.ShortStyles[J]){return ;}K=String(I.style[J]);B[J]=(K.test(/^rgb/))?K.rgbToHex():K;
});});});return Fx.CSS.Cache[A]=B;}});Fx.CSS.Cache={};Fx.CSS.Parsers=new Hash({Color:{parse:function(A){if(A.match(/^#[0-9a-f]{3,6}$/i)){return A.hexToRgb(true);
}return((A=A.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[A[1],A[2],A[3]]:false;},compute:function(C,B,A){return C.map(function(E,D){return Math.round(Fx.compute(C[D],B[D],A));
});},serve:function(A){return A.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(B,A){return(A)?B+A:B;}},String:{parse:$lambda(false),compute:$arguments(1),serve:$arguments(0)}});
Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(B,A){this.element=this.subject=$(B);this.parent(A);},set:function(B,A){if(arguments.length==1){A=B;
B=this.property||this.options.property;}this.render(this.element,B,A,this.options.unit);return this;},start:function(C,E,D){if(!this.check(arguments.callee,C,E,D)){return this;
}var B=Array.flatten(arguments);this.property=this.options.property||B.shift();var A=this.prepare(this.element,this.property,B);return this.parent(A.from,A.to);
}});Element.Properties.tween={set:function(A){var B=this.retrieve("tween");if(B){B.cancel();}return this.eliminate("tween").store("tween:options",$extend({link:"cancel"},A));
},get:function(A){if(A||!this.retrieve("tween")){if(A||!this.retrieve("tween:options")){this.set("tween",A);}this.store("tween",new Fx.Tween(this,this.retrieve("tween:options")));
}return this.retrieve("tween");}};Element.implement({tween:function(A,C,B){this.get("tween").start(arguments);return this;},fade:function(C){var E=this.get("tween"),D="opacity",A;
C=$pick(C,"toggle");switch(C){case"in":E.start(D,1);break;case"out":E.start(D,0);break;case"show":E.set(D,1);break;case"hide":E.set(D,0);break;case"toggle":var B=this.retrieve("fade:flag",this.get("opacity")==1);
E.start(D,(B)?0:1);this.store("fade:flag",!B);A=true;break;default:E.start(D,arguments);}if(!A){this.eliminate("fade:flag");}return this;},highlight:function(C,A){if(!A){A=this.retrieve("highlight:original",this.getStyle("background-color"));
A=(A=="transparent")?"#fff":A;}var B=this.get("tween");B.start("background-color",C||"#ffff88",A).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original"));
B.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(B,A){this.element=this.subject=$(B);this.parent(A);},set:function(A){if(typeof A=="string"){A=this.search(A);
}for(var B in A){this.render(this.element,B,A[B],this.options.unit);}return this;},compute:function(E,D,C){var A={};for(var B in E){A[B]=this.parent(E[B],D[B],C);
}return A;},start:function(B){if(!this.check(arguments.callee,B)){return this;}if(typeof B=="string"){B=this.search(B);}var E={},D={};for(var C in B){var A=this.prepare(this.element,C,B[C]);
E[C]=A.from;D[C]=A.to;}return this.parent(E,D);}});Element.Properties.morph={set:function(A){var B=this.retrieve("morph");if(B){B.cancel();}return this.eliminate("morph").store("morph:options",$extend({link:"cancel"},A));
},get:function(A){if(A||!this.retrieve("morph")){if(A||!this.retrieve("morph:options")){this.set("morph",A);}this.store("morph",new Fx.Morph(this,this.retrieve("morph:options")));
}return this.retrieve("morph");}};Element.implement({morph:function(A){this.get("morph").start(A);return this;}});(function(){var A=Fx.prototype.initialize;
Fx.prototype.initialize=function(B){A.call(this,B);var C=this.options.transition;if(typeof C=="string"&&(C=C.split(":"))){var D=Fx.Transitions;D=D[C[0]]||D[C[0].capitalize()];
if(C[1]){D=D["ease"+C[1].capitalize()+(C[2]?C[2].capitalize():"")];}this.options.transition=D;}};})();Fx.Transition=function(B,A){A=$splat(A);return $extend(B,{easeIn:function(C){return B(C,A);
},easeOut:function(C){return 1-B(1-C,A);},easeInOut:function(C){return(C<=0.5)?B(2*C,A)/2:(2-B(2*(1-C),A))/2;}});};Fx.Transitions=new Hash({linear:$arguments(0)});
Fx.Transitions.extend=function(A){for(var B in A){Fx.Transitions[B]=new Fx.Transition(A[B]);}};Fx.Transitions.extend({Pow:function(B,A){return Math.pow(B,A[0]||6);
},Expo:function(A){return Math.pow(2,8*(A-1));},Circ:function(A){return 1-Math.sin(Math.acos(A));},Sine:function(A){return 1-Math.sin((1-A)*Math.PI/2);
},Back:function(B,A){A=A[0]||1.618;return Math.pow(B,2)*((A+1)*B-A);},Bounce:function(D){var C;for(var B=0,A=1;1;B+=A,A/=2){if(D>=(7-4*B)/11){C=-Math.pow((11-6*B-11*D)/4,2)+A*A;
break;}}return C;},Elastic:function(B,A){return Math.pow(2,10*--B)*Math.cos(20*B*Math.PI*(A[0]||1)/3);}});["Quad","Cubic","Quart","Quint"].each(function(B,A){Fx.Transitions[B]=new Fx.Transition(function(C){return Math.pow(C,[A+2]);
});});var Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false},initialize:function(A){this.xhr=new Browser.Request();
this.setOptions(A);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=new Hash(this.options.headers);},onStateChange:function(){if(this.xhr.readyState!=4||!this.running){return ;
}this.running=false;this.status=0;$try(function(){this.status=this.xhr.status;}.bind(this));if(this.options.isSuccess.call(this,this.status)){this.response={text:this.xhr.responseText,xml:this.xhr.responseXML};
this.success(this.response.text,this.response.xml);}else{this.response={text:null,xml:null};this.failure();}this.xhr.onreadystatechange=$empty;},isSuccess:function(){return((this.status>=200)&&(this.status<300));
},processScripts:function(A){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return $exec(A);}return A.stripScripts(this.options.evalScripts);
},success:function(B,A){this.onSuccess(this.processScripts(B),A);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain();
},failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},setHeader:function(A,B){this.headers.set(A,B);
return this;},getHeader:function(A){return $try(function(){return this.xhr.getResponseHeader(A);}.bind(this));},check:function(A){if(!this.running){return true;
}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(A.bind(this,Array.slice(arguments,1)));return false;}return false;
},send:function(I){if(!this.check(arguments.callee,I)){return this;}this.running=true;var G=$type(I);if(G=="string"||G=="element"){I={data:I};}var D=this.options;
I=$extend({data:D.data,url:D.url,method:D.method},I);var E=I.data,B=I.url,A=I.method;switch($type(E)){case"element":E=$(E).toQueryString();break;case"object":case"hash":E=Hash.toQueryString(E);
}if(this.options.format){var H="format="+this.options.format;E=(E)?H+"&"+E:H;}if(this.options.emulation&&["put","delete"].contains(A)){var F="_method="+A;
E=(E)?F+"&"+E:F;A="post";}if(this.options.urlEncoded&&A=="post"){var C=(this.options.encoding)?"; charset="+this.options.encoding:"";this.headers.set("Content-type","application/x-www-form-urlencoded"+C);
}if(E&&A=="get"){B=B+(B.contains("?")?"&":"?")+E;E=null;}this.xhr.open(A.toUpperCase(),B,this.options.async);this.xhr.onreadystatechange=this.onStateChange.bind(this);
this.headers.each(function(K,J){if(!$try(function(){this.xhr.setRequestHeader(J,K);return true;}.bind(this))){this.fireEvent("exception",[J,K]);}},this);
this.fireEvent("request");this.xhr.send(E);if(!this.options.async){this.onStateChange();}return this;},cancel:function(){if(!this.running){return this;
}this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$empty;this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});(function(){var A={};
["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(B){A[B]=function(){var C=Array.link(arguments,{url:String.type,data:$defined});
return this.send($extend(C,{method:B.toLowerCase()}));};});Request.implement(A);})();Element.Properties.send={set:function(A){var B=this.retrieve("send");
if(B){B.cancel();}return this.eliminate("send").store("send:options",$extend({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")},A));
},get:function(A){if(A||!this.retrieve("send")){if(A||!this.retrieve("send:options")){this.set("send",A);}this.store("send",new Request(this.retrieve("send:options")));
}return this.retrieve("send");}};Element.implement({send:function(A){var B=this.get("send");B.send({data:this,url:A||B.options.url});return this;}});Request.HTML=new Class({Extends:Request,options:{update:false,evalScripts:true,filter:false},processHTML:function(C){var B=C.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
C=(B)?B[1]:C;var A=new Element("div");return $try(function(){var D="<root>"+C+"</root>",G;if(Browser.Engine.trident){G=new ActiveXObject("Microsoft.XMLDOM");
G.async=false;G.loadXML(D);}else{G=new DOMParser().parseFromString(D,"text/xml");}D=G.getElementsByTagName("root")[0];for(var F=0,E=D.childNodes.length;
F<E;F++){var H=Element.clone(D.childNodes[F],true,true);if(H){A.grab(H);}}return A;})||A.set("html",C);},success:function(D){var C=this.options,B=this.response;
B.html=D.stripScripts(function(E){B.javascript=E;});var A=this.processHTML(B.html);B.tree=A.childNodes;B.elements=A.getElements("*");if(C.filter){B.tree=B.elements.filter(C.filter);
}if(C.update){$(C.update).empty().adopt(B.tree);}if(C.evalScripts){$exec(B.javascript);}this.onSuccess(B.tree,B.elements,B.html,B.javascript);}});Element.Properties.load={set:function(A){var B=this.retrieve("load");
if(B){send.cancel();}return this.eliminate("load").store("load:options",$extend({data:this,link:"cancel",update:this,method:"get"},A));},get:function(A){if(A||!this.retrieve("load")){if(A||!this.retrieve("load:options")){this.set("load",A);
}this.store("load",new Request.HTML(this.retrieve("load:options")));}return this.retrieve("load");}};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Object.type,url:String.type}));
return this;}});Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(A){this.parent(A);this.headers.extend({Accept:"application/json","X-Request":"JSON"});
},success:function(A){this.response.json=JSON.decode(A,this.options.secure);this.onSuccess(this.response.json,A);}});

View file

@ -0,0 +1,109 @@
/**
* Autocompleter.Request
*
* http://digitarald.de/project/autocompleter/
*
* @version 1.1.2
*
* @license MIT-style license
* @author Harald Kirschner <mail [at] digitarald.de>
* @copyright Author
*/
Autocompleter.Request = new Class({
Extends: Autocompleter,
options: {/*
indicator: null,
indicatorClass: null,
onRequest: $empty,
onComplete: $empty,*/
postData: {},
ajaxOptions: {},
postVar: 'value'
},
query: function(){
var data = $unlink(this.options.postData) || {};
data[this.options.postVar] = this.queryValue;
var indicator = $(this.options.indicator);
if (indicator) indicator.setStyle('display', '');
var cls = this.options.indicatorClass;
if (cls) this.element.addClass(cls);
this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
this.request.send({'data': data});
},
/**
* queryResponse - abstract
*
* Inherated classes have to extend this function and use this.parent()
*/
queryResponse: function() {
var indicator = $(this.options.indicator);
if (indicator) indicator.setStyle('display', 'none');
var cls = this.options.indicatorClass;
if (cls) this.element.removeClass(cls);
return this.fireEvent('onComplete', [this.element, this.request]);
}
});
Autocompleter.Request.JSON = new Class({
Extends: Autocompleter.Request,
initialize: function(el, url, options) {
this.parent(el, options);
this.request = new Request.JSON($merge({
'url': url,
'link': 'cancel'
}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
},
queryResponse: function(response) {
this.parent();
this.update(response);
}
});
Autocompleter.Request.HTML = new Class({
Extends: Autocompleter.Request,
initialize: function(el, url, options) {
this.parent(el, options);
this.request = new Request.HTML($merge({
'url': url,
'link': 'cancel',
'update': this.choices
}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
},
queryResponse: function(tree, elements) {
this.parent();
if (!elements || !elements.length) {
this.hideChoices();
} else {
this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function(choice) {
var value = choice.innerHTML;
choice.inputValue = value;
this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
}, this);
this.showChoices();
}
}
});
/* compatibility */
Autocompleter.Ajax = {
Base: Autocompleter.Request,
Json: Autocompleter.Request.JSON,
Xhtml: Autocompleter.Request.HTML
};

View file

@ -0,0 +1,442 @@
/**
* Autocompleter
*
* http://digitarald.de/project/autocompleter/
*
* @version 1.1.2
*
* @license MIT-style license
* @author Harald Kirschner <mail [at] digitarald.de>
* @copyright Author
*/
var Autocompleter = new Class({
Implements: [Options, Events],
options: {/*
onOver: $empty,
onSelect: $empty,
onSelection: $empty,
onShow: $empty,
onHide: $empty,
onBlur: $empty,
onFocus: $empty,*/
minLength: 1,
markQuery: true,
width: 'inherit',
maxChoices: 10,
injectChoice: null,
customChoices: null,
emptyChoices: null,
visibleChoices: true,
className: 'autocompleter-choices',
zIndex: 42,
delay: 400,
observerOptions: {},
fxOptions: {},
autoSubmit: false,
overflow: false,
overflowMargin: 25,
selectFirst: false,
filter: null,
filterCase: false,
filterSubset: false,
forceSelect: false,
selectMode: true,
choicesMatch: null,
multiple: false,
separator: ', ',
separatorSplit: /\s*[,;]\s*/,
autoTrim: false,
allowDupes: false,
cache: true,
relative: false
},
initialize: function(element, options) {
this.element = $(element);
this.setOptions(options);
this.build();
this.observer = new Observer(this.element, this.prefetch.bind(this), $merge({
'delay': this.options.delay
}, this.options.observerOptions));
this.queryValue = null;
if (this.options.filter) this.filter = this.options.filter.bind(this);
var mode = this.options.selectMode;
this.typeAhead = (mode == 'type-ahead');
this.selectMode = (mode === true) ? 'selection' : mode;
this.cached = [];
},
/**
* build - Initialize DOM
*
* Builds the html structure for choices and appends the events to the element.
* Override this function to modify the html generation.
*/
build: function() {
if ($(this.options.customChoices)) {
this.choices = this.options.customChoices;
} else {
this.choices = new Element('ul', {
'class': this.options.className,
'styles': {
'zIndex': this.options.zIndex
}
}).inject(document.body);
this.relative = false;
if (this.options.relative) {
this.choices.inject(this.element, 'after');
this.relative = this.element.getOffsetParent();
}
this.fix = new OverlayFix(this.choices);
}
if (!this.options.separator.test(this.options.separatorSplit)) {
this.options.separatorSplit = this.options.separator;
}
this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, $merge({
'property': 'opacity',
'link': 'cancel',
'duration': 200
}, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
this.element.setProperty('autocomplete', 'off')
.addEvent((Browser.Engine.trident || Browser.Engine.webkit) ? 'keydown' : 'keypress', this.onCommand.bind(this))
.addEvent('click', this.onCommand.bind(this, [false]))
.addEvent('focus', this.toggleFocus.create({bind: this, arguments: true, delay: 100}))
.addEvent('blur', this.toggleFocus.create({bind: this, arguments: false, delay: 100}));
},
destroy: function() {
if (this.fix) this.fix.destroy();
this.choices = this.selected = this.choices.destroy();
},
toggleFocus: function(state) {
this.focussed = state;
if (!state) this.hideChoices(true);
this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]);
},
onCommand: function(e) {
if (!e && this.focussed) return this.prefetch();
if (e && e.key && !e.shift) {
switch (e.key) {
case 'enter':
if (this.element.value != this.opted) return true;
if (this.selected && this.visible) {
this.choiceSelect(this.selected);
return !!(this.options.autoSubmit);
}
break;
case 'up': case 'down':
if (!this.prefetch() && this.queryValue !== null) {
var up = (e.key == 'up');
this.choiceOver((this.selected || this.choices)[
(this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')
](this.options.choicesMatch), true);
}
return false;
case 'esc': case 'tab':
this.hideChoices(true);
break;
}
}
return true;
},
setSelection: function(finish) {
var input = this.selected.inputValue, value = input;
var start = this.queryValue.length, end = input.length;
if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
if (this.options.multiple) {
var split = this.options.separatorSplit;
value = this.element.value;
start += this.queryIndex;
end += this.queryIndex;
var old = value.substr(this.queryIndex).split(split, 1)[0];
value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
if (finish) {
var tokens = value.split(this.options.separatorSplit).filter(function(entry) {
return this.test(entry);
}, /[^\s,]+/);
if (!this.options.allowDupes) tokens = [].combine(tokens);
var sep = this.options.separator;
value = tokens.join(sep) + sep;
end = value.length;
}
}
this.observer.setValue(value);
this.opted = value;
if (finish || this.selectMode == 'pick') start = end;
this.element.selectRange(start, end);
this.fireEvent('onSelection', [this.element, this.selected, value, input]);
},
showChoices: function() {
var match = this.options.choicesMatch, first = this.choices.getFirst(match);
this.selected = this.selectedValue = null;
if (this.fix) {
var pos = this.element.getCoordinates(this.relative), width = this.options.width || 'auto';
this.choices.setStyles({
'left': pos.left,
'top': pos.bottom,
'width': (width === true || width == 'inherit') ? pos.width : width
});
}
if (!first) return;
if (!this.visible) {
this.visible = true;
this.choices.setStyle('display', '');
if (this.fx) this.fx.start(1);
this.fireEvent('onShow', [this.element, this.choices]);
}
if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
var items = this.choices.getChildren(match), max = this.options.maxChoices;
var styles = {'overflowY': 'hidden', 'height': ''};
this.overflown = false;
if (items.length > max) {
var item = items[max - 1];
styles.overflowY = 'scroll';
styles.height = item.getCoordinates(this.choices).bottom;
this.overflown = true;
};
this.choices.setStyles(styles);
this.fix.show();
if (this.options.visibleChoices) {
var scroll = document.getScroll(),
size = document.getSize(),
coords = this.choices.getCoordinates();
if (coords.right > scroll.x + size.x) scroll.x = coords.right - size.x;
if (coords.bottom > scroll.y + size.y) scroll.y = coords.bottom - size.y;
window.scrollTo(Math.min(scroll.x, coords.left), Math.min(scroll.y, coords.top));
}
},
hideChoices: function(clear) {
if (clear) {
var value = this.element.value;
if (this.options.forceSelect) value = this.opted;
if (this.options.autoTrim) {
value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator);
}
this.observer.setValue(value);
}
if (!this.visible) return;
this.visible = false;
if (this.selected) this.selected.removeClass('autocompleter-selected');
this.observer.clear();
var hide = function(){
this.choices.setStyle('display', 'none');
this.fix.hide();
}.bind(this);
if (this.fx) this.fx.start(0).chain(hide);
else hide();
this.fireEvent('onHide', [this.element, this.choices]);
},
prefetch: function() {
var value = this.element.value, query = value;
if (this.options.multiple) {
var split = this.options.separatorSplit;
var values = value.split(split);
var index = this.element.getSelectedRange().start;
var toIndex = value.substr(0, index).split(split);
var last = toIndex.length - 1;
index -= toIndex[last].length;
query = values[last];
}
if (query.length < this.options.minLength) {
this.hideChoices();
} else {
if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
if (this.visible) return false;
this.showChoices();
} else {
this.queryValue = query;
this.queryIndex = index;
if (!this.fetchCached()) this.query();
}
}
return true;
},
fetchCached: function() {
return false;
if (!this.options.cache
|| !this.cached
|| !this.cached.length
|| this.cached.length >= this.options.maxChoices
|| this.queryValue) return false;
this.update(this.filter(this.cached));
return true;
},
update: function(tokens) {
this.choices.empty();
this.cached = tokens;
var type = tokens && $type(tokens);
if (!type || (type == 'array' && !tokens.length) || (type == 'hash' && !tokens.getLength())) {
(this.options.emptyChoices || this.hideChoices).call(this);
} else {
if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices;
tokens.each(this.options.injectChoice || function(token){
var choice = new Element('li', {'html': this.markQueryValue(token)});
choice.inputValue = token;
this.addChoiceEvents(choice).inject(this.choices);
}, this);
this.showChoices();
}
},
choiceOver: function(choice, selection) {
if (!choice || choice == this.selected) return;
if (this.selected) this.selected.removeClass('autocompleter-selected');
this.selected = choice.addClass('autocompleter-selected');
this.fireEvent('onSelect', [this.element, this.selected, selection]);
if (!this.selectMode) this.opted = this.element.value;
if (!selection) return;
this.selectedValue = this.selected.inputValue;
if (this.overflown) {
var coords = this.selected.getCoordinates(this.choices), margin = this.options.overflowMargin,
top = this.choices.scrollTop, height = this.choices.offsetHeight, bottom = top + height;
if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom);
}
if (this.selectMode) this.setSelection();
},
choiceSelect: function(choice) {
if (choice) this.choiceOver(choice);
this.setSelection(true);
this.queryValue = false;
this.hideChoices();
},
filter: function(tokens) {
return (tokens || this.tokens).filter(function(token) {
return this.test(token);
}, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'));
},
/**
* markQueryValue
*
* Marks the queried word in the given string with <span class="autocompleter-queried">*</span>
* Call this i.e. from your custom parseChoices, same for addChoiceEvents
*
* @param {String} Text
* @return {String} Text
*/
markQueryValue: function(str) {
return (!this.options.markQuery || !this.queryValue) ? str
: str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>');
},
/**
* addChoiceEvents
*
* Appends the needed event handlers for a choice-entry to the given element.
*
* @param {Element} Choice entry
* @return {Element} Choice entry
*/
addChoiceEvents: function(el) {
return el.addEvents({
'mouseover': this.choiceOver.bind(this, [el]),
'click': this.choiceSelect.bind(this, [el])
});
}
});
var OverlayFix = new Class({
initialize: function(el) {
if (Browser.Engine.trident) {
this.element = $(el);
this.relative = this.element.getOffsetParent();
this.fix = new Element('iframe', {
'frameborder': '0',
'scrolling': 'no',
'src': 'javascript:false;',
'styles': {
'position': 'absolute',
'border': 'none',
'display': 'none',
'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
}
}).inject(this.element, 'after');
}
},
show: function() {
if (this.fix) {
var coords = this.element.getCoordinates(this.relative);
delete coords.right;
delete coords.bottom;
this.fix.setStyles($extend(coords, {
'display': '',
'zIndex': (this.element.getStyle('zIndex') || 1) - 1
}));
}
return this;
},
hide: function() {
if (this.fix) this.fix.setStyle('display', 'none');
return this;
},
destroy: function() {
if (this.fix) this.fix = this.fix.destroy();
}
});
Element.implement({
getSelectedRange: function() {
if (!Browser.Engine.trident) return {start: this.selectionStart, end: this.selectionEnd};
var pos = {start: 0, end: 0};
var range = this.getDocument().selection.createRange();
if (!range || range.parentElement() != this) return pos;
var dup = range.duplicate();
if (this.type == 'text') {
pos.start = 0 - dup.moveStart('character', -100000);
pos.end = pos.start + range.text.length;
} else {
var value = this.value;
var offset = value.length - value.match(/[\n\r]*$/)[0].length;
dup.moveToElementText(this);
dup.setEndPoint('StartToEnd', range);
pos.end = offset - dup.text.length;
dup.setEndPoint('StartToStart', range);
pos.start = offset - dup.text.length;
}
return pos;
},
selectRange: function(start, end) {
if (Browser.Engine.trident) {
var diff = this.value.substr(start, end - start).replace(/\r/g, '').length;
start = this.value.substr(0, start).replace(/\r/g, '').length;
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', start + diff);
range.moveStart('character', start);
range.select();
} else {
this.focus();
this.setSelectionRange(start, end);
}
return this;
}
});
/* compatibility */
Autocompleter.Base = Autocompleter;

View file

@ -0,0 +1,69 @@
/**
* Observer - Observe formelements for changes
*
* - Additional code from clientside.cnet.com
*
* @version 1.1
*
* @license MIT-style license
* @author Harald Kirschner <mail [at] digitarald.de>
* @copyright Author
*/
var Observer = new Class({
Implements: [Options, Events],
options: {
periodical: false,
delay: 1000
},
initialize: function(el, onFired, options){
this.element = $(el) || $$(el);
this.addEvent('onFired', onFired);
this.setOptions(options);
this.bound = this.changed.bind(this);
this.resume();
},
changed: function() {
var value = this.element.get('value');
if ($equals(this.value, value)) return;
this.clear();
this.value = value;
this.timeout = this.onFired.delay(this.options.delay, this);
},
setValue: function(value) {
this.value = value;
this.element.set('value', value);
return this.clear();
},
onFired: function() {
this.fireEvent('onFired', [this.value, this.element]);
},
clear: function() {
$clear(this.timeout || null);
return this;
},
pause: function(){
if (this.timer) $clear(this.timer);
else this.element.removeEvent('keyup', this.bound);
return this.clear();
},
resume: function(){
this.value = this.element.get('value');
if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
else this.element.addEvent('keyup', this.bound);
return this;
}
});
var $equals = function(obj1, obj2) {
return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};

View file

@ -0,0 +1,55 @@
.roar-body
{
position: absolute;
font: 12px/14px "Lucida Grande", Arial, Helvetica, Verdana, sans-serif;
color: #fff;
text-align: left;
z-index: 999;
}
.roar
{
position: absolute;
width: 300px;
cursor: pointer;
}
.roar-bg
{
position: absolute;
z-index: 1000;
width: 100%;
height: 100%;
left: 0;
top: 0;
background-color: #000;
-moz-border-radius: 10px;
-webkit-border-radius: 5px;
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}
.roar-body-ugly .roar
{
background-color: #333;
}
.roar-body-ugly .roar-bg
{
display: none;
}
.roar h3
{
position: relative;
padding: 15px 10px 0;
margin: 0;
border: 0;
font-size: 13px;
color: #fff;
z-index: 1002;
}
.roar p
{
position: relative;
padding: 10px 10px 15px;
margin: 0;
font-size: 12px;
color: #fff;
z-index: 1002;
}

View file

@ -0,0 +1,167 @@
/**
* Roar - Notifications
*
* Inspired by Growl
*
* @version 1.0.1
*
* @license MIT-style license
* @author Harald Kirschner <mail [at] digitarald.de>
* @copyright Author
*/
var Roar = new Class({
Implements: [Options, Events, Chain],
options: {
duration: 4000,
position: 'upperLeft',
container: null,
bodyFx: null,
itemFx: null,
margin: {x: 10, y: 10},
offset: 5,
className: 'roar',
onShow: $empty,
onHide: $empty,
onRender: $empty,
style: 'notice'
},
initialize: function(options) {
this.setOptions(options);
this.items = [];
this.container = $(this.options.container) || document;
},
alert: function(title, message, options) {
var params = Array.link(arguments, {title: String.type, message: String.type, options: Object.type});
var items = [new Element('h3', {'html': $pick(params.title, '')})];
if (params.message) items.push(new Element('p', {'html': params.message}));
return this.inject(items, params.options);
},
inject: function(elements, options) {
if (!this.body) this.render();
options = options || {};
var offset = [-this.options.offset, 0];
var last = this.items.getLast();
if (last) {
offset[0] = last.retrieve('roar:offset');
offset[1] = offset[0] + last.offsetHeight + this.options.offset;
}
var to = {'opacity': 1};
to[this.align.y] = offset;
var item = new Element('div', {
'class': this.options.className,
'opacity': 0
}).adopt(
new Element('div', {
'class': this.options.className+'-bg',
'opacity': 0.7
}),
elements
);
item.setStyle(this.align.x, 0).store('roar:offset', offset[1]).set('morph', $merge({
unit: 'px',
link: 'cancel',
onStart: Chain.prototype.clearChain,
transition: Fx.Transitions.Back.easeOut
}, this.options.itemFx));
var remove = this.remove.create({
bind: this,
arguments: [item],
delay: 10
});
this.items.push(item.addEvent('click', remove));
if (this.options.duration) {
var over = false;
var trigger = (function() {
trigger = null;
if (!over) remove();
}).delay(this.options.duration);
item.addEvents({
mouseover: function() {
over = true;
},
mouseout: function() {
over = false;
if (!trigger) remove();
}
});
}
item.inject(this.body).morph(to);
return this.fireEvent('onShow', [item, this.items.length]);
},
remove: function(item) {
var index = this.items.indexOf(item);
if (index == -1) return this;
this.items.splice(index, 1);
item.removeEvents();
var to = {opacity: 0};
to[this.align.y] = item.getStyle(this.align.y).toInt() - item.offsetHeight - this.options.offset;
item.morph(to).get('morph').chain(item.destroy.bind(item));
return this.fireEvent('onHide', [item, this.items.length]).callChain(item);
},
empty: function() {
while (this.items.length) this.remove(this.items[0]);
return this;
},
render: function() {
this.position = this.options.position;
if ($type(this.position) == 'string') {
var position = {x: 'center', y: 'center'};
this.align = {x: 'left', y: 'top'};
if ((/left|west/i).test(this.position)) position.x = 'left';
else if ((/right|east/i).test(this.position)) this.align.x = position.x = 'right';
if ((/upper|top|north/i).test(this.position)) position.y = 'top';
else if ((/bottom|lower|south/i).test(this.position)) this.align.y = position.y = 'bottom';
this.position = position;
}
this.body = new Element('div', {'class': this.options.className+'-body'}).inject(document.body);
if (Browser.Engine.trident4) this.body.addClass(this.options.className+'-body-ugly');
this.moveTo = this.body.setStyles.bind(this.body);
this.reposition();
if (this.options.bodyFx) {
var morph = new Fx.Morph(this.body, $merge({
unit: 'px',
chain: 'cancel',
transition: Fx.Transitions.Circ.easeOut
}, this.options.bodyFx));
this.moveTo = morph.start.bind(morph);
}
var repos = this.reposition.bind(this);
window.addEvents({
scroll: repos,
resize: repos
});
this.fireEvent('onRender', this.body);
},
reposition: function() {
var max = document.getCoordinates(), scroll = document.getScroll(), margin = this.options.margin;
max.left += scroll.x;
max.right += scroll.x;
max.top += scroll.y;
max.bottom += scroll.y;
var rel = ($type(this.container) == 'element') ? this.container.getCoordinates() : max;
this.moveTo({
left: (this.position.x == 'right')
? (Math.min(rel.right, max.right) - margin.x)
: (Math.max(rel.left, max.left) + margin.x),
top: (this.position.y == 'bottom')
? (Math.min(rel.bottom, max.bottom) - margin.y)
: (Math.max(rel.top, max.top) + margin.y)
});
}
});

View file

@ -0,0 +1,7 @@
Smarty is supported only in PHP 4.0.6 or later.
Smarty versions previous to 2.0 require the PEAR libraries. Be sure to include
the path to the PEAR libraries in your php include_path. Config_file.class.php
uses the PEAR library for its error handling routines. PEAR comes with the PHP
distribution. Unix users check /usr/local/lib/php, windows users check
C:/php/pear.

View file

@ -0,0 +1,458 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS

File diff suppressed because it is too large Load diff

284
classes/lib/external/Smarty-2.6.19/FAQ vendored Normal file
View file

@ -0,0 +1,284 @@
QUESTION INDEX
--------------
GENERAL
Q: What is Smarty?
Q: What's the difference between Smarty and other template engines?
Q: What do you mean "Compiled PHP Scripts" ?
Q: Why can't I just use PHPA (http://php-accelerator.co.uk) or Zend Cache?
Q: Why does smarty have a built in cache? Wouldn't it be better to handle this
in a separate class?
Q: Is Smarty faster than <insert other PHP template engine>?
Q: How can I be sure to get the best performance from Smarty?
Q: Do you have a mailing list?
Q: Can you change the mailing list so reply-to sends to the list and not the
user?
TROUBLESHOOTING
Q: Smarty doesn't work.
Q: I get the following error when running Smarty:
Warning: Smarty error: problem creating directory "templates_c/239/239105369"
in /path/to/Smarty.class.php on line 542
Q: I get the following error when running Smarty:
Warning: Wrong parameter count for preg_replace() in
Smarty.class.php on line 371
Q: I get this error when passing variables to {include}:
Fatal error: Call to undefined function: get_defined_vars() in
/path/to/Smarty/templates_c/index.tpl.php on line 8
Q: I get PHP errors in my {if} tag logic.
Q: I'm changing my php code and/or templates, and my results are not getting
updated.
Q: I'm running Windows 2000 and I get blank content. My compiled PHP files are
also zero length.
Q: The template goes into an infinite loop when I include included templates
that pass local variables
Q: Javascript is causing Smarty errors in my templates.
Q: I get "SAFE MODE Restriction in effect. ..."-errors when running smarty.
MISC
Q: Can I use Macromedia's Dreamweaver to edit my templates?
Q: Dreamweaver is urlencoding the template delimiters when they are in a SRC or
HREF link. How do I get around this?
HOWTO
Q: How do I generate different cache files per template based on arguments
passed to the page?
Q: How do I pass a template variable as a parameter? {function param={$varname}}
does not work.
Q: How do I include cached template(s) within a non-cached template?
GENERAL
-------
Q: What is Smarty?
A: Smarty is a template engine for PHP... but be aware this isn't just another
PHP template engine. It's much more than that.
Q: What's the difference between Smarty and other template engines?
A: Most other template engines for PHP provide basic variable substitution and
dynamic block functionality. Smarty takes a step further to be a "smart"
template engine, adding features such as configuration files, template
functions, variable modifiers (see the docs!) and making all of this
functionality as easy as possible to use for both programmers and template
designers. Smarty also compiles the templates into PHP scripts, eliminating
the need to parse the templates on every invocation, making Smarty extremely
scalable and manageable for large application needs.
Q: What do you mean "Compiled PHP Scripts" ?
A: Smarty reads the template files and creates PHP scripts from them. Once
these PHP scripts are created, Smarty executes these, never having to parse
the template files again. If you change a template file, Smarty will
recreate the PHP script for it. All this is done automatically by Smarty.
Template designers never need to mess with the generated PHP scripts or even
know of their existance. (NOTE: you can turn off this compile checking step
in Smarty for increased performance.)
Q: Why can't I just use PHPA (http://php-accelerator.co.uk) or Zend Cache?
A: You certainly can, and we highly recommend it! What PHPA does is caches
compiled bytecode of your PHP scripts in shared memory or in a file. This
speeds up server response and saves the compilation step. Smarty creates PHP
scripts, which PHPA will cache nicely. Now, Smarty's built-in cache is
something completely different. It caches the _output_ of the template
contents. For example, if you have a template that requires several database
queries, Smarty can cache this output, saving the need to call the database
every time. Smarty and PHPA (or Zend Cache) complement each other nicely. If
performance is of the utmost importance, we would recommend using one of
these with any PHP application, using Smarty or not. As you can see in the
benchmarks, Smartys performance _really_ excels in combination with a PHP
accelerator.
Q: Why does Smarty have a built in cache? Wouldn't it be better to handle this
in a separate class?
A: Smarty's caching functionality is tightly integrated with the template
engine, making it quite a bit more flexible than a simple caching wrapper.
For instance, you can cache select portions of a template page. Let's say
you have a polling box on your site. With Smarty, you can leave the poll
dynamic and cache the rest of the page. You can also pass templates
multiple cache ids, meaning that a template can have several caches
depending on URL, cookies, etc.
Q: Is Smarty faster than <insert other PHP template engine>?
A: See the benchmark page for some performance comparisons. Smarty's approach
to templates is a bit different from some languages: it compiles templates
into PHP scripts instead of parsing them on each invocation. This usually
results in great performance gains, especially with complex templates.
Coupled with the built-in caching of Smarty templates, the performance is
outstanding.
Q: How can I be sure to get the best performance from Smarty?
A: Be sure you set $compile_check=false once your templates are initially
compiled. This will skip the unneeded step of testing if the template has
changed since it was last compiled. If you have complex pages that don't
change too often, turn on the caching engine and adjust your application so
it doesn't do unnecessary work (like db calls) if a cached page is
available. See the documentation for examples.
Q: Do you have a mailing list?
A: We have a few mailing lists. "general" for you to share your ideas or ask
questions, "dev" for those interested in the development efforts of Smarty,
and "cvs" for those that would like to track the updates made in the cvs
repository.
send a blank e-mail message to:
smarty-general-subscribe@lists.php.net (subscribe to the general list)
smarty-general-unsubscribe@lists.php.net (unsubscribe from the general list)
smarty-general-digest-subscribe@lists.php.net (subscribe to digest)
smarty-general-digest-unsubscribe@lists.php.net (unsubscribe from digest)
smarty-dev-subscribe@lists.php.net (subscribe to the dev list)
smarty-dev-unsubscribe@lists.php.net (unsubscribe from the dev list)
smarty-cvs-subscribe@lists.php.net (subscribe to the cvs list)
smarty-cvs-unsubscribe@lists.php.net (unsubscribe from the cvs list)
You can also browse the mailing list archives at
http://marc.theaimsgroup.com/?l=smarty&r=1&w=2
Q: Can you change the mailing list so Reply-To sends to the list and not the
user?
A: Yes we could, but no we won't. Use "Reply-All" in your e-mail client to send
to the list. http://www.unicom.com/pw/reply-to-harmful.html
TROUBLESHOOTING
---------------
Q: Smarty doesn't work.
A: You must be using PHP 4.0.6 or later if you use any version of Smarty
past 2.0.1. Read the BUGS file for more info.
Q: I get the following error when running Smarty:
Warning: Smarty error: problem creating directory "templates_c/239/239105369"
in /path/to/Smarty.class.php on line 542
A: Your web server user does not have permission to write to the templates_c
directory, or is unable to create the templates_c directory. Be sure the
templates_c directory exists in the location defined in Smarty.class.php,
and the web server user can write to it. If you do not know the web server
user, chmod 777 the templates_c directory, reload the page, then check the
file ownership of the files created in templates_c. Or, you can check the
httpd.conf (usually in /usr/local/apache/conf) file for this setting:
User nobody
Group nobody
Q: I get the following error when running Smarty: Warning: Wrong parameter
count for preg_replace() in Smarty.class.php on line 371
A: preg_replace had a parameter added in PHP 4.0.2 that Smarty
requires. Upgrade to at least 4.0.6 to fix all known PHP issues with
Smarty.
Q: I get this error when passing variables to {include}:
Fatal error: Call to undefined function: get_defined_vars() in
/path/to/Smarty/templates_c/index.tpl.php on line 8
A: get_defined_vars() was added to PHP 4.0.4. If you plan on passing
variables to included templates, you will need PHP 4.0.6 or later.
Q: I get PHP errors in my {if} tag logic.
A: All conditional qualifiers must be separated by spaces. This syntax will not
work: {if $name=="Wilma"} You must instead do this: {if $name == "Wilma"}.
The reason for this is syntax ambiguity. Both "==" and "eq" are equivalent
in the template parser, so something like {if $nameeq"Wilma"} wouldn't be
parsable by the tokenizer.
Q: I'm changing my php code and/or templates, and my results are not getting
updated.
A: This may be the result of your compile or cache settings. If you are
changing your php code, your templates will not necessarily get recompiled
to reflect the changes. Use $force_compile during develpment to avoid these
situations. Also turn off caching during development when you aren't
specifically testing it. You can also remove everything from your
compile_dir and cache_dir and reload the page to be sure everything gets
regenerated.
Q: I'm running Windows 2000 and I get blank content. My compiled PHP files are
also zero length.
A: There seems to be a problem with some W2k machines and exclusive file
locking. Comment out the flock() call in _write_file to get around this,
although be aware this could possibly cause a problem with simultaneous
writes to a file, especially with caching turned on. NOTE: As of Smarty
1.4.0, a workaround was put in place that should solve this.
Q: The template goes into an infinite loop when I include included templates
that pass local variables
A: This was fixed in 1.3.2 (new global attribute)
Q: Javascript is causing Smarty errors in my templates.
A: Surround your javascript with {literal}{/literal} tags. See the docs.
Q: I get "SAFE MODE Restriction in effect. ..."-errors when running smarty.
A: Use $smarty->use_sub_dirs = false when running php in safe mode.
MISC
----
Q: Can I use Macromedia's Dreamweaver to edit my templates?
A: Certainly. You might want to change your tag delimiters from {} to something
that resembles valid HTML, like <!--{ }--> or <{ }> or something similar.
This way the editor won't view the template tags as errors.
Q: Dreamweaver is urlencoding the template delimiters when they are in a SRC or
HREF link. How do I get around this?
A: In Edit - Properties - Rewrite HTML you can specify if Dreamweaver should
change special letters to %-equivalent or not. The default is on which
produces this error.
HOWTO
-----
Q: How do I generate different cache files per template based on arguments
passed to the page?
A: Use your $REQUEST_URI as the cache_id when fetching the page:
global $REQUEST_URI; // if not already present
$smarty->display('index.tpl',$REQUEST_URI);
This will create a separate cache file for each unique URL when you call
index.tpl. See the documentation for display() and fetch()
Q: How do I pass a template variable as a parameter? {function param={$varname}}
does not work.
A: {function param=$varname} (You cannot nest template delimiters.)
Q: How do I include cached template(s) within a non-cached template?
A: One way to do it:
$smarty->caching = true;
$tpl1 = $smarty->fetch("internal1.tpl");
$tpl2 = $smarty->fetch("internal2.tpl");
$tpl3 = $smarty->fetch("internal3.tpl");
$smarty->assign("tpl1_contents",$tpl1);
$smarty->assign("tpl2_contents",$tpl2);
$smarty->assign("tpl3_contents",$tpl3);
$smarty->caching = false;
$smarty->display('index.tpl');
index.tpl
---------
<table>
<tr>
<td>{$tpl1_contents}</td>
<td>{$tpl2_contents}</td>
<td>{$tpl3_contents}</td>
</tr>
</table>
Another approach:
You could write a custom insert function to fetch your internal
templates:
<table>
<tr>
<td>{insert name=fetch_tpl tpl="internal1.tpl"}</td>
<td>{insert name=fetch_tpl tpl="internal2.tpl"}</td>
<td>{insert name=fetch_tpl tpl="internal3.tpl"}</td>
</tr>
</table>

View file

@ -0,0 +1,29 @@
REQUIREMENTS:
Smarty requires PHP 4.0.6 or later.
See the on-line documentation for complete install instructions.
INSTALLATION (quick):
* copy the files under the libs/ directory to a directory that is in your PHP
include_path, or set the SMARTY_DIR constant and put them in this directory.
(if you upgrade from versions before 2.5.0 be aware that up to Smarty 2.4.2
all necessary files where in the distribution's root directory, but are now
in libs/.)
* for each application using Smarty, create a "templates", "configs", and a
"templates_c" directory, be sure to set the appropriate directory settings in
Smarty for them. If they are located in the same directory as your
application, they shouldn't need to be modified. Be sure the "templates_c"
directory is writable by your web server user (usually nobody). chown
nobody:nobody templates_c; chmod 700 templates_c You can also chmod 777 this
directory, but be aware of security issues for multi-user systems. If you are
using Smarty's built-in caching, create a "cache" directory and also chown
nobody:nobody.
* setup your php and template files. A good working example is in the on-line
documentation.
* TECHNICAL NOTE: If you do not have access to the php.ini file, you can change
non-server settings (such as your include_path) with the ini_set() command.
example: ini_set("include_path",".:/usr/local/lib/php");

1024
classes/lib/external/Smarty-2.6.19/NEWS vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,103 @@
This is a simple guide to get Smarty setup and running quickly. The online
documentation includes a very thorough explanation of a Smarty installation.
This guide is meant to be a quick and painless way of getting Smarty working,
and nothing more. The guide assumes you are familiar with the UNIX system
environment. Windows users will need to make adjustments where necessary.
INSTALL SMARTY LIBRARY FILES
Copy the Smarty library files to your system. In our example, we place them in
/usr/local/lib/php/Smarty/
$> cd YOUR_DOWNLOAD_DIRECTORY
$> gtar -ztvf Smarty-2.6.7.tar.gz
$> mkdir /usr/local/lib/php/Smarty
$> cp -r Smarty-2.6.7/libs/* /usr/local/lib/php/Smarty
You should now have the following file structure:
/usr/local/lib/php/Smarty/
Config_File.class.php
debug.tpl
internals/
plugins/
Smarty.class.php
Smarty_Compiler.class.php
SETUP SMARTY DIRECTORIES
You will need four directories setup for Smarty to work. These files are for
templates, compiled templates, cached templates and config files. You may or
may not use caching or config files, but it is a good idea to set them up
anyways. It is also recommended to place them outside of the web server
document root. The web server PHP user will need write access to the cache and
compile directories as well.
In our example, the document root is /web/www.domain.com/docs and the
web server username is "nobody". We will keep our Smarty files under
/web/www.domain.com/smarty
$> cd /web/www.domain.com
$> mkdir smarty
$> mkdir smarty/templates
$> mkdir smarty/templates_c
$> mkdir smarty/cache
$> mkdir smarty/configs
$> chown nobody:nobody smarty/templates_c
$> chown nobody:nobody smarty/cache
$> chmod 775 smarty/templates_c
$> chmod 775 smarty/cache
SETUP SMARTY PHP SCRIPTS
Now we setup our application in the document root:
$> cd /web/www.domain.com/docs
$> mkdir myapp
$> cd myapp
$> vi index.php
Edit the index.php file to look like the following:
<?php
// put full path to Smarty.class.php
require('/usr/local/lib/php/Smarty/Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = '/web/www.domain.com/smarty/templates';
$smarty->compile_dir = '/web/www.domain.com/smarty/templates_c';
$smarty->cache_dir = '/web/www.domain.com/smarty/cache';
$smarty->config_dir = '/web/www.domain.com/smarty/configs';
$smarty->assign('name', 'Ned');
$smarty->display('index.tpl');
?>
SETUP SMARTY TEMPLATE
$> vi /web/www.domain.com/smarty/templates/index.tpl
Edit the index.tpl file with the following:
<html>
<head>
<title>Smarty</title>
</head>
<body>
Hello, {$name}!
</body>
</html>
Now go to your new application through the web browser,
http://www.domain.com/myapp/index.php in our example. You should see the text
"Hello Ned!" in your browser.
Once you get this far, you can continue on to the Smarty Crash Course to learn
a few more simple things, or on to the documentation to learn it all.

View file

@ -0,0 +1,85 @@
NAME:
Smarty - the PHP compiling template engine
VERSION: 2.6.19
AUTHORS:
Monte Ohrt <monte at ohrt dot com>
Andrei Zmievski <andrei@php.net>
MAILING LISTS:
We have a few mailing lists. "discussion" for you to share your ideas or ask
questions, "developers" for those interested in the development efforts of Smarty,
and "svn" for those that would like to track the updates made in the svn
repository.
send a blank e-mail message to:
smarty-discussion-subscribe@googlecode.com(subscribe to the general discussion list)
smarty-discussion-unsubscribe@googlecode.com (unsubscribe from the general discussion list)
smarty-discussion-digest-subscribe@googlecode.com (subscribe to digest)
smarty-discussion-digest-unsubscribe@googlecode.com (unsubscribe from digest)
smarty-developers-subscribe@googlecode.com (subscribe to the dev list)
smarty-developers-unsubscribe@googlecode.com (unsubscribe from the dev list)
smarty-svn-subscribe@googlecode.com (subscribe to the svn list)
smarty-svn-unsubscribe@googlecode.com (unsubscribe from the svn list)
You can also browse the mailing list archives at
http://groups.google.com/group/smarty-discussion
http://groups.google.com/group/smarty-developers
and the OLD list archives at
http://marc.theaimsgroup.com/?l=smarty&r=1&w=2
SYNOPSIS:
require("Smarty.class.php");
$smarty = new Smarty;
$smarty->assign("Title","My Homepage");
$smarty->assign("Names",array("John","Gary","Gregg","James"));
$smarty->display("index.tpl");
DESCRIPTION:
What is Smarty?
Smarty is a template engine for PHP. Many other template engines for PHP
provide basic variable substitution and dynamic block functionality.
Smarty takes a step further to be a "smart" template engine, adding
features such as configuration files, template functions, and variable
modifiers, and making all of this functionality as easy as possible to
use for both programmers and template designers. Smarty also converts
the templates into PHP scripts, eliminating the need to parse the
templates on every invocation. This makes Smarty extremely scalable and
manageable for large application needs.
Some of Smarty's features:
* it is extremely fast
* no template parsing overhead, only compiles once.
* it is smart about recompiling only the template files that have
changed.
* the template language is remarkably extensible via the plugin
architecture.
* configurable template delimiter tag syntax, so you can use
{}, {{}}, <!--{}-->, or whatever you like.
* built-in caching of template output.
* arbitrary template sources (filesystem, databases, etc.)
* template if/elseif/else/endif constructs are passed to the PHP parser,
so the if syntax can be as simple or as complex as you like.
* unlimited nesting of sections, conditionals, etc. allowed
* it is possible to embed PHP code right in your template files,
although not recommended and doubtfully needed since the engine
is so customizable.
* and many more.
COPYRIGHT:
Copyright (c) 2001-2005 New Digital Group, Inc. All rights reserved.
This software is released under the GNU Lesser General Public License.
Please read the disclaimer at the top of the Smarty.class.php file.

View file

@ -0,0 +1,428 @@
2.6.7
-----
Those using Smarty with security enabled: a hole was found that allowed PHP code to be executed from within a template file. This has been fixed and you are engouraged to upgrade immediately. Note that this hole does NOT affect the security of your web server or PHP applications, only the ability for someone editing a template to execute PHP code. Other changes in this release can be found in the NEWS file.
2.5.0
-----
Very minor adjustments since RC2, see the NEWS file for details.
2.5.0-RC2
---------
Many fixes since the RC1 release. This one is as close to production quality as
they come, so this will be the last release before 2.5.0. The SGML documentation
files have also been removed from the tarball. If you want them, get them from
the CVS repository.
2.5.0-RC1
---------
Release Candidate 1. All $smarty vars can now be dynamic, such as
$smarty.get.$foo. A new class function get_function_object() gets you a
reference to an assigned object, useful within your own custom functions.
append() can now merge as well as append with a third optional attribute. A new
class function get_config_vars() was added, and get_template_vars() can now be
used to get individual vars. Full variable syntax is now supported within
double quotes via a backtick (`) syntax. Files created by smarty are now
written to a tmp file then renamed to avoid file lock retention. html_radios,
html_checkboxes, html_table, html_image, nl2br functions added, see the NEWS
file for full details.
2.4.2
-----
Another point release. Added support for dynamic object reference syntax
($foo->$bar), support for full variable syntax within quotes ("$foo[0].bar"),
and other minor fixes. See the NEWS file for full details.
2.4.1
-----
This is basically a point release, cleaning up a few things caught
in the 2.4.0 release. See the NEWS file for full details.
2.4.0
-----
Smarty now supports the ability to access objects within the templates. Two
methods are available, one which closely follows Smartys conventions, and
another that follows more traditional object syntax for those familiar with
PHP.
The internal compiling engine has also undergone some major work. The regex
parsing was rewritten to be much more strict, more secure and more
maintainable. Config files are now compiled, which can speed up pages quite a
bit that use config files extensively. Assigned variables are no longer
extracted to PHP namespace, saving an extract call for every template. There is
now support for applying modifiers to static values and functions. You can now
access constants with $smarty.const.VAR. See the NEWS file for complete
changes.
2.3.1
-----
The mtime on compiled files will now match the source files, in the case where
the source file may not get the current timestamp, recompiling will still work
as expected. Proper support for open_basedir has been added, so Smarty should
work correctly in safe mode. Added a few new features such as textformat block
function, strip variable modifier and optgroup support for html_options. Also
other minor bug fixes, see the Change Log.
2.3.0
-----
Smarty now has a {debug} template function that brings up the debugging console
right where {debug} is called, regardless of $debugging settings. This works a
little different than turning on $debugging in the sense that it shows all the
template variables available at the time {debug} is called, including local
scope vars. It does not show the templates names however, since this
executed during runtime of the template.
You can now supply an expire time when clearing cache or compile files. This is
mostly useful for removing stale files via the API.
Plugins now stop execution upon error, instead of outputting a warning and
continuing.
Two new API functions, assign_by_ref() and append_by_ref() were added. They
allow assigning template variables by reference. This can make a significant
performance gain, especially if you are assigning large arrays of data. PHP 5.0
will do this implicitly, so these functions are basically workarounds.
Several misc bug fixes, see the Change Log for information.
2.2.0
-----
Smarty now allows an array of paths for the $plugin_dir class variable. The
directories will be searched in the order they are given, so for efficiency keep
the most-used plugins at the top. Also, absolute paths to the plugin directories are
more efficient than relying on the PHP include_path.
Cache files can now be grouped with the cache_id. See the documentation under
the new "Caching" section for details. compile_id also respects the same
grouping syntax. The cache/compile file structure changed, so be sure to clear
out all your cache and compile files when upgrading Smarty. Also if you are
using PHP-accelerator, restart apache. I've seen some quirky things happen if
the phpa files do not get cleared (known issue with phpa and parent
class-member changes, so just clear 'em.)
Smarty now correctly respects the PHP include_path for $template_dir, $compile_dir,
$cache_dir, $config_dir and $plugin_dir. Be aware that relying on the
include_path is an overhead, try to use absolute pathnames when possible
(or relative to working directory.)
Documentation has been updated and rearranged a bit. Most notably, the
installation instructions are completely revamped, and a new Caching section
explains Smarty's caching in detail along with the new grouping functionality.
Many misc. bug fixes and enhancements, see the full ChangeLog (NEWS file) for
details.
2.1.1
-----
There was a bug with template paths and the include_path, this has been fixed.
Also register_outputfilter() did not work, this is fixed. A new template
function named "cycle" has been added to the distribution, nice for cycling
through a list (or array) of values.
2.1.0
-----
This release has quite a few new features and fixes. Most notable are the
introduction of block functions, so you can write plugins that work on a block
of text with {func}{/func} notation. Also output filters were added, so you can
apply a function against the output of your templates. This differs from the
postfilter function, which works on the compiled template at compile time, and
output filters work on the template output at runtime.
Many other features and bug fixes are noted in the NEWS file.
2.0.1
-----
This is a point release, fixing a few bugs and cleaning things up. A plugin
was renamed, the dash "-" was removed from compiled template and cached file
names. If you're upgrading, you might want to clear them out first. See the
ChangeLog for details.
2.0.0
-----
This release is a huge milestone for Smarty. Most notable new things are a
plugin architecture, removal of PEAR dependency, and optimizations that
drastically improve the performance of Smarty in most cases.
The plugin architecture allows modifiers, custom functions, compiler functions,
prefilters, postfilters, resources, and insert functions to be added by
simply dropping a file into the plugins directory. Once dropped in, they are
automatically registered by the template engine. This makes user-contributed
plugins easy to manage, as well as the internal workings of Smarty easy to
control and customize. This new architecture depends on the __FILE__ constant,
which contains the full path to the executing script. Some older versions of
PHP incorrectly gave the script name and not the full filesystem path. Be sure
your version of PHP populates __FILE__ correctly. If you use custom template
resource functions, the format of these changed with the plugin architecture.
Be sure to update your functions accordingly. See the template resource section
of the documentation.
The PEAR dependancy was removed from Smarty. The Config_File class that comes
with Smarty was actually what needed PEAR for error handling which Smarty didn't
use, but now everything is self-contained.
Performance improvements are graphed on the benchmark page, you will see that
overall performance has been sped up by as much as 80% in some cases.
Smarty-cached pages now support If-Modified-Since headers, meaning that if a
cached template page has not changed since the last request, a "304 Not
Modified" header will be sent instead of resending the same page. This is
disabled by default, change the setting of $cache_modified_check.
1.5.2
-----
Mostly bug fixes, added a default template resource handler.
1.5.1
-----
Critical bug fix release. If you use caching, you'll need to upgrade.
1.5.0
-----
Several feature enhancements were made to this version, most notably the
{foreach ...} command which is an alternative to {section ...} with an easier
syntax for looping through a single array of values. Several functions were
enhanced so that the output can be automatically assigned to a template
variable instead of displayed (assign attribute). Cache files can now be
controlled with a custom function as an alternative to the built-in file based
method. Many code cleanups and bug fixed went into this release as well.
1.4.6
-----
The behavior with caching and compile_check has been slightly enhanced. If
caching is enabled AND compile_check is enabled, the cache will immediately get
regenerated if _any_ involved template or config file is updated. This imposes
a slight performance hit because it must check all the files for changes, so be
sure to run live sites with caching enabled and compile_check disabled for best
performance. If you update a template or config file, simply turn on
compile_check, load the page, then turn it back off. This will update the cache
file with the new content. This is accomplished by maintaining a list of
included/loaded templates and config files at the beginning of the cache file.
Therefore it is advisable to remove all cache files after upgrading to 1.4.6
(although not absolutely necessary, old cache files will regenerate)
The debug console now has script timing and array values printed. You MUST
update your debug.tpl file with this version of Smarty. Also, the new debug.tpl
will not work with older versions of Smarty.
1.4.5
-----
Mostly bug fixes and minor improvements. Added compile id for separate compiled
versions of the same script. The directory format and filename convention for
the files in templates_c has changed, so you may want to remove all of the
existing ones before you upgrade.
1.4.4
-----
A few bug fixes, new section looping attributes and properties, debugging
console function for control via URL, and overLib integration and access
to request variables from within the template.
1.4.3
-----
This release has a few bug fixes and several enhancements. Smarty now supports
template security for third-party template editing. These features disallow the
ability for someone to execute commands or PHP code from the template language.
Smarty also now has a built-in debugging console, which is a javascript pop-up
window that displays all the included template names and assigned variables.
1.4.2
-----
This was mostly one bug fix with variable scoping within included templates
and a few documentation changes and updates. See the ChangeLog file for full
details.
1.4.1
-----
It seems that the EX_LOCK logic from the previous release didn't fix all the
problems with windows platforms. Hopefully this one does. It basically
disables file locking on windows, so there is a potential that two programs
could write over the same file at the same time, fyi.
The reset is minor bug fixes, please refer to the ChangeLog file.
1.4.0
-----
IMPORTANT NOTICE
Smarty now has a new syntax for accessing elements within section loops. The
new syntax is easier to use and nicely handles data structures of any
complexity. Consequently, this breaks the old syntax.
Here is an example of the syntax change:
old syntax:
{$sec1/sec2/sec3/customer.phone}
new syntax:
{$customer[$sec1][$sec2][$sec3].phone}
The section names used to come first, followed by the variable name. Now the
variable name always comes first, followed by the section names in brackets.
You can access variable indexes anywhere, depending on how you passed the
variables in.
To fix your current templates, we have provided a script that will adjust the
syntax for you. Located in misc/fix_vars.php, run this script from the the
command line, giving each template as an argument. Be sure to use absolute
pathnames, or pathnames relative to the executing script. Probably the easiest
way to do this is to copy the fix_vars.php script into your template directory
and run 'php -q fix_vars.php *.tpl' Be sure you have proper write permission,
and backup your scripts first to be safe! The examples in the 1.4.0
documentation have been updated to reflect the changes.
cd /path/to/templates
cp /path/to/fix_vars.php .
find . -name "*.tpl" -exec php -q ./fix_vars.php {} \;
NEW AND IMPROVED COMPILATION PROCESS
Smarty 1.4.0 also has a new compilation process. Instead of compiling all the
templates up front, it now compiles them at runtime. This has several
advantages. First of all, there is no longer a need to have a single template
directory. You can now have arbitrary template sources, such as multiple
directories or even database calls. This also speeds the performance of Smarty
when $compile_check is enabled, since it is only checking the template that is
being executed instead of everything found in the template directory. The
$tpl_file_ext is no longer needed, but kept for backward compatability.
Templates can now be named anything you like with any extension.
MINOR FIXES
A workaround for LOCK_EX on Windows systems was added, and changed a couple of
file permissions for better security on public servers.
$show_info_header is now defaulted to false instead of true. This header causes
problems when displaying content other than HTML, so now you must explicitly
set this flag to true to show the header information (or change the default in
your copy of Smarty.)
Documentation is written in docbook format. I updated the docbook -> HTML
generating software & style-sheets, and consequently the examples are no longer
in a different background color. If anyone wants to contribute a better
stylesheet or help with documentation, drop me a line. <monte at ohrt dot com>
CHANGES/ENHANCEMENTS/UPDATES
date_format, html_select_date and html_select_time used to require a unix
timestamp as the format of the date passed into the template. Smarty is now a
bit smarter at this. It will take a unix timestamp, a mysql timestamp, or any
date string that is parsable by strtotime, such as 10/01/2001 or 2001-10-01,
etc. Just give some formats a try and see what works.
Smarty now has template prefilters, meaning that you can run your templates
through custom functions before they are compiled. This is good for things like
removing unwanted comments, keeping an eye on words or functionality people are
putting in templates, translating XML -> HTML, etc. See the register_prefilter
documentation for more info.
Another addition are the so-called compiler functions. These are custom
functions registered by the user that are executed at compilation time of the
template. They can be used to inject PHP code or time-sensitive static content
into the compiled template.
The run-time custom functions are now passed the Smarty object as the second
parameter. This can be used, for example, to assign or clear template variables
from inside the custom function.
clear_compile_dir() was added for clearing out compiled versions of your
templates. Not something normally needed, but you may have a need for this if
you have $compile_check set to false and you periodically update templates via
some automated process. As of 1.4.0, uncompiled templates _always_ get
compiled regardless of $compile_check setting, although they won't be checked
for recompile if $compile_check is set to false.
You can now refer to properties of objects assigned from PHP by using the '->'
symbol and specifying the property name after it, e.g. $foo->bar.
{php}{/php} tags were added to embed php into the templates. Not normally
needed, but some circumstances may call for it. Check out the "componentized
templates" tip in the documentation for an example.
{capture}{/capture} and {counter} functions were added. See the documentation
for a complete description and examples.
UPGRADE NOTES
The format of the files created in the $compile_dir are now a bit different.
The compiled template filename is the template resource name url-encoded.
Therefore, all compiled files are now in the top directory of $compile_dir.
This was done to make way for arbitrary template resources. Each compiled
template also has a header that states what template resource was used to
create it. From a unix command prompt, you can use "head -2 *" to see the first
two lines of each file.
When upgrading to 1.4.0, you will want to clear out all your old files in the
$compile_dir. If you have $compile_check set to false and the compiled template
does not yet exist, it will compile it regardless of this setting. This way you
can clear out the $compile_dir and not worry about setting $compile_check to
true to get the inital compilation under way.
1.3.2
-----
Smarty now has (an optional) header prepended to the output of the Smarty
templates. This displays the Smarty version and the date/time when the page was
generated. This is useful for debugging your cache routines, and purely
informational so there is evidence that the page was generated by Smarty. Set
$show_info_header to false to disable it.
{config_load ...} performance was tuned by placing the loaded variables into a
global array, so basically a config file is read from the file system and
placed into a php array structure only once, no matter how many times it is
called in any of the templates. The scope of the loaded variables has changed a
bit as well. Variables loaded by config_load used to be treated as global
variables, meaning that parent templates (templates that included the current
template) could see them. Now the default behavior is such that loaded
variables are only visible by the current template and child templates (all
templates included after the {config_load ...} is called.) To mimic the
original behavior, provide the attribute "global=yes" like so: {config_load
file="mystuff.conf" global=yes}. Now when you load in mystuff.conf, the
variables will be visible to parent templates (merged with any existing config
variables.)
A formatting attribute was added to the {math ...} function, adding the ability
to control the format of the output. Use the same formatting syntax as the PHP
function sprintf().
{html_select_time ...} was added, a custom function that works much like
{html_select_date ...} except it displays time elements instead of dates.
A few custom modifiers were added: count_characters, count_words,
count_sentences, count_paragraphs. All pretty self-explanatory.
/* vim: set et: */

10
classes/lib/external/Smarty-2.6.19/TODO vendored Normal file
View file

@ -0,0 +1,10 @@
* handle asp style tags in $php_handler
* fix all E_NOTICE warnings
* make simple math easier
* caching all but parts of the template
* change plugins so $smarty variable always comes first
* get cache ttl with function call
FIX: make inserts use normal functions before plugins
UPD: change it so that if template comes from some resource,
that resource stays as the default, no need to specify it
in includes.

View file

@ -0,0 +1,5 @@
title = Welcome to Smarty!
cutoff_size = 40
[setup]
bold = true

View file

@ -0,0 +1,25 @@
<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty;
$smarty->compile_check = true;
$smarty->debugging = true;
$smarty->assign("Name","Fred Irving Johnathan Bradley Peppergill");
$smarty->assign("FirstName",array("John","Mary","James","Henry"));
$smarty->assign("LastName",array("Doe","Smith","Johnson","Case"));
$smarty->assign("Class",array(array("A","B","C","D"), array("E", "F", "G", "H"),
array("I", "J", "K", "L"), array("M", "N", "O", "P")));
$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));
$smarty->assign("option_values", array("NY","NE","KS","IA","OK","TX"));
$smarty->assign("option_output", array("New York","Nebraska","Kansas","Iowa","Oklahoma","Texas"));
$smarty->assign("option_selected", "NE");
$smarty->display('index.tpl');
?>

View file

@ -0,0 +1,2 @@
</BODY>
</HTML>

View file

@ -0,0 +1,6 @@
<HTML>
<HEAD>
{popup_init src="/javascripts/overlib.js"}
<TITLE>{$title} - {$Name}</TITLE>
</HEAD>
<BODY bgcolor="#ffffff">

View file

@ -0,0 +1,81 @@
{config_load file=test.conf section="setup"}
{include file="header.tpl" title=foo}
<PRE>
{* bold and title are read from the config file *}
{if #bold#}<b>{/if}
{* capitalize the first letters of each word of the title *}
Title: {#title#|capitalize}
{if #bold#}</b>{/if}
The current date and time is {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}
The value of global assigned variable $SCRIPT_NAME is {$SCRIPT_NAME}
Example of accessing server environment variable SERVER_NAME: {$smarty.server.SERVER_NAME}
The value of {ldelim}$Name{rdelim} is <b>{$Name}</b>
variable modifier example of {ldelim}$Name|upper{rdelim}
<b>{$Name|upper}</b>
An example of a section loop:
{section name=outer loop=$FirstName}
{if $smarty.section.outer.index is odd by 2}
{$smarty.section.outer.rownum} . {$FirstName[outer]} {$LastName[outer]}
{else}
{$smarty.section.outer.rownum} * {$FirstName[outer]} {$LastName[outer]}
{/if}
{sectionelse}
none
{/section}
An example of section looped key values:
{section name=sec1 loop=$contacts}
phone: {$contacts[sec1].phone}<br>
fax: {$contacts[sec1].fax}<br>
cell: {$contacts[sec1].cell}<br>
{/section}
<p>
testing strip tags
{strip}
<table border=0>
<tr>
<td>
<A HREF="{$SCRIPT_NAME}">
<font color="red">This is a test </font>
</A>
</td>
</tr>
</table>
{/strip}
</PRE>
This is an example of the html_select_date function:
<form>
{html_select_date start_year=1998 end_year=2010}
</form>
This is an example of the html_select_time function:
<form>
{html_select_time use_24_hours=false}
</form>
This is an example of the html_options function:
<form>
<select name=states>
{html_options values=$option_values selected=$option_selected output=$option_output}
</select>
</form>
{include file="footer.tpl"}

View file

@ -0,0 +1,389 @@
<?php
/**
* Config_File class.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @link http://smarty.php.net/
* @version 2.6.19
* @copyright Copyright: 2001-2005 New Digital Group, Inc.
* @author Andrei Zmievski <andrei@php.net>
* @access public
* @package Smarty
*/
/* $Id: Config_File.class.php 2702 2007-03-08 19:11:22Z mohrt $ */
/**
* Config file reading class
* @package Smarty
*/
class Config_File {
/**#@+
* Options
* @var boolean
*/
/**
* Controls whether variables with the same name overwrite each other.
*/
var $overwrite = true;
/**
* Controls whether config values of on/true/yes and off/false/no get
* converted to boolean values automatically.
*/
var $booleanize = true;
/**
* Controls whether hidden config sections/vars are read from the file.
*/
var $read_hidden = true;
/**
* Controls whether or not to fix mac or dos formatted newlines.
* If set to true, \r or \r\n will be changed to \n.
*/
var $fix_newlines = true;
/**#@-*/
/** @access private */
var $_config_path = "";
var $_config_data = array();
/**#@-*/
/**
* Constructs a new config file class.
*
* @param string $config_path (optional) path to the config files
*/
function Config_File($config_path = NULL)
{
if (isset($config_path))
$this->set_path($config_path);
}
/**
* Set the path where configuration files can be found.
*
* @param string $config_path path to the config files
*/
function set_path($config_path)
{
if (!empty($config_path)) {
if (!is_string($config_path) || !file_exists($config_path) || !is_dir($config_path)) {
$this->_trigger_error_msg("Bad config file path '$config_path'");
return;
}
if(substr($config_path, -1) != DIRECTORY_SEPARATOR) {
$config_path .= DIRECTORY_SEPARATOR;
}
$this->_config_path = $config_path;
}
}
/**
* Retrieves config info based on the file, section, and variable name.
*
* @param string $file_name config file to get info for
* @param string $section_name (optional) section to get info for
* @param string $var_name (optional) variable to get info for
* @return string|array a value or array of values
*/
function get($file_name, $section_name = NULL, $var_name = NULL)
{
if (empty($file_name)) {
$this->_trigger_error_msg('Empty config file name');
return;
} else {
$file_name = $this->_config_path . $file_name;
if (!isset($this->_config_data[$file_name]))
$this->load_file($file_name, false);
}
if (!empty($var_name)) {
if (empty($section_name)) {
return $this->_config_data[$file_name]["vars"][$var_name];
} else {
if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name]))
return $this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name];
else
return array();
}
} else {
if (empty($section_name)) {
return (array)$this->_config_data[$file_name]["vars"];
} else {
if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"]))
return (array)$this->_config_data[$file_name]["sections"][$section_name]["vars"];
else
return array();
}
}
}
/**
* Retrieves config info based on the key.
*
* @param $file_name string config key (filename/section/var)
* @return string|array same as get()
* @uses get() retrieves information from config file and returns it
*/
function &get_key($config_key)
{
list($file_name, $section_name, $var_name) = explode('/', $config_key, 3);
$result = &$this->get($file_name, $section_name, $var_name);
return $result;
}
/**
* Get all loaded config file names.
*
* @return array an array of loaded config file names
*/
function get_file_names()
{
return array_keys($this->_config_data);
}
/**
* Get all section names from a loaded file.
*
* @param string $file_name config file to get section names from
* @return array an array of section names from the specified file
*/
function get_section_names($file_name)
{
$file_name = $this->_config_path . $file_name;
if (!isset($this->_config_data[$file_name])) {
$this->_trigger_error_msg("Unknown config file '$file_name'");
return;
}
return array_keys($this->_config_data[$file_name]["sections"]);
}
/**
* Get all global or section variable names.
*
* @param string $file_name config file to get info for
* @param string $section_name (optional) section to get info for
* @return array an array of variables names from the specified file/section
*/
function get_var_names($file_name, $section = NULL)
{
if (empty($file_name)) {
$this->_trigger_error_msg('Empty config file name');
return;
} else if (!isset($this->_config_data[$file_name])) {
$this->_trigger_error_msg("Unknown config file '$file_name'");
return;
}
if (empty($section))
return array_keys($this->_config_data[$file_name]["vars"]);
else
return array_keys($this->_config_data[$file_name]["sections"][$section]["vars"]);
}
/**
* Clear loaded config data for a certain file or all files.
*
* @param string $file_name file to clear config data for
*/
function clear($file_name = NULL)
{
if ($file_name === NULL)
$this->_config_data = array();
else if (isset($this->_config_data[$file_name]))
$this->_config_data[$file_name] = array();
}
/**
* Load a configuration file manually.
*
* @param string $file_name file name to load
* @param boolean $prepend_path whether current config path should be
* prepended to the filename
*/
function load_file($file_name, $prepend_path = true)
{
if ($prepend_path && $this->_config_path != "")
$config_file = $this->_config_path . $file_name;
else
$config_file = $file_name;
ini_set('track_errors', true);
$fp = @fopen($config_file, "r");
if (!is_resource($fp)) {
$this->_trigger_error_msg("Could not open config file '$config_file'");
return false;
}
$contents = ($size = filesize($config_file)) ? fread($fp, $size) : '';
fclose($fp);
$this->_config_data[$config_file] = $this->parse_contents($contents);
return true;
}
/**
* Store the contents of a file manually.
*
* @param string $config_file file name of the related contents
* @param string $contents the file-contents to parse
*/
function set_file_contents($config_file, $contents)
{
$this->_config_data[$config_file] = $this->parse_contents($contents);
return true;
}
/**
* parse the source of a configuration file manually.
*
* @param string $contents the file-contents to parse
*/
function parse_contents($contents)
{
if($this->fix_newlines) {
// fix mac/dos formatted newlines
$contents = preg_replace('!\r\n?!', "\n", $contents);
}
$config_data = array();
$config_data['sections'] = array();
$config_data['vars'] = array();
/* reference to fill with data */
$vars =& $config_data['vars'];
/* parse file line by line */
preg_match_all('!^.*\r?\n?!m', $contents, $match);
$lines = $match[0];
for ($i=0, $count=count($lines); $i<$count; $i++) {
$line = $lines[$i];
if (empty($line)) continue;
if ( substr($line, 0, 1) == '[' && preg_match('!^\[(.*?)\]!', $line, $match) ) {
/* section found */
if (substr($match[1], 0, 1) == '.') {
/* hidden section */
if ($this->read_hidden) {
$section_name = substr($match[1], 1);
} else {
/* break reference to $vars to ignore hidden section */
unset($vars);
$vars = array();
continue;
}
} else {
$section_name = $match[1];
}
if (!isset($config_data['sections'][$section_name]))
$config_data['sections'][$section_name] = array('vars' => array());
$vars =& $config_data['sections'][$section_name]['vars'];
continue;
}
if (preg_match('/^\s*(\.?\w+)\s*=\s*(.*)/s', $line, $match)) {
/* variable found */
$var_name = rtrim($match[1]);
if (strpos($match[2], '"""') === 0) {
/* handle multiline-value */
$lines[$i] = substr($match[2], 3);
$var_value = '';
while ($i<$count) {
if (($pos = strpos($lines[$i], '"""')) === false) {
$var_value .= $lines[$i++];
} else {
/* end of multiline-value */
$var_value .= substr($lines[$i], 0, $pos);
break;
}
}
$booleanize = false;
} else {
/* handle simple value */
$var_value = preg_replace('/^([\'"])(.*)\1$/', '\2', rtrim($match[2]));
$booleanize = $this->booleanize;
}
$this->_set_config_var($vars, $var_name, $var_value, $booleanize);
}
/* else unparsable line / means it is a comment / means ignore it */
}
return $config_data;
}
/**#@+ @access private */
/**
* @param array &$container
* @param string $var_name
* @param mixed $var_value
* @param boolean $booleanize determines whether $var_value is converted to
* to true/false
*/
function _set_config_var(&$container, $var_name, $var_value, $booleanize)
{
if (substr($var_name, 0, 1) == '.') {
if (!$this->read_hidden)
return;
else
$var_name = substr($var_name, 1);
}
if (!preg_match("/^[a-zA-Z_]\w*$/", $var_name)) {
$this->_trigger_error_msg("Bad variable name '$var_name'");
return;
}
if ($booleanize) {
if (preg_match("/^(on|true|yes)$/i", $var_value))
$var_value = true;
else if (preg_match("/^(off|false|no)$/i", $var_value))
$var_value = false;
}
if (!isset($container[$var_name]) || $this->overwrite)
$container[$var_name] = $var_value;
else {
settype($container[$var_name], 'array');
$container[$var_name][] = $var_value;
}
}
/**
* @uses trigger_error() creates a PHP warning/error
* @param string $error_msg
* @param integer $error_type one of
*/
function _trigger_error_msg($error_msg, $error_type = E_USER_WARNING)
{
trigger_error("Config_File error: $error_msg", $error_type);
}
/**#@-*/
}
?>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,157 @@
{* Smarty *}
{* debug.tpl, last updated version 2.1.0 *}
{assign_debug_info}
{capture assign=debug_output}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Smarty Debug Console</title>
{literal}
<style type="text/css">
/* <![CDATA[ */
body, h1, h2, td, th, p {
font-family: sans-serif;
font-weight: normal;
font-size: 0.9em;
margin: 1px;
padding: 0;
}
h1 {
margin: 0;
text-align: left;
padding: 2px;
background-color: #f0c040;
color: black;
font-weight: bold;
font-size: 1.2em;
}
h2 {
background-color: #9B410E;
color: white;
text-align: left;
font-weight: bold;
padding: 2px;
border-top: 1px solid black;
}
body {
background: black;
}
p, table, div {
background: #f0ead8;
}
p {
margin: 0;
font-style: italic;
text-align: center;
}
table {
width: 100%;
}
th, td {
font-family: monospace;
vertical-align: top;
text-align: left;
width: 50%;
}
td {
color: green;
}
.odd {
background-color: #eeeeee;
}
.even {
background-color: #fafafa;
}
.exectime {
font-size: 0.8em;
font-style: italic;
}
#table_assigned_vars th {
color: blue;
}
#table_config_vars th {
color: maroon;
}
/* ]]> */
</style>
{/literal}
</head>
<body>
<h1>Smarty Debug Console</h1>
<h2>included templates &amp; config files (load time in seconds)</h2>
<div>
{section name=templates loop=$_debug_tpls}
{section name=indent loop=$_debug_tpls[templates].depth}&nbsp;&nbsp;&nbsp;{/section}
<font color={if $_debug_tpls[templates].type eq "template"}brown{elseif $_debug_tpls[templates].type eq "insert"}black{else}green{/if}>
{$_debug_tpls[templates].filename|escape:html}</font>
{if isset($_debug_tpls[templates].exec_time)}
<span class="exectime">
({$_debug_tpls[templates].exec_time|string_format:"%.5f"})
{if %templates.index% eq 0}(total){/if}
</span>
{/if}
<br />
{sectionelse}
<p>no templates included</p>
{/section}
</div>
<h2>assigned template variables</h2>
<table id="table_assigned_vars">
{section name=vars loop=$_debug_keys}
<tr class="{cycle values="odd,even"}">
<th>{ldelim}${$_debug_keys[vars]|escape:'html'}{rdelim}</th>
<td>{$_debug_vals[vars]|@debug_print_var}</td></tr>
{sectionelse}
<tr><td><p>no template variables assigned</p></td></tr>
{/section}
</table>
<h2>assigned config file variables (outer template scope)</h2>
<table id="table_config_vars">
{section name=config_vars loop=$_debug_config_keys}
<tr class="{cycle values="odd,even"}">
<th>{ldelim}#{$_debug_config_keys[config_vars]|escape:'html'}#{rdelim}</th>
<td>{$_debug_config_vals[config_vars]|@debug_print_var}</td></tr>
{sectionelse}
<tr><td><p>no config vars assigned</p></td></tr>
{/section}
</table>
</body>
</html>
{/capture}
{if isset($_smarty_debug_output) and $_smarty_debug_output eq "html"}
{$debug_output}
{else}
<script type="text/javascript">
// <![CDATA[
if ( self.name == '' ) {ldelim}
var title = 'Console';
{rdelim}
else {ldelim}
var title = 'Console_' + self.name;
{rdelim}
_smarty_console = window.open("",title.value,"width=680,height=600,resizable,scrollbars=yes");
_smarty_console.document.write('{$debug_output|escape:'javascript'}');
_smarty_console.document.close();
// ]]>
</script>
{/if}

View file

@ -0,0 +1,67 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* assemble filepath of requested plugin
*
* @param string $type
* @param string $name
* @return string|false
*/
function smarty_core_assemble_plugin_filepath($params, &$smarty)
{
static $_filepaths_cache = array();
$_plugin_filename = $params['type'] . '.' . $params['name'] . '.php';
if (isset($_filepaths_cache[$_plugin_filename])) {
return $_filepaths_cache[$_plugin_filename];
}
$_return = false;
foreach ((array)$smarty->plugins_dir as $_plugin_dir) {
$_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename;
// see if path is relative
if (!preg_match("/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/", $_plugin_dir)) {
$_relative_paths[] = $_plugin_dir;
// relative path, see if it is in the SMARTY_DIR
if (@is_readable(SMARTY_DIR . $_plugin_filepath)) {
$_return = SMARTY_DIR . $_plugin_filepath;
break;
}
}
// try relative to cwd (or absolute)
if (@is_readable($_plugin_filepath)) {
$_return = $_plugin_filepath;
break;
}
}
if($_return === false) {
// still not found, try PHP include_path
if(isset($_relative_paths)) {
foreach ((array)$_relative_paths as $_plugin_dir) {
$_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename;
$_params = array('file_path' => $_plugin_filepath);
require_once(SMARTY_CORE_DIR . 'core.get_include_path.php');
if(smarty_core_get_include_path($_params, $smarty)) {
$_return = $_params['new_file_path'];
break;
}
}
}
}
$_filepaths_cache[$_plugin_filename] = $_return;
return $_return;
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,43 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty assign_smarty_interface core plugin
*
* Type: core<br>
* Name: assign_smarty_interface<br>
* Purpose: assign the $smarty interface variable
* @param array Format: null
* @param Smarty
*/
function smarty_core_assign_smarty_interface($params, &$smarty)
{
if (isset($smarty->_smarty_vars) && isset($smarty->_smarty_vars['request'])) {
return;
}
$_globals_map = array('g' => 'HTTP_GET_VARS',
'p' => 'HTTP_POST_VARS',
'c' => 'HTTP_COOKIE_VARS',
's' => 'HTTP_SERVER_VARS',
'e' => 'HTTP_ENV_VARS');
$_smarty_vars_request = array();
foreach (preg_split('!!', strtolower($smarty->request_vars_order)) as $_c) {
if (isset($_globals_map[$_c])) {
$_smarty_vars_request = array_merge($_smarty_vars_request, $GLOBALS[$_globals_map[$_c]]);
}
}
$_smarty_vars_request = @array_merge($_smarty_vars_request, $GLOBALS['HTTP_SESSION_VARS']);
$smarty->_smarty_vars['request'] = $_smarty_vars_request;
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,79 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* create full directory structure
*
* @param string $dir
*/
// $dir
function smarty_core_create_dir_structure($params, &$smarty)
{
if (!file_exists($params['dir'])) {
$_open_basedir_ini = ini_get('open_basedir');
if (DIRECTORY_SEPARATOR=='/') {
/* unix-style paths */
$_dir = $params['dir'];
$_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
$_new_dir = (substr($_dir, 0, 1)=='/') ? '/' : getcwd().'/';
if($_use_open_basedir = !empty($_open_basedir_ini)) {
$_open_basedirs = explode(':', $_open_basedir_ini);
}
} else {
/* other-style paths */
$_dir = str_replace('\\','/', $params['dir']);
$_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
if (preg_match('!^((//)|([a-zA-Z]:/))!', $_dir, $_root_dir)) {
/* leading "//" for network volume, or "[letter]:/" for full path */
$_new_dir = $_root_dir[1];
/* remove drive-letter from _dir_parts */
if (isset($_root_dir[3])) array_shift($_dir_parts);
} else {
$_new_dir = str_replace('\\', '/', getcwd()).'/';
}
if($_use_open_basedir = !empty($_open_basedir_ini)) {
$_open_basedirs = explode(';', str_replace('\\', '/', $_open_basedir_ini));
}
}
/* all paths use "/" only from here */
foreach ($_dir_parts as $_dir_part) {
$_new_dir .= $_dir_part;
if ($_use_open_basedir) {
// do not attempt to test or make directories outside of open_basedir
$_make_new_dir = false;
foreach ($_open_basedirs as $_open_basedir) {
if (substr($_new_dir, 0, strlen($_open_basedir)) == $_open_basedir) {
$_make_new_dir = true;
break;
}
}
} else {
$_make_new_dir = true;
}
if ($_make_new_dir && !file_exists($_new_dir) && !@mkdir($_new_dir, $smarty->_dir_perms) && !is_dir($_new_dir)) {
$smarty->trigger_error("problem creating directory '" . $_new_dir . "'");
return false;
}
$_new_dir .= '/';
}
}
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,61 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty debug_console function plugin
*
* Type: core<br>
* Name: display_debug_console<br>
* Purpose: display the javascript debug console window
* @param array Format: null
* @param Smarty
*/
function smarty_core_display_debug_console($params, &$smarty)
{
// we must force compile the debug template in case the environment
// changed between separate applications.
if(empty($smarty->debug_tpl)) {
// set path to debug template from SMARTY_DIR
$smarty->debug_tpl = SMARTY_DIR . 'debug.tpl';
if($smarty->security && is_file($smarty->debug_tpl)) {
$smarty->secure_dir[] = realpath($smarty->debug_tpl);
}
$smarty->debug_tpl = 'file:' . SMARTY_DIR . 'debug.tpl';
}
$_ldelim_orig = $smarty->left_delimiter;
$_rdelim_orig = $smarty->right_delimiter;
$smarty->left_delimiter = '{';
$smarty->right_delimiter = '}';
$_compile_id_orig = $smarty->_compile_id;
$smarty->_compile_id = null;
$_compile_path = $smarty->_get_compile_path($smarty->debug_tpl);
if ($smarty->_compile_resource($smarty->debug_tpl, $_compile_path))
{
ob_start();
$smarty->_include($_compile_path);
$_results = ob_get_contents();
ob_end_clean();
} else {
$_results = '';
}
$smarty->_compile_id = $_compile_id_orig;
$smarty->left_delimiter = $_ldelim_orig;
$smarty->right_delimiter = $_rdelim_orig;
return $_results;
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,44 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Get path to file from include_path
*
* @param string $file_path
* @param string $new_file_path
* @return boolean
* @staticvar array|null
*/
// $file_path, &$new_file_path
function smarty_core_get_include_path(&$params, &$smarty)
{
static $_path_array = null;
if(!isset($_path_array)) {
$_ini_include_path = ini_get('include_path');
if(strstr($_ini_include_path,';')) {
// windows pathnames
$_path_array = explode(';',$_ini_include_path);
} else {
$_path_array = explode(':',$_ini_include_path);
}
}
foreach ($_path_array as $_include_path) {
if (@is_readable($_include_path . DIRECTORY_SEPARATOR . $params['file_path'])) {
$params['new_file_path'] = $_include_path . DIRECTORY_SEPARATOR . $params['file_path'];
return true;
}
}
return false;
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,23 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Get seconds and microseconds
* @return double
*/
function smarty_core_get_microtime($params, &$smarty)
{
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = (double)($mtime[1]) + (double)($mtime[0]);
return ($mtime);
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,80 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Retrieves PHP script resource
*
* sets $php_resource to the returned resource
* @param string $resource
* @param string $resource_type
* @param $php_resource
* @return boolean
*/
function smarty_core_get_php_resource(&$params, &$smarty)
{
$params['resource_base_path'] = $smarty->trusted_dir;
$smarty->_parse_resource_name($params, $smarty);
/*
* Find out if the resource exists.
*/
if ($params['resource_type'] == 'file') {
$_readable = false;
if(file_exists($params['resource_name']) && is_readable($params['resource_name'])) {
$_readable = true;
} else {
// test for file in include_path
$_params = array('file_path' => $params['resource_name']);
require_once(SMARTY_CORE_DIR . 'core.get_include_path.php');
if(smarty_core_get_include_path($_params, $smarty)) {
$_include_path = $_params['new_file_path'];
$_readable = true;
}
}
} else if ($params['resource_type'] != 'file') {
$_template_source = null;
$_readable = is_callable($smarty->_plugins['resource'][$params['resource_type']][0][0])
&& call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][0],
array($params['resource_name'], &$_template_source, &$smarty));
}
/*
* Set the error function, depending on which class calls us.
*/
if (method_exists($smarty, '_syntax_error')) {
$_error_funcc = '_syntax_error';
} else {
$_error_funcc = 'trigger_error';
}
if ($_readable) {
if ($smarty->security) {
require_once(SMARTY_CORE_DIR . 'core.is_trusted.php');
if (!smarty_core_is_trusted($params, $smarty)) {
$smarty->$_error_funcc('(secure mode) ' . $params['resource_type'] . ':' . $params['resource_name'] . ' is not trusted');
return false;
}
}
} else {
$smarty->$_error_funcc($params['resource_type'] . ':' . $params['resource_name'] . ' is not readable');
return false;
}
if ($params['resource_type'] == 'file') {
$params['php_resource'] = $params['resource_name'];
} else {
$params['php_resource'] = $_template_source;
}
return true;
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,59 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* determines if a resource is secure or not.
*
* @param string $resource_type
* @param string $resource_name
* @return boolean
*/
// $resource_type, $resource_name
function smarty_core_is_secure($params, &$smarty)
{
if (!$smarty->security || $smarty->security_settings['INCLUDE_ANY']) {
return true;
}
if ($params['resource_type'] == 'file') {
$_rp = realpath($params['resource_name']);
if (isset($params['resource_base_path'])) {
foreach ((array)$params['resource_base_path'] as $curr_dir) {
if ( ($_cd = realpath($curr_dir)) !== false &&
strncmp($_rp, $_cd, strlen($_cd)) == 0 &&
substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) {
return true;
}
}
}
if (!empty($smarty->secure_dir)) {
foreach ((array)$smarty->secure_dir as $curr_dir) {
if ( ($_cd = realpath($curr_dir)) !== false) {
if($_cd == $_rp) {
return true;
} elseif (strncmp($_rp, $_cd, strlen($_cd)) == 0 &&
substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR) {
return true;
}
}
}
}
} else {
// resource is not on local file system
return call_user_func_array(
$smarty->_plugins['resource'][$params['resource_type']][0][2],
array($params['resource_name'], &$smarty));
}
return false;
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,47 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* determines if a resource is trusted or not
*
* @param string $resource_type
* @param string $resource_name
* @return boolean
*/
// $resource_type, $resource_name
function smarty_core_is_trusted($params, &$smarty)
{
$_smarty_trusted = false;
if ($params['resource_type'] == 'file') {
if (!empty($smarty->trusted_dir)) {
$_rp = realpath($params['resource_name']);
foreach ((array)$smarty->trusted_dir as $curr_dir) {
if (!empty($curr_dir) && is_readable ($curr_dir)) {
$_cd = realpath($curr_dir);
if (strncmp($_rp, $_cd, strlen($_cd)) == 0
&& substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) {
$_smarty_trusted = true;
break;
}
}
}
}
} else {
// resource is not on local file system
$_smarty_trusted = call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][3],
array($params['resource_name'], $smarty));
}
return $_smarty_trusted;
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,125 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Load requested plugins
*
* @param array $plugins
*/
// $plugins
function smarty_core_load_plugins($params, &$smarty)
{
foreach ($params['plugins'] as $_plugin_info) {
list($_type, $_name, $_tpl_file, $_tpl_line, $_delayed_loading) = $_plugin_info;
$_plugin = &$smarty->_plugins[$_type][$_name];
/*
* We do not load plugin more than once for each instance of Smarty.
* The following code checks for that. The plugin can also be
* registered dynamically at runtime, in which case template file
* and line number will be unknown, so we fill them in.
*
* The final element of the info array is a flag that indicates
* whether the dynamically registered plugin function has been
* checked for existence yet or not.
*/
if (isset($_plugin)) {
if (empty($_plugin[3])) {
if (!is_callable($_plugin[0])) {
$smarty->_trigger_fatal_error("[plugin] $_type '$_name' is not implemented", $_tpl_file, $_tpl_line, __FILE__, __LINE__);
} else {
$_plugin[1] = $_tpl_file;
$_plugin[2] = $_tpl_line;
$_plugin[3] = true;
if (!isset($_plugin[4])) $_plugin[4] = true; /* cacheable */
}
}
continue;
} else if ($_type == 'insert') {
/*
* For backwards compatibility, we check for insert functions in
* the symbol table before trying to load them as a plugin.
*/
$_plugin_func = 'insert_' . $_name;
if (function_exists($_plugin_func)) {
$_plugin = array($_plugin_func, $_tpl_file, $_tpl_line, true, false);
continue;
}
}
$_plugin_file = $smarty->_get_plugin_filepath($_type, $_name);
if (! $_found = ($_plugin_file != false)) {
$_message = "could not load plugin file '$_type.$_name.php'\n";
}
/*
* If plugin file is found, it -must- provide the properly named
* plugin function. In case it doesn't, simply output the error and
* do not fall back on any other method.
*/
if ($_found) {
include_once $_plugin_file;
$_plugin_func = 'smarty_' . $_type . '_' . $_name;
if (!function_exists($_plugin_func)) {
$smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", $_tpl_file, $_tpl_line, __FILE__, __LINE__);
continue;
}
}
/*
* In case of insert plugins, their code may be loaded later via
* 'script' attribute.
*/
else if ($_type == 'insert' && $_delayed_loading) {
$_plugin_func = 'smarty_' . $_type . '_' . $_name;
$_found = true;
}
/*
* Plugin specific processing and error checking.
*/
if (!$_found) {
if ($_type == 'modifier') {
/*
* In case modifier falls back on using PHP functions
* directly, we only allow those specified in the security
* context.
*/
if ($smarty->security && !in_array($_name, $smarty->security_settings['MODIFIER_FUNCS'])) {
$_message = "(secure mode) modifier '$_name' is not allowed";
} else {
if (!function_exists($_name)) {
$_message = "modifier '$_name' is not implemented";
} else {
$_plugin_func = $_name;
$_found = true;
}
}
} else if ($_type == 'function') {
/*
* This is a catch-all situation.
*/
$_message = "unknown tag - '$_name'";
}
}
if ($_found) {
$smarty->_plugins[$_type][$_name] = array($_plugin_func, $_tpl_file, $_tpl_line, true, true);
} else {
// output error
$smarty->_trigger_fatal_error('[plugin] ' . $_message, $_tpl_file, $_tpl_line, __FILE__, __LINE__);
}
}
}
/* vim: set expandtab: */
?>

View file

@ -0,0 +1,74 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* load a resource plugin
*
* @param string $type
*/
// $type
function smarty_core_load_resource_plugin($params, &$smarty)
{
/*
* Resource plugins are not quite like the other ones, so they are
* handled differently. The first element of plugin info is the array of
* functions provided by the plugin, the second one indicates whether
* all of them exist or not.
*/
$_plugin = &$smarty->_plugins['resource'][$params['type']];
if (isset($_plugin)) {
if (!$_plugin[1] && count($_plugin[0])) {
$_plugin[1] = true;
foreach ($_plugin[0] as $_plugin_func) {
if (!is_callable($_plugin_func)) {
$_plugin[1] = false;
break;
}
}
}
if (!$_plugin[1]) {
$smarty->_trigger_fatal_error("[plugin] resource '" . $params['type'] . "' is not implemented", null, null, __FILE__, __LINE__);
}
return;
}
$_plugin_file = $smarty->_get_plugin_filepath('resource', $params['type']);
$_found = ($_plugin_file != false);
if ($_found) { /*
* If the plugin file is found, it -must- provide the properly named
* plugin functions.
*/
include_once($_plugin_file);
/*
* Locate functions that we require the plugin to provide.
*/
$_resource_ops = array('source', 'timestamp', 'secure', 'trusted');
$_resource_funcs = array();
foreach ($_resource_ops as $_op) {
$_plugin_func = 'smarty_resource_' . $params['type'] . '_' . $_op;
if (!function_exists($_plugin_func)) {
$smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", null, null, __FILE__, __LINE__);
return;
} else {
$_resource_funcs[] = $_plugin_func;
}
}
$smarty->_plugins['resource'][$params['type']] = array($_resource_funcs, true);
}
}
/* vim: set expandtab: */
?>

Some files were not shown because too many files have changed in this diff Show more