This commit is contained in:
2026-05-15 18:33:51 +02:00
parent 3601be572f
commit c980004309
8442 changed files with 783630 additions and 1 deletions

1
core/.htaccess Normal file
View File

@@ -0,0 +1 @@
Options -Indexes

89
core/ErrorHandler.php Normal file
View File

@@ -0,0 +1,89 @@
<?php
/**
* $Id: ErrorHandler.php 959 2008-07-29 06:34:41Z pawy $
* Obsluga bledow
*
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param integer $errline
* @return unknown
*/
function AppErrorHandler($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_STRICT:
break;
case E_NOTICE:
MFLog::Warn("Line: ".$errline." File: ".$errfile." Message: ".$errstr." Referer: ".getenv('HTTP_REFERER'));
if(Config::Get('ERROR_REDIRECT') != 'true') {
echo "<span style=\"color: red;\">Unknown error type: [$errno] $errstr<br /></span>\n";
echo $errfile.':'.$errline;
}
break;
default:
if(!preg_match('/mysql_connect()/', $errstr)) {
MFLog::Error("Line: ".$errline." File: ".$errfile." Message: ".$errstr." Referer: ".getenv('HTTP_REFERER'));
if(Config::Get('ERROR_REDIRECT') == 'true') {
if(getenv('HTTP_REFERER')==Config::Get('URL_MAIN')) {
Header("Location: ".Config::Get('URL_MAIN')."/error.html");
} else {
header("HTTP/1.0 302 Moved Temporarily");
Header("Location: ".Config::Get('URL_MAIN'));
}
} else {
echo "<span style=\"color: red;\">Unknown error type: [$errno] $errstr<br /></span>\n";
echo $errfile.':'.$errline;
break;
}
}
}
/* Don't execute PHP internal error handler */
return true;
}
set_error_handler("AppErrorHandler");
/**
* Obsluguje wyjatki
*
* @param Exception $exception
*/
function ExceptionHandler($exception) {
MFLog::Error("Line: ".$exception->getLine()." Message: ".$exception->getMessage()." Referer: ".getenv('HTTP_REFERER'));
if(ERROR_REDIRECT == 'true') {
if(getenv('HTTP_REFERER')==Config::Get('URL_MAIN')) {
Header("Location: ".Config::Get('URL_MAIN')."/error.html");
} else {
header("HTTP/1.0 302 Moved Temporarily");
Header("Location: ".Config::Get('URL_MAIN'));
}
} else {
echo "<br /><span style=\"color: red;\">Nie obsluzony wyjatek: " , $exception->getMessage(), "</span>\n".getenv('HTTP_REFERER');
echo $exception;
}
}
set_exception_handler('ExceptionHandler');
if(Config::Get('ERROR_REDIRECT') == true) {
ini_set('html_errors',false);
ini_set('error_prepend_string','<html><head><META http-equiv="refresh" content="0;URL='.Config::Get('FATAL_ERROR_URL').'"></head></html>');
//ini_set('error_append_string','"></head></html>');
}
?>

View File

@@ -0,0 +1,81 @@
<?php
/**
*
* Singleton dostepu do danych konfiguracyjnych serwisu
*
*/
class Config {
static private $dbConfig;
static private $internalConfig;
static private $iniConfig;
/**
* Konstruktor klasy
*
*/
private function __construct() {}
/**
* Zapobiegacz klonowania
*
*/
private function __clone() {}
/**
* Ustawia konfiga z bazy
*
*/
public static function SetDbConfig($dbConfig) {
self::$dbConfig = $dbConfig;
}
/**
* Zwraca wartosc lub wyjatek
*
*/
public static function Get($value) {
if(isset(self::$dbConfig[$value])) {
$return = self::$dbConfig[$value];
} else if(isset(self::$internalConfig[$value])) {
$return = self::$internalConfig[$value];
} else if(isset(self::$iniConfig[$value])) {
$return = self::$iniConfig[$value];
} else if(defined($value)) {
$return = constant($value);
} else {
$return = false;
throw new UserException("Niezdefiniowany parametr konfiguracji: '$value'",$value);
}
return $return;
}
public static function Exists($value) {
if(isset(self::$dbConfig[$value]) || isset(self::$internalConfig[$value]) || defined($value)) {
return true;
} else {
$return = false;
}
}
public static function Set($variable, $value) {
self::$internalConfig[$variable] = $value;
}
public static function LoadIniConfig($file, $sections = true) {
if (!is_array(self::$iniConfig)) {
self::$iniConfig = array();
}
self::$iniConfig = array_merge(self::$iniConfig, parse_ini_file($file, $sections));
}
public static function GetIniConfig() {
return self::$iniConfig;
}
}
?>

View File

@@ -0,0 +1,755 @@
<?
/**
* $Id: Controller.mod.php 394 2008-05-28 19:28:03Z dakl $
* Klasa kontrolera v 1.2.0
*
*/
abstract class Controller {
/**
* Szablon dla metody
*
* @var unknown_type
*/
public $partialTemplate;
/**
* Sciezka szablonu dla metody
*
* @var unknown_type
*/
public $templatePath;
/**
* Wygenerowana przez metode tresc
*
* @var unknown_type
*/
public $content;
/**
* Czas cache dla metody
*
* @var unknown_type
*/
public $cacheTime;
/**
* Obiekt Smarty
*
* @var Smarty
*/
protected $smarty;
/**
* Obiekt request
*
* @Request
*/
protected $request;
public $utf8;
/**
* Zawiera url na ktory ma byc przekierowany user
*
* @var string
*/
private $redirect = array('url'=>'', 'time'=>'');
/**
* Wylacza obsluge smarty
*
* @var unknown_type
*/
public $disableTemplates = false;
public $actionRedirect = false;
private $breadCrumbs = array();
private $actionSet = array();
/**
* Konstruktor klasy
*
*/
public final function __construct() {
}
/**
* Ustawia przekierowanie
*
* @param string $action (true/false/string: action)
*
*/
public final function SetActionRedirect($action) {
$this->actionRedirect = $action;
}
/**
* Zwraca przekierowanie
*
*/
public final function GetActionRedirect() {
return $this->actionRedirect;
}
public final function SetBreadCrumbs($array) {
$this->breadCrumbs = $array;
}
public function SetUtf8() {
$this->utf8 = true;
}
public final function GetBreadCrumbs() {
return $this->breadCrumbs;
}
public final function AddBreadCrumb($title, $url) {
$this->breadCrumbs[] = array('title'=>$title, 'url'=>$url);
// Utils::ArrayDisplay($this->breadCrumbs);
}
public final function AddHeader($name, $value) {
//TODO : New Feature - testme
$headers = Registry::Get('headers');
$headers[$name][] = $value;
Registry::Remove('headers');
Registry::Set('headers', $headers);
}
/**
* Dodawanie opisu
*
* @param unknown_type $desc
*/
public final function AddDescription($desc) {
//Registry::Remove('description');
//Registry::Set('description', $desc);
$this->AddHeader('description', $desc);
}
/**
* Dodawanie opisu
*
* @param unknown_type $desc
*/
public final function AddKeywords($desc) {
//Registry::Remove('description');
//Registry::Set('description', $desc);
$this->AddHeader('meta', array('name'=>'keywords', 'content'=>$desc));
}
/**
* Metoda przypisujaca obiekt smarty
*
* @param Smarty $smarty
*/
public final function SetSmarty(Smarty $smarty) {
$this->smarty = $smarty;
}
/**
* Dodawanie elementu tytulu
*
* @param unknown_type $title
*/
public final function AddTitle($title) {
/*$t = Registry::Get('title');
$t[] = $title;
Registry::Remove('title');
Registry::Set('title', $t);*/
$this->AddHeader('title', $title);
}
/**
* Weryfikacja cache metody
*
* @param unknown_type $method
* @param unknown_type $param
* @return unknown
*/
public final function Init($method, $param) {
$this->SetReturnPath(array());
//logika werifikacji cache dla metod.
$cacheTimeTmp = CacheParam::Get(get_class($this).$method);
$cacheTimeTmp2 = CacheParam::Get(get_class($this));
if(isset($cacheTimeTmp) && $cacheTimeTmp != '') {
$cacheTime = $cacheTimeTmp;
} else if(isset($cacheTimeTmp2) && $cacheTimeTmp2 != '') {
$cacheTime = $cacheTimeTmp2;
} else {
$cacheTime = CacheParam::Get('global');
}
if($this->CheckLiveMethod($method, $param)) {
$this->cacheTime = 0;
} else {
$this->cacheTime = $cacheTime;
}
if(Core::GetAppSafeMode()) {
return true;
}
if(!$this->smarty->CacheControl($this->templatePath.$this->partialTemplate, array('cache_id'=> md5($method.$param), 'lifetime'=>$this->cacheTime))) {
if(!Core::GetAppSafeMode()) {
$this->smarty->CacheControl($this->templatePath.$this->partialTemplate, array('cache_id'=> md5($method.$param), 'write'=>true));
return false;
} else {
return true;
}
} else {
return true;
}
//echo ">>".$this->smarty->is_cached($this->templatePath.$this->partialTemplate, $method.substr($param,0, 100))."<<";
//return $this->smarty->is_cached($this->templatePath.$this->partialTemplate, $method.substr($param,0, 100));
}
/**
* Czysci bufor strony
*
* @param string $method
* @param array $param
*/
public final function ClearCache($method, $param) {
$cacheParam = implode('-', $param);
$this->smarty->clear_cache($this->partialTemplate, $method.substr($cacheParam,0, 100));
}
/**
* Dodaje skrypt do naglowka strony
*
* @param string $script
* @param string $type (file/code)
* @param string $position (top/bottom)
* @param int $sort
*/
public final function AddScript($script, $type='file', $position='top', $sort=100) {
if($position == 'top') {
$name = 'javascript';
} else {
$name = 'footerJavascript';
}
$t = Registry::Get($name);
if($type=='file') {
$t[$sort][$script] = array('file'=>$script, 'code'=>'');
} else {
$t[$sort][$script] = array('code'=>$script, 'file'=>'');
}
Registry::Remove($name);
Registry::Set($name, $t);
}
/**
* Dodaje CSS do naglowka strony
*
* @param string $script
* @param string $type (file/code)
* @param int $sort
*/
public final function AddCSS($script, $type='file', $sort=100) {
$name = 'headerCSS';
$t = Registry::Get($name);
if($type=='file') {
$t[$sort][$script] = array('file'=>$script, 'code'=>'');
} else {
$t[$sort][$script] = array('code'=>$script, 'file'=>'');
}
Registry::Remove($name);
Registry::Set($name, $t);
}
public final function AddWpStatistics($key) {
$this->AddScript("var pp_gemius_identifier ='$key';
var pp_gemius_hitcollector = 'wp.hit.gemius.pl';",'code','top',0);
$this->AddScript("WP.stat.dot('max15','','');", 'code', 'top', 2);
}
/**
* Dodaje skrypt przed </body>
*
* @param string $script
* @param string $type
*/
public final function AddFooterScript($script, $type='file') {
throw new ApiException('Metoda nieobslugiwana od wersji 1.1 Controllera. Uzyj AddScript z opcja bottom.');
}
/**
* Dodaje przekierowanie
*
* @param string $url
* @param int $time
*/
public final function AddRedirect($url, $time, $code=302) {
if(is_array($url)) {
Core::RequireOnce('plugins/Smarty/function.url.php');
$urlData = smarty_function_url($url, $this->smarty);
} else {
$urlData = $url;
}
if($this->redirect['url']=='') {
$this->redirect['url']=$urlData;
$this->redirect['time']=$time;
$this->redirect['code']=$code;
}
}
/**
* Usuwa przekierowanie
*
*/
public final function ClearRedirect() {
$this->redirect = array('url'=>'', 'time'=>'');
}
/**
* Sprawdza czy ustawione jest przekierowanie
*
* @return bool
*/
public final function IsRedirect() {
if($this->redirect['url']!='') {
$return = true;
} else {
$return = false;
}
return $return;
}
/**
* Zwraca url do przekierowania
*
* @return string
*/
public final function GetRedirect() {
return $this->redirect;
}
/**
* Wylacza wyswietlenie szablonow
*
*/
public final function SetNoRender() {
$this->disableTemplates = true;
Profiler::$profiling = false;
}
/**
* Uruchamianie obiektu klasy SharedController i wywolywanie pozadanej metody
*
* @param string $method
*/
public final function RunShared($method,$param) {
//print_R($param);
//echo $method."<br>";
$this->smarty->assign('param', $param);
$shared = new SharedController();
$shared->SetSmarty($this->smarty);
$shared->templatePath = 'partial/Shared/';
$shared->partialTemplate = $method.'.tpl';
//$this->smarty->cache_lifetime = CacheParam::Get('shared'.$method);
$cacheParam = Utils::MultiImplode('-', $param, '|').$shared->partialTemplate;
if(FrontController::dispatchChecker($this->smarty, $shared->templatePath.$shared->partialTemplate, $cacheParam, CacheParam::Get('shared'.$method))) {
//if(!$this->smarty->CacheControl($shared->templatePath.$shared->partialTemplate, array('cache_id'=> md5($cacheParam), 'lifetime'=>CacheParam::Get('shared'.$method)))) {
//if(!Core::GetAppSafeMode()) {
//$this->smarty->CacheControl($shared->templatePath.$shared->partialTemplate, array('cache_id'=> md5($cacheParam), 'write'=>true));
//$this->smarty->assign($variable, $this->smarty->fetch($shared->templatePath.$shared->partialTemplate, md5($cacheParam), md5($cacheParam)));
//if(!$this->smarty->is_cached($shared->templatePath.$shared->partialTemplate, md5($cacheParam), md5($cacheParam)) && !Core::GetAppSafeMode()) {
//echo $method."<br />".$this->smarty->is_cached($shared->templatePath.$shared->partialTemplate, md5($cacheParam));
$shared->$method($param);
//}
//echo "<br />".$method."<br />";
//echo $this->smarty->get_template_vars($variable);
}
if(isset($param['runSharedVariable'])) {
$variable = $param['runSharedVariable'];
} else {
$variable = strtolower(substr($method, 0, 1)) . substr($method, 1);
}
$this->smarty->assign($variable, $this->smarty->fetch($shared->templatePath.$shared->partialTemplate, md5($cacheParam), md5($cacheParam)));
}
/**
*
* Uruchamianie metody zewnetrzenego modulu
*
* @param string $module
* @param string $method
* @param string $param = null
* @param string $template = false - czy ma byc zaladowany template
*
*/
public final function RunModule($module,$method,$param,$template = false) {
if(isset($param) && is_array($param)) {
$cparam = Utils::MultiImplode('-', $param, '|');
} else {
$cparam = null;
}
$cacheParam = $module.$method.$template.$cparam;
$moduleControllerName = $module;
$moduleControllerName .= "Controller";
$moduleArray = explode('_', $moduleControllerName);
if (count($moduleArray) > 1) {
require_once "controller/".$moduleArray[0]."/".$moduleArray[1].".php";
} else {
require_once "controller/$moduleControllerName.php";
}
$moduleController = new $moduleControllerName();
if($template == true) {
$moduleController->SetSmarty($this->smarty);
if (count($moduleArray) > 1) {
$moduleController->templatePath = "partial/".$moduleArray[0]."/".str_replace('Controller', '',$moduleArray[1]);
// die($module.$moduleController->templatePath);
$moduleController->partialTemplate = $method.'.tpl';
} else {
$moduleController->templatePath = "partial/$module/";
// die($module.$moduleController->templatePath);
$moduleController->partialTemplate = str_replace('Action', '', $method).'.tpl';
//$this->smarty->cache_lifetime = CacheParam::Get($module.$method);
// if(!$this->smarty->is_cached($moduleController->partialTemplate) && !Core::GetAppSafeMode()) {
// return $moduleController->$method($param);
// }
//Utils::ArrayDisplay($moduleController->partialTemplate);
}
if(!$this->smarty->CacheControl($moduleController->templatePath.$moduleController->partialTemplate, array('cache_id'=> md5($cacheParam), 'lifetime'=>CacheParam::Get($module.$method)))) {
if(!Core::GetAppSafeMode()) {
//Utils::ArrayDisplay($moduleController->$method($param));
$this->smarty->CacheControl($moduleController->templatePath.$moduleController->partialTemplate, array('cache_id'=> md5($cacheParam), 'write'=>true));
return $moduleController->$method($param);
}
}
}
else {
$moduleController->SetNoRender();
return $moduleController->$method($param);
}
}
/**
*
* Uruchamianie metody zewnetrzenego modulu
*
* @param string $module
* @param string $method
* @param string $param = null
* @param string $template = false - czy ma byc zaladowany template
*
*/
public final function RunModuleController($module,$method,$param,$template = false) {
$this->smarty->assign('param', $param);
$moduleControllerName = $module;
//$moduleControllerName .= "Controller";
$moduleArray = explode('_', $moduleControllerName);
//Utils::ArrayDisplay($moduleArray);
if (count($moduleArray) > 1) {
require_once "controller/".$moduleArray[0]."/".$moduleArray[1].".php";
} else {
require_once "controller/$moduleControllerName.php";
}
//Utils::ArrayDisplay('sd: '.$moduleControllerName);
$moduleController = new $moduleControllerName();
$moduleController->SetSmarty($this->smarty);
if (count($moduleArray) > 1) {
$moduleController->templatePath = "partial/".$moduleArray[0]."/".str_replace('Controller', '',$moduleArray[1]."/");
// die($module.$moduleController->templatePath);
$moduleController->partialTemplate = $method.'.tpl';
//Utils::ArrayDisplay('metoda '.$method);
} else {
$moduleController->templatePath = "partial/".str_replace('Controller', '',$module)."/";
// die($module.$moduleController->templatePath);
$moduleController->partialTemplate = $method.'.tpl';
//$this->smarty->cache_lifetime = CacheParam::Get($module.$method);
// if(!$this->smarty->is_cached($moduleController->partialTemplate) && !Core::GetAppSafeMode()) {
// return $moduleController->$method($param);
// }
//Utils::ArrayDisplay($moduleController->partialTemplate);
}
// $moduleController->templatePath = 'partial/Shared/';
// $moduleController->partialTemplate = $method.'.tpl';
//$this->smarty->cache_lifetime = CacheParam::Get('shared'.$method);
$cacheParam = Utils::MultiImplode('-', $param, '|').$moduleController->partialTemplate;
if(FrontController::dispatchChecker($this->smarty, $moduleController->templatePath.$moduleController->partialTemplate, $cacheParam, CacheParam::Get($module.$method))) {
$methodToRun = $method.'Action';
//Utils::ArrayDisplay($methodToRun);
$moduleController->$methodToRun($param);
}
if(isset($param['runSharedVariable'])) {
$variable = $param['runSharedVariable'];
} else {
$variable = strtolower(substr($method, 0, 1)) . substr($method, 1);
}
//Utils::ArrayDisplay($param['runSharedVariable']);
//Utils::ArrayDisplay($variable);
$this->smarty->assign($variable, $this->smarty->fetch($moduleController->templatePath.$moduleController->partialTemplate, md5($cacheParam), md5($cacheParam)));
}
public final function SetRequest(Request $request) {
$this->request = $request;
}
/**
* Zwraca obiekt Request
*
* @return Request
*/
public final function Request() {
return $this->request;
}
/**
* Zmienia szablon glowny na pusty dla akcji ajaxowych
*
*/
public final function SetAjaxRender($ajaxCallPath = false) {
Router::DeleteThisUrl();
if ($ajaxCallPath) {
$prev = SessionProxy::GetValue(Router::$PREV_URL);
if($prev != null)
SessionProxy::SetValue('ajaxCallPath', $prev);
}
$template = 'clean.tpl';
Registry::Remove('smartyTemplate');
Registry::Set('smartyTemplate', $template);
Profiler::$profiling = false;
}
/**
* Ustawia sciezke powrotna
*
* @param array $path
*/
public final function SetReturnPath($path) {
Registry::Set('smartyReturnPath', $path);
}
/**
* Dodaje element sciezki powrotnej
*
* array(title=>title, url=>url)
*
* @param array $item
*/
public final function AddReturnPathItem($item) {
if(Registry::Exists('smartyReturnPath')) {
$data = Registry::Get('smartyReturnPath');
Registry::Remove('smartyReturnPath');
$data[]=$item;
Registry::Set('smartyReturnPath', $data);
}
}
/**
* Zwaraca sciezke powrotna
*
* @return array
*/
public final function GetReturnPath() {
return Registry::Get('smartyReturnPath');
}
/**
* Zwraca sformatowany url
*
* @param string $controller
* @param string $action
* @return string
*/
public final function GetMyUrl($controller,$action) {
return ereg_replace('Action', '', $action).PATH_SEPARATOR.ereg_replace('Controller', '', $controller).APPLICATION_FILE_TYPE;
}
/**
* Sprawdza czy dana metoda ma byc zawsze uruchamiana (cache independent)
*
* @param string $method
* @return bool
*/
public final function CheckLiveMethod($method, $param) {
if(isset($this->$method) || preg_match('/^ajax/', $method) || (isset($param['liveMethod']) && $param['liveMethod']==true)) {
return true;
} else {
return false;
}
}
/**
* Zwraca oryginalne parametry z urla
*
* @param array $param
* @return array
*/
public final function GetUrlParam($param) {
if(is_array($param) && isset($param['urlParam'])) {
return array_reverse(explode(",", $param['urlParam']));
} else {
return array();
}
}
public function SetActionSet($set) {
$this->actionSet = $set;
}
public function LoadAdditionalModule($module, $controller) {
if(is_file('controller/'.$module.'/'.str_replace($module.'_', '', ucfirst($controller)).'.php')) {
Core::RequireOnce('controller/'.$module.'/'.str_replace($module.'_', '', ucfirst($controller)).'.php');
MFLog::Debug('Loading module: '.$module.': '.$controller);
} else {
MFLog::Debug('Unable to load module, Loading controller: '.$controller);
throw new CoreException('Unable to load module, Loading controller: '.$controller);
}
}
public function LoadAdditionalController($controller) {
if(is_file('controller/'.ucfirst($controller).'.php')) {
Core::RequireOnce('controller/'.ucfirst($controller).'.php');
MFLog::Debug('Loading module: '.$controller);
} else {
MFLog::Debug('Unable to load module, Loading controller: '.$controller);
throw new CoreException('Unable to load module, Loading controller: '.$controller);
}
}
public function RunAdditionalModule($controller, $method) {
$controllerObj = null;
if(class_exists($controller) && class_parents($controller) == Array('MainController'=>'MainController', 'Controller'=>'Controller') && class_implements($controller) == Array('ControllerInterface'=>'ControllerInterface')) {
$controllerObj = new $controller();
if(!method_exists($controllerObj, $method) && !method_exists($controllerObj, $method.'Action')) {
MFLog::Debug('Method thoes not exists: '.$method);
throw new CoreException('Method thoes not exists: '.$method);
}
} else {
throw new CoreException('Brak klasy lub brak dziedziczenia!');
}
return $controllerObj;
}
public function DispatchAdditionalModule($controllerObj, $controller, $method, $module, $param, $liveMethod) {
$controllerObj->SetSmarty($this->smarty);
$controllerObj->partialTemplate = $method.'.tpl';
$controllerObj->templatePath = 'partial/'.str_replace('_', '/', str_replace('Controller', '', $controller)).'/';
if((!$controllerObj->Init($method, md5(implode($param, '-'))) || $controllerObj->CheckLiveMethod($method, $param) || $liveMethod) && $controllerObj->GetActionRedirect()!=true) {
$methodAction = $method;
$controllerObj->$methodAction($param);
}
if(!isset($controllerObj->content) && !$liveMethod) {
//$this->smarty->cache_lifetime = $controllerObj->cacheTime;
if(!$this->smarty->CacheControl($controllerObj->templatePath.$controllerObj->partialTemplate, array('cache_id'=> $method.substr(md5(implode($param, '-')),0,100), 'lifetime'=>$controllerObj->cacheTime)) && !Core::GetAppSafeMode()) {
$this->smarty->CacheControl($controllerObj->templatePath.$controllerObj->partialTemplate, array('cache_id'=> $method.substr(md5(implode($param, '-')),0,100), 'write'=>true));
}
$controllerObj->content = $this->smarty->fetch($controllerObj->templatePath.$controllerObj->partialTemplate, $method.substr(md5(implode($param, '-')),0,100));
//echo $this->controllerObj->templatePath.$this->controllerObj->partialTemplate;
}
//Utils::ArrayDisplay($controllerObj->content);
$this->smarty->append('zoneContent', $controllerObj->content);
$this->smarty->assign('zoneContent', $controllerObj->content);
}
public function GetActionSet() {
return $this->actionSet;
}
public function ExecuteAdditionalActions($param) {
$actionSetArray = $this->GetActionSet();
$this->smarty->assign('zoneContent', '');
//Utils::ArrayDisplay($actionSetArray);
foreach($actionSetArray as $actionSet) {
if(isset($actionSet['liveMethod'])) {
$liveMethod = true;
} else {
$liveMethod = false;
}
try {
$this->LoadAdditionalModule($actionSet['module'], $actionSet['controller']);
} catch (CoreException $e) {
$this->LoadAdditionalController($actionSet['controller']);
}
$controllerObj = $this->RunAdditionalModule($actionSet['controller'], $actionSet['method']);
$this->DispatchAdditionalModule($controllerObj, $actionSet['controller'], $actionSet['method'], $actionSet['module'], $param, $liveMethod);
}
}
}
?>

View File

@@ -0,0 +1,49 @@
<?php
/*
* Wymiana danych w kontrolerze modułowym
*/
class ControllerDataExchange {
public static function Get($variable) {
$index = self::Init();
if(isset($index[$variable])) {
return $index[$variable];
} else {
throw new UserException('Niezdefiniowana zmienna: '.$variable.' w indeksie ControllerDataExchange');
}
}
public static function Exists($variable) {
$index = self::Init();
if(isset($index[$variable])) {
return true;
} else {
return false;
}
}
public static function Set($variable, $value) {
$index = self::Init();
$index[$variable] = $value;
self::Save($index);
}
private static function Init() {
if(Registry::Exists('ControllerDataExchange')) {
return Registry::Get('ControllerDataExchange');
} else {
return array();
}
}
private static function Save($index) {
if(Registry::Exists('ControllerDataExchange')) {
return Registry::Remove('ControllerDataExchange');
}
Registry::Set('ControllerDataExchange', $index);
}
}
?>

View File

@@ -0,0 +1,26 @@
<?php
/**
* Obowiązkowy interfejs dla wszystkich kontrolerów
*
*/
interface ControllerInterface {
/**
* metoda wywolywana przed metoda
*
*/
public function PreDispatch($param);
/**
* metoda wywolywana po metodzie
*
*/
public function PostDispatch($param);
/**
* metoda glowna
*
*/
public function IndexAction($param);
}
?>

704
core/class/DB.class.php Normal file
View File

@@ -0,0 +1,704 @@
<?
/**
*
* Interfejs polaczenia z baza
*
*/
interface DBConnection {
public function Prepare($query);
public function Execute($query);
}
/**
* Interfejs danych w bazie
*
*/
interface DBStatement {
public function Execute();
public function BindParam($key, $value);
public function FetchRow();
public function FetchAssoc();
public function FetchAllAssoc();
}
/**
* Klasa do obslugi bazy mysql
*
*/
class DBMysql implements DBConnection {
protected $user;
protected $pass;
protected $dbHost;
protected $dbName;
protected $dbh;
private $query;
protected $characterset = 'utf8';
/**
* Konstruktor klasy
*
* @param string $user
* @param string $pass
* @param string $dbHost
* @param string $dbName
*/
public function __construct($user, $pass, $dbHost, $dbName) {
$this->user = $user;
$this->pass = $pass;
$this->dbHost = $dbHost;
$this->dbName = $dbName;
}
/* Nawiazywanie polaczenia z baza */
public function Connect($method = null) {
if (!Core::GetAppSafeMode()) {
try { //echo $method;
$this->DbConnect();
//Utils::ArrayDisplay($this);
$this->SelectDb();
$this->SetCharacterset();
} catch (Exception $e) {
MFLog::Fatal("Line: " . $e->getLine() . " Message: " . $e->getMessage() . " Referer: " . getenv('HTTP_REFERER'));
MFLog::Error("Switching app to safe mode");
Core::SetAppSafeMode();
}
}
}
protected function DbConnect() {
//echo"konekt";
Profiler::log('mysqlStart', '', microtime());
$this->dbh = new mysqli($this->dbHost, $this->user, $this->pass, $this->dbName);
if ($this->dbh->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
}
protected function SelectDb() {
if (!mysqli_select_db($this->dbh, $this->dbName)) {
throw new MysqlException('Cannot select database!');
}
}
protected function SetCharacterset() {
mysqli_query($this->dbh, "SET CHARACTER SET " . $this->characterset);
mysqli_query($this->dbh, "SET NAMES '" . $this->characterset . "'");
mysqli_query($this->dbh, "SET CHARACTER_SET_CLIENT = " . $this->characterset);
mysqli_query($this->dbh, "SET character_set_results = " . $this->characterset);
mysqli_query($this->dbh, "SET character_set_connection = " . $this->characterset);
}
public function Escape($string) {
$return = mysqli_real_escape_string($this->dbh, $string);
return $return;
}
/* Wykonanie zapytania */
public function Execute($query) {
if (!$this->dbh) {
$this->Connect(__METHOD__);
}
MFLog::Debug($query);
$ret = 'unexecuted';
if ($this->dbh) {
$startTime = microtime();
$ret = $this->dbh->query($query);
$endTime = microtime();
$deltaTime = (int)$endTime - (int)$startTime;
Profiler::log('mysql', $query, abs($deltaTime));
}
if (!$ret && $ret != 'unexecuted') {
throw new MysqlException(mysqli_error($this->dbh) . $query);
} else {
$this->setQuery($query);
$stmt = new DBMysqlStatement($this);
$stmt->result = $ret;
return $stmt;
}
}
/* Przygotowanie zapytania zwraca obiekt klasy DBMysqlStatement */
public function Prepare($query) {
if (!$this->dbh) {
//$this->Connect(__METHOD__);
}
$this->setQuery($query);
return new DBMysqlStatement($this);
}
/**
* Rozpoczyna transakcje
*
*/
public function BeginTransaction() {
if (!$this->dbh) {
$this->Connect(__METHOD__);
}
@mysqli_query($this->dbh, "START TRANSACTION ");
}
/**
* Zartwierdza transakcje
*
*/
public function CommitTransaction() {
if (!$this->dbh) {
$this->Connect(__METHOD__);
}
@mysqli_query($this->dbh,"COMMIT");
}
/**
* Wycofuje transakcje
*
*/
public function Rollback() {
if (!$this->dbh) {
$this->Connect(__METHOD__);
}
@mysqli_query($this->dbh,"ROLLBACK");
}
/**
* Destruktor zamykajacy polaczenie
*
*/
public function __destruct() {
if (isset($this->dbh) && is_resource($this->dbh)) {
Profiler::log('mysqlEnd', '', microtime());
}
}
public function GetDbh() {
return $this->dbh;
}
public function getQuery() {
return $this->query;
}
public function setQuery($query) {
$this->query = $query;
}
}
/**
* Klasa implementujaca interfejs DBStatement dla mysqla
*
*/
class DBMysqlStatement implements DBStatement {
public $result;
public $binds;
public $query;
public $dbh;
private $cacheTime = 30;
private $cacheFile;
private $cachePath = DBCACHE_PATH;
private $cacheEnable = DBCACHE_ENABLE;
private $cacheQuery = false;
private $dbMysql;
/**
* KOnstruktor klasy
*
* @param mysql $dbh
* @param string $query
*/
public function __construct(DBMysql $dbMysql) {
$this->query = $dbMysql->getQuery();
$this->dbh = $dbMysql->GetDbh();
$this->dbMysql = $dbMysql;
if (!$this->dbh) {
// $this->dbMysql->Connect();
//throw new MysqlException("No db connection");
}
}
/**
* Zwraca tresc zapytania
*
* @return unknown
*/
public function GetQuery() {
return $this->query;
}
/* Zamienia zmienne w zapytaniu na podane wartosci */
public function BindParam($ph, $pv) {
$this->binds[$ph] = $pv;
return $this;
}
/* Wykonanie zapytania */
public function Execute($q = null) {
//echo $q.":";
//var_dump($this->CacheCheck());
//var_dump(Core::GetAppSafeMode());
if (!$this->CacheCheck() && !Core::GetAppSafeMode()) {
//echo"qq";
if (!$this->dbh) {
$this->dbMysql->Connect(__METHOD__ . $this->query);
}
$binds = func_get_args();
foreach ($binds as $index => $name) {
$this->binds[$index + 1] = $name;
}
$cnt = count($binds);
$query = $this->query;
$binds = func_get_args();
foreach ($binds as $index => $name) {
$this->binds[$index + 1] = $name;
}
$cnt = count($binds);
$query = $this->query;
//Utils::ArrayDisplay($query);
if(is_countable($this->binds)) {
if (count($this->binds) > 0) {
foreach ($this->binds as $ph => $pv) {
// $query = str_replace(":$ph", "'".mysqli_escape_string($pv)."'", $query);
$query = str_replace(":$ph", '\'' . mysqli_real_escape_string($this->dbh, $pv) . '\'', $query);
}
}//echo ">>".$query;
}
MFLog::Debug(__FUNCTION__ . ' query: ' . $query);
$startTime = microtime();
$this->result = $this->dbh->query($query);
$endTime = microtime();
$deltaTime = (int)$endTime - (int)$startTime;
Profiler::log('mysql', $query, abs($deltaTime));
if (!$this->result) {
throw new MysqlException($query . "<br /><br />" . mysqli_error($this->dbh));
}
}
return $this;
}
/* Zwraca wiersz */
public function FetchRow() {
if (!$this->result) {
throw new MysqlException("Query failed");
}
$this->SetCacheFile($this->query . 'FetchRow');
if ($this->cacheQuery == false) {
if (!$this->result)
$this->Execute();
$result = mysqli_fetch_row($this->result);
mysqli_free_result($this->result);
}
else if ($this->cacheQuery == true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
if (!$this->result)
$this->Execute();
$result = mysqli_fetch_row($this->result);
mysqli_free_result($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/* Zwraca wiersz jako tablice asocjacyjna */
public function FetchAssoc() {
$this->SetCacheFile($this->query . 'FetchAssoc');
if ($this->cacheQuery == false) {
//$this->dbMysql->Connect();
if (!$this->result)
$this->Execute();
//var_dump($this->result);
//Utils::ArrayDisplay($this);
$result = \mysqli_fetch_assoc($this->result);
}
else if (($this->cacheQuery == true && !$this->CacheCheck() && !Core::GetAppSafeMode())) {
//$this->dbMysql->Connect(__METHOD__);
$this->Execute();
$result = mysqli_fetch_assoc($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
//Utils::ArrayDisplay($this->dbh);
return $result;
}
/* Zwraca ca<63>y wynik jako tablica asocjacyjna */
public function FetchAllAssoc() {
$this->SetCacheFile($this->query . 'FetchAllAssoc');
//Utils::ArrayDisplay($this);
if ($this->cacheQuery == false) {
$result = array();
//$this->Execute();
while ($row = $this->fetchAssoc()) {
$result[] = $row;
}
} else if ($this->cacheQuery == true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
$result = array();
$this->cacheQuery = false;
while ($row = $this->fetchAssoc()) {
$result[] = $row;
}
$this->SetCacheFile($this->query . 'FetchAllAssoc');
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/* Zwraca ca<63>y wynik jako tablica asocjacyjna */
public function FetchAllRow() {
$this->SetCacheFile($this->query . 'FetchAllRow');
if ($this->cacheQuery == false) {
$result = array();
while ($row = $this->fetchRow()) {
$result[] = $row;
}
} else if ($this->cacheQuery == true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
$result = array();
$this->cacheQuery = false;
while ($row = $this->fetchRow()) {
$result[] = $row;
}
$this->SetCacheFile($this->query . 'FetchAllRow');
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/* Zwraca liczbe wierszy */
public function NumRows() {
if (!$this->result) {
throw new MysqlException("Query failed");
}
$this->SetCacheFile($this->query . 'NumRows');
if ($this->cacheQuery == false) {
if (!$this->result)
$this->Execute();
$result = mysqli_num_rows($this->result);
}
else if ($this->cacheQuery == true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
if (!$this->result)
$this->Execute();
$result = mysqli_num_rows($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/* Zwraca wiersz w postaci tablicy */
public function FetchArray() {
if (!$this->result) {
throw new MysqlException("Query failed");
}
$this->SetCacheFile($this->query . 'FetchArray');
if ($this->cacheQuery == false) {
if (!$this->result)
$this->Execute();
$result = mysqli_fetch_array($this->result);
}
else if ($this->cacheQuery == true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
if (!$this->result)
$this->Execute();
$result = mysqli_fetch_array($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/**
* Zwraca id ostatnio zmienionego rekordu
*
* @return integer
*/
public function GetInsertionId() {
if (!$this->result) {
throw new MysqlException("Query failed");
}
return mysqli_insert_id($this->dbh);
}
/**
* Zwraca liczb<7A> zmienionych rekord<72>w w ostatnim zapytaniu modyfikuj<75>cym dane.
*
* @return integer
*/
public function GetAffectedRows() {
if (!$this->result) {
throw new MysqlException("Query failed");
}
return mysqli_affected_rows($this->dbh);
}
/**
* Sprawdza czy zaoytanie jest cacheowane
*
* @return boolean
*/
public function CacheCheck() {
if (($this->cacheEnable == true && (is_file($this->cachePath . $this->cacheFile) && filemtime($this->cachePath . $this->cacheFile) > (time() - $this->cacheTime)))) {
return true;
} else {
if (is_file($this->cachePath . $this->cacheFile)) {
touch($this->cachePath . $this->cacheFile);
}
return false;
}
}
/**
* Zapisuje cache do pliku
*
* @param obj $result
*/
public function CacheWrite($result) {
if ($this->cacheEnable != false) {
$records = serialize($result);
$fp = fopen($this->cachePath . $this->cacheFile, "w");
fputs($fp, $records);
fclose($fp);
$this->cacheQuery = false;
}
}
/**
* Odczytuje cache z pliku
*
* @return obj
*/
public function CacheRead() {
if (is_file($this->cachePath . $this->cacheFile)) {
$records = unserialize(file_get_contents($this->cachePath . $this->cacheFile));
$this->cacheQuery = false;
return $records;
} else {
throw new MysqlException('File does not exist: ' . $this->cachePath . $this->cacheFile);
}
}
/**
* Uruchamia cacheowanie
*
* @param integer $time
*/
public function CacheStart($time = null) {
if ($time != null && $this->cacheEnable != false) {
$this->cacheTime = $time;
}
if ($this->cacheEnable != false)
$this->cacheQuery = true;
else
$this->cacheQuery = false;
return $this;
}
/**
* Ustanawia nazw<7A> pliku cache
*
* @param unknown_type $fileName
*/
public function SetCacheFile($fileName) {
$this->cacheFile = md5($fileName);
}
}
/**
* Klasa obslugi wynikow zapytan
*
*/
class DBResult {
protected $stmt;
protected $result = array();
private $rowIndex = 0;
private $currIndex = 0;
private $done = false;
/**
* Konstruktor
*
* @param DBStatement $stmt
*/
public function __construct(DBStatement $stmt) {
$this->stmt = $stmt;
}
/* Zwraca pierwszy rekord */
public function First() {
if (!$this->result) {
$this->result[$this->rowIndex++] = $this->stmt->FetchAssoc();
}
$this->currIndex = 0;
return $this;
}
/* Zwraca ostatni rekord */
public function Last() {
if (!$this->done) {
array_push($this->result, $this->stmt->FetchAllAssoc());
}
$this->done = true;
$this->currIndex = $this->rowIndex = count($this->result) - 1;
return $this;
}
/* Zwieksza index i zwraca kolejny rekord */
public function Next() {
if ($this->done) {
return false;
}
$offset = $this->currIndex + 1;
if (!$this->result[$offset]) {
$row = $this->stmt->FetchAssoc();
if (!$row) {
$this->done = true;
return false;
}
$this->result[$offset] = $row;
++$this->rowIndex;
++$this->currIndex;
return $this;
} else {
++$this->currIndex;
return $this;
}
}
/* Zmniejsza index i zwraca poprzedni wiersz */
public function Prev() {
if ($this->currIndex == 0) {
return false;
}
--$this->currIndex;
return $this;
}
/**
* Getter dla pobieranych danych
*
* @param string $value
* @return string
*/
public function __get($value) {
if (array_key_exists($value, $this->result[$this->currIndex])) {
return $this->result[$this->currIndex][$value];
}
}
}
/**
* Klasa oslonowa naszej bazy danych
*
*/
class DBProd extends DBMysql {
protected $user;
protected $pass;
protected $dbHost;
protected $dbName;
/**
* Pusty konstruktor
*
*/
public function __construct() {
//$db = Config::Get('db');
//Utils::ArrayDisplay($db, __FILE__.' - '.__LINE__);
$this->dbHost = prodHost;
$this->dbName = prodDb;
$this->user = prodUser;
$this->pass = prodPass;
}
public function GetDbh() {
if (empty($this->dbh)) {
//$this->Connect(__METHOD__);
}
return $this->dbh;
}
}
?>

489
core/class/Daemon.class.php Normal file
View File

@@ -0,0 +1,489 @@
<?php
// Logowanie
define('DLOG_TO_CONSOLE', 1);
define('DLOG_NOTICE', 2);
define('DLOG_WARNING', 4);
define('DLOG_ERROR', 8);
define('DLOG_CRITICAL', 16);
/**
* Daemon
*
* Wymagania:
* Unix
* PHP 4 >= 4.3.0 or PHP 5
* PHP z:
* --enable-sigchild
* --enable-pcntl
*/
class Daemon
{
private $userID = 99;
public $x=0;
private $groupID = 99;
/**
* Zakonczyc prace gdy nie da sie ustawic tozsamosci demona ?
*/
private $requireSetIdentity = false;
/**
* sciezka do pida
*
*/
private $pidFileLocation = '/home/users/turystyka/public_html/test/daemon.pid';
/**
* sciezka home'a.. tylko po co?
*
*/
private $homePath = '/home/users/turystyka/public_html/Server/Daemon';
/**
* id procesu
*
*/
protected $pid = 0;
/**
* czy proces jest dzieckiem
*
*/
private $isChildren = false;
/**
* czy dzialamy czy nie :)
*
*/
private $isRunning = false;
private $children = array();
private $maxProcesses = 10;
/**
* Konstruktor
*/
public function __construct($homePath, $pidFileLocation) {
error_reporting(0);
set_time_limit(0);
ob_implicit_flush();
register_shutdown_function(array(&$this, 'releaseDaemon'));
}
public function GetUserID() {
return $this->userID;
}
public function SetUserID($userID) {
$this->userID = $userID;
}
public function GetGroupID() {
return $this->groupID;
}
public function SetGroupID($groupID) {
$this->groupID = $groupID;
}
public function GetRequireSetIdentity() {
return $this->requireSetIdentity;
}
public function SetRequireSetIdentity($requireSetIdentity) {
$this->requireSetIdentity = $requireSetIdentity;
}
public function GetPidFileLocation() {
return $this->pidFileLocation;
}
public function SetPidFileLocation($pidFileLocation) {
$this->pidFileLocation = $pidFileLocation;
}
public function GetHomePath() {
return $this->homePath;
}
public function SetHomePath($homePath) {
$this->homePath = $homePath;
}
public function GetPid() {
return $this->pid;
}
public function SetPid($pid) {
$this->pid = $pid;
$fp = fopen($this->GetHomePath().'/'.$this->pid.'.pid', 'w');
fwrite($fp, serialize($this));
fclose($fp);
}
public function GetIsChildren() {
return $this->isChildren;
}
public function SetIsChildren($isChildren) {
$this->isChildren = $isChildren;
}
public function GetIsRunning() {
return $this->isRunning;
}
public function SetIsRunning($isRunning) {
$this->isRunning = $isRunning;
}
public function GetChildren() {
return $this->children;
}
public function AddChild($pid) {
$this->children[$pid] = true;
}
public function RemChild($pid) {
if(isset($this->children[$pid])) {
unset($this->childern[$pid]);
}
}
public function StartChild($child) {
$pid = Daemon::InitChild($chils, $this->GetPid());
$this->AddChild($pid);
MFLog::DbLog('Child process '.$pid.' started');
if(!is_dir($filename)) {
mkdir($this->GetHomePath().'/'.$this->GetPid(), 0777);
}
$fp = fopen($this->GetHomePath().'/'.$this->GetPid().'/'.$pid.'.pid', 'w');
fwrite($fp, serialize($child));
fclose($fp);
$pidReturn = pcntl_waitpid($pid, $status);
if(pcntl_wifexited($status)) {
MFLog::DbLog('Child process '.$pid.' finished with status: '.$status);
} else {
MFLog::DbLog('child process '.$pid.' died');
}
return true;
}
public static function InitChild($child, $masterPid) {
$pid = pcntl_fork();
if($pid == 0) {
exit($child->Run($masterPid));
} else {
return $pid;
}
}
public function KillAll() {
foreach($this->GetChildren() as $pid => $data) {
MFLog::DbLog('Killing: '.$pid);
posix_kill($pid, 0);
if(is_file($this->GetHomePath().'/'.$this->GetPid().'/'.$pid.'.pid')) {
unlink($this->GetHomePath().'/'.$this->GetPid().'/'.$pid.'.pid');
}
}
}
/**
* Inicjowanie komponentow systemu
*
*/
public function Init() {
//include('class/DB.class.php');
//include('class/Registry.class.php');
//include('ErrorHandler.php');
$db = new DBProd();
Registry::Remove('db');
Registry::Set('db', $db);
}
/**
* Start daemona
*
*/
public function Start() {
$this->LogMessage('Starting daemon');
if (!$this->Daemonize())
{
$this->LogMessage('Could not start daemon', DLOG_ERROR);
return false;
}
$this->LogMessage('Running...');
$this->IsRunning = true;
while ($this->IsRunning)
{
$this->DoTask();
}
return true;
}
/**
* Stop daemona
*
*/
public function Stop()
{
$this->LogMessage('Stoping daemon');
$this->KillAll();
if(is_file($this->GetHomePath().'/'.$this->pid.'.pid')) {
unlink($this->GetHomePath().'/'.$this->pid.'.pid');
}
$this->IsRunning = false;
//posix_kill($this->GetPid(), 0);
//exit;
}
/**
* Podaj lape :)
*
*/
function DoTask()
{
while(1) {
if(is_dir($this->GetHomePath().'/todo')) {
if($handle = opendir($this->GetHomePath().'/todo')) {
while (false !== ($file = readdir($handle))) {
if(count($this->GetChildren()) < $this->maxProcesses) {
$taskFile = fopen($this->GetHomePath().'/todo/'.$file, 'r');
$taskData = fread($taskFile, filesize($this->GetHomePath().'/todo/'.$file));
fclose($taskFile);
unlink($this->GetHomePath().'/todo/'.$file);
$taskObj = unserialize($taskData);
$this->InitChild($taskObj, $this->GetPid());
}
}
}
}
}
// hau hau
//mail('pawy@formix.pl', 'demonizer', 'im running');
// $fp = fopen('/home/users/turystyka/public_html/test/data'.$this->x.'.txt', 'w');
// fwrite($fp, '1');
// fwrite($fp, '23');
// fclose($fp);
// sleep(10);
// //$fp = fopen('/home/users/turystyka/public_html/test/data2.txt', 'w');
// $this->x++;
// if($this->x < 5){
// $this->DoTask();
// } else {
// $this->Stop();
// }
}
/**
* Logujemy cos
*
*/
public function LogMessage($msg, $level = DLOG_NOTICE)
{
// logowanie
MFLog::DbLog($msg);
}
/**
* Nie taki diabel straszny..
*
*/
private function Daemonize()
{
// ob_end_flush();
if ($this->IsDaemonRunning())
{
// Deamon dziala. Exiting
return false;
}
if (!$this->Fork())
{
// niesforkowalo sie. Exiting.
return false;
}
if (!$this->SetIdentity() && $this->requireSetIdentity)
{
// nie udalo sie ustawic tozsamosci. Exiting
return false;
}
if (!posix_setsid())
{
$this->LogMessage('Could not make the current process a session leader', DLOG_ERROR);
return false;
}
if (!$fp = @fopen($this->pidFileLocation, 'w'))
{
$this->LogMessage('Could not write to PID file', DLOG_ERROR);
return false;
}
else
{
fputs($fp, $this->pid);
fclose($fp);
}
@chdir($this->homePath);
umask(0);
declare(ticks = 1);
pcntl_signal(SIGCHLD, array(&$this, 'sigHandler'));
pcntl_signal(SIGTERM, array(&$this, 'sigHandler'));
return true;
}
/**
* sprawdzamy czy dzialamy juz
*
*/
private function IsDaemonRunning()
{
$oldPid = false;
if(is_file($this->pidFileLocation)) {
$oldPid = @file_get_contents($this->pidFileLocation);
}
if ($oldPid !== false && posix_kill(trim($oldPid),0))
{
$this->LogMessage('Daemon already running with PID: '.$oldPid, (DLOG_TO_CONSOLE | DLOG_ERROR));
return true;
}
else
{
return false;
}
}
/**
* Forkujemy proces
*/
private function Fork()
{
$this->LogMessage('Forking...');
$pid = pcntl_fork();
if ($pid == -1) // error
{
$this->LogMessage('Could not fork', DLOG_ERROR);
return false;
}
else if ($pid) // parent
{
$this->LogMessage('Killing parent');
exit();
}
else // children
{
$this->IsChildren = true;
$this->SetPid(posix_getpid());
return true;
}
}
/**
* Ustawiamy tozsamosc diob³a i zwracamy wynik
*
*/
private function SetIdentity()
{
if (!posix_setgid($this->groupID) || !posix_setuid($this->userID))
{
$this->LogMessage('Could not set identity', DLOG_WARNING);
return false;
}
else
{
return true;
}
}
/**
* Obsluga sig'ow
*
*/
public function SigHandler($sigNo)
{
switch ($sigNo)
{
case SIGTERM: // Shutdown
$this->LogMessage('Shutdown signal');
$this->Stop();
exit();
break;
case SIGCHLD: // Halt
$this->LogMessage('Halt signal');
while (pcntl_waitpid(-1, $status, WNOHANG) > 0);
break;
}
}
/**
* Zwalnia plik z pidem
* Cos ala desktruktor
*
*/
public function ReleaseDaemon()
{
if (file_exists($this->pidFileLocation))
// if ($this->isChildren && file_exists($this->pidFileLocation))
{
$this->LogMessage('Releasing daemon');
unlink($this->pidFileLocation);
}
}
}
?>

View File

@@ -0,0 +1,77 @@
<?php
class DaemonTask {
private $pid;
private $sheduleType = array('year'=>0, 'month'=>0, 'week'=>0, 'day'=>0, 'hour'=>0, 'minute'=>0, 'second'=>0);
private $sheduleOffset;
private $masterPid;
public function getPid() {
return $this->pid;
}
public function SetPid($pid) {
$this->pid = $pid;
}
public function GetSheduleType() {
return $this->sheduleType;
}
public function SetSheduleType($sheduleType) {
$this->sheduleType = $sheduleType;
}
public function GetSheduleOffset() {
return $this->sheduleOffset;
}
public function SetSheduleOffset($sheduleOffset) {
$this->sheduleOffset = $sheduleOffset;
}
public function GetMasterPid() {
return $this->masterPid;
}
public function SetMasterPid($masterPid) {
$this->masterPid = $masterPid;
}
public function __construct() {
}
public function Run($masterPid) {
$this->SetMasterPid($masterPid);
$this->Action();
$this->ReShedule();
return true;
}
public function Action() {
return true;
}
public function ReShedule() {
$shedule = $this->GetSheduleType();
if(isset($shedule['year']) && $shedule['year']>0) {
//$next = mktime(0,0,0,date("m"), date("d"), date("Y")+$shedule['year']);
}
return true;
}
}
?>

View File

@@ -0,0 +1,310 @@
<?php
/*
* Obiekt konfiguracyjny dla DALi
*/
class DalData {
/*
* nazwa klasy
*/
private $objClassName;
/*
* tablica klasy
*/
private $objClassTable;
/*
* primary key
*/
private $objClassTablePK;
/*
* klasa opcjonalna
*/
private $optClass;
/*
* warunki
*/
private $condition = array(); //$data
/*
* lista pol do selecta
*/
private $queryFields = array();
private $selectFields = array();
/*
* limit
*/
private $limit = 0;
/*
* order by
*/
private $sortBy = null;
/*
* group by
*/
private $groupBy = null;
/*
* count w wyniku
*/
private $count = null;
/*
* zapytanie cacheowane
*/
private $cache = true;
/*
* tablica do joina
*/
private $join = null;
/*
* czas cache
*/
private $cacheTime = 0;
/*
* cacheowanie obiektow wynikowych
*/
private $cacheObject = 0;
/*
* obiekt do przeslania do dal
*/
private $obj;
private $updateFileldArray;
private $id;
private $fieldName;
private $updateFieldId;
/*
* handler do bazy db/sqlite
*/
private $databaseType = 'db';
private $dataArray = array();
public function getUpdateFieldId() {
return $this->updateFieldId;
}
public function setUpdateFieldId($updateFieldId) {
$this->updateFieldId = $updateFieldId;
}
public function __construct($data = array()) {
if(is_array($data))
{
foreach($data as $key => $value)
{
eval ('self::set' . $key . '($value);');
}
}
}
public function getCacheTime() {
return $this->cacheTime;
}
public function setCacheTime($cacheTime) {
$this->cacheTime = $cacheTime;
}
public function getObjClassName() {
return $this->objClassName;
}
public function setObjClassName($objClassName) {
$this->objClassName = $objClassName;
}
public function getObjClassTable() {
return $this->objClassTable;
}
public function setObjClassTable($objClassTable) {
$this->objClassTable = $objClassTable;
}
public function getObjClassTablePK() {
return $this->objClassTablePK;
}
public function setObjClassTablePK($objClassTablePK) {
$this->objClassTablePK = $objClassTablePK;
}
public function getOptClass() {
return $this->optClass;
}
public function setOptClass($optClass) {
$this->optClass = $optClass;
}
public function getCondition() {
return $this->condition;
}
public function setCondition($condition) {
$this->condition = $condition;
}
public function addCondition($field, $value, $condition = null, $split = null) {
if ($condition === null) {
$this->condition[$field] = $value;
} else {
$this->condition[$field] = array('value' => $value, 'split' => $split, 'condition' => $condition);
}
}
public function getQueryFields() {
return $this->queryFields;
}
public function setQueryFields($queryFields) {
$this->queryFields = $queryFields;
}
public function getLimit() {
return $this->limit;
}
public function setLimit($limit) {
$this->limit = $limit;
}
public function getSortBy() {
return $this->sortBy;
}
public function setSortBy($sortBy) {
$this->sortBy = $sortBy;
}
public function getCount() {
return $this->count;
}
public function setCount($count) {
$this->count = $count;
}
public function getCache() {
return $this->cache;
}
public function setCache($cache) {
$this->cache = $cache;
}
public function getJoin() {
return $this->join;
}
public function setJoin($join) {
$this->join = $join;
}
public function addJoin($name, $join) {
$this->join[$name] = $join;
}
public function getCacheObject() {
return $this->cacheObject;
}
public function setCacheObject($cacheObject) {
$this->cacheObject = $cacheObject;
}
public function getObj() {
return $this->obj;
}
public function setObj($obj) {
$this->obj = $obj;
}
public function getUpdateFileldArray() {
return $this->updateFileldArray;
}
public function setUpdateFileldArray($updateFileldArray) {
$this->updateFileldArray = $updateFileldArray;
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getFieldName() {
return $this->fieldName;
}
public function setFieldName($fieldName) {
$this->fieldName = $fieldName;
}
public function getDatabaseType() {
return $this->databaseType;
}
public function setDatabaseType($databaseType) {
$this->databaseType = $databaseType;
}
public function getDataArray($key) {
if(isset($this->dataArray[$key]))
return $this->dataArray[$key];
else
return null;
}
public function setDataArray($key,$value) {
$this->dataArray[$key] = $value;
}
public function getSelectFields() {
return $this->selectFields;
}
public function getSelectFieldsQuery()
{
if(count($this->selectFields) > 0 )
{
$q = " , ";
foreach($this->selectFields as $key => $value)
{
$q.= $value . " as " . $key . ",";
}
return substr($q, 0, strlen($q)-1);
}
else
return null;
}
public function addSelectFields($selectFields,$key) {
if($key == null)
$this->selectFields[] = $selectFields;
else
$this->selectFields[$key] = $selectFields;
}
public function getGroupBy() {
return $this->groupBy;
}
public function setGroupBy($groupBy) {
$this->groupBy = $groupBy;
}
public function getFields()
{
if(!is_null($this->obj))return $this->obj->GetFields();
else return false;
}
}
?>

View File

@@ -0,0 +1,202 @@
<?php
/**
* Description of DataObject
*
* @author mabi
*/
abstract class DataObject {
static $tableName;
static $className = __CLASS__;
static $fields = array();
static $classTablePK;
protected $label;
public function GetLabel() {
if (!$this->label) {
throw new UserException("Object hasn't label.");
}
return $this->label;
}
/**
* pola wystepujace tylko w obiekatch (nie sa zapisywane do BD)
*
* @var array
*/
static $classFields = array();
protected $id;
/** zdjecia **/
/**
* Export danych do tablicy asocjacyjnej z pol klasy.
*
* @return array()
*/
public function ToArrayAssoc() {
$fields = $this->GetFields();
$done = array();
foreach($fields as $index => $value) {
$temp = 'Get'.$fields[$index];
$done[$index] = $this->$temp();
}
return $done;
}
/**
* Import danych z tablicy asocjacyjnej do p�l klasy.
*
* @param string $array tablica asocjacyjna zawieraj�ca rekordy pobrane z bazy
* @param int $cut 1 - klucze musz� mie� posta� <KLASA>_<POLE>, 0 - <POLE>
*/
public function FromArray($array, $cut = false, $alias = null) {
$fields = $this->GetFields();
// sprawdzenie czy istnieje metoda dla pol niebedacych w BD
if(method_exists($this, 'GetClassFields')) {
$fields = array_merge($fields, $this -> GetClassFields());
}
$prfx = ((!empty($alias) && is_string($alias)) ? $alias .'_' : '' );
if (is_array($array))
foreach ($array as $index => $var) {
if($cut == true)
$index = str_replace($prfx . $this->GetClassName() . "_", "", $index);
if (array_key_exists($index, $fields)) {
$temp = 'Set'.$fields[$index];
$this->$temp($var);
}
}
}
/**
* Import danych z tablicy asocjacyjnej do p�l klasy.
* Jedyn� r�nic� w por�wnaniu do @see FromArray jest zmiana postaci
* klucza, kt�re teraz maja posta�: $prefix_<KLASA>_<POLE>
*
* @param string $array tablica asocjacyjna zawieraj�ca rekordy pobrane z bazy
*/
public function FromArrayPrefix($array, $prefix) {
$fields = $this->GetFields();
if (is_array($array)) {
foreach ($array as $index => $var) {
$index = str_replace($prefix . "_" . $this->GetClassName() . "_", "", $index);
if (array_key_exists($index, $fields)) {
$temp = 'Set'.$fields[$index];
$this->$temp($var);
}
}
}
}
// public function GetType() {
// //MAKL:!!
// return array_search($this->GetClassName(),'Stars');
// }
public abstract function GetId();
public abstract function GetTableName();
public abstract function GetFields();
public abstract function GetClassName();
public abstract function GetClassTablePK();
public static function GetStaticVariable($variableName) {
if(isset(self::$$variableName)) {
return self::$$variableName;
} else {
throw new Exception('Klasa '.__CLASS__.' nie posiada staÅej: '.$variableName.' !');
}
}
/**
* Metoda zwraca tablice id'k�w tablicy obiekt�w.
* Wykorzystywana na potrzeby DefaultDAL::ToJavaScriptArray($array, $jsName)
*
* @param array $objArray
*/
public static function GetObjIDs($objArray) {
$array = array();
if(is_array($objArray)) {
foreach($objArray as $obj) {
$array[] = $obj->GetId();
}
} else {
return $array;
}
return $array;
}
/**
* Metoda zwraca tablice nazw
* Wykorzystywana tylko w slownikach!
*
* @param unknown_type $objArray
*/
public static function ToArray($objArray) {
$done = array();
foreach($objArray as $value) {
$done[$value->GetId()] = $value->GetName();
}
return $done;
}
public static function ToArrayUrl($objArray) {
$done = array();
foreach($objArray as $value) {
$done[$value->GetName()] = $value->GetUrlName();
}
return $done;
}
public function GetTitleAlt() {
return strip_tags(Utils::cleanUrlSpaces($this->GetTitle()));
}
public function GetTitleUrl() {
return Utils::TextToUrl(strip_tags(Utils::cleanUrl($this->GetTitle())));
}
/**
* Funkcja generuje url
*
* TODO: Dopisaæ dzia³anie matrixa.
*
* @param String $label Opcjonalnie, niestandardowy label
*/
public function GenerateUrl($label = null, $matrix = array()) {
if (!$label) {
$label = $this->GetLabel();
}
$route = Router::$route[$label];
$dataArray = array();
foreach ($route['variables'] as $v) {
$fun = 'Get' . ucfirst($v);
$dataArray[$v] = Utils::TextToUrl($this->$fun());
}
return Router::GenerateUrl($label, $dataArray);
}
// abstract public function GetUrl();
}
?>

View File

@@ -0,0 +1,43 @@
<?php
class DbCache {
private $query;
private $cacheTime = 30;
private $cacheFile;
private $cachePath = DBCACHE_PATH;
private $cacheEnable = DBCACHE_ENABLE;
public function __construct($query, $time=null) {
$this->query = $query;
$this->cacheFile = md5($query);
if($time!=null) $this->cacheTime = $time;
}
public function CacheCheck() {
if($this->cacheEnable == false || ($this->cacheEnable == true && is_file($this->cachePath.$this->cacheFile) && filemtime($this->cachePath.$this->cacheFile) > (time() - $this->cacheTime))) {
return true;
} else {
return false;
}
}
public function CacheWrite($result) {
if($this->cacheEnable != false) {
$records = serialize($result);
$fp = fopen($this->cachePath.$this->cacheFile, "w");
fputs($fp, $records);
fclose($fp);
}
}
public function CacheRead() {
$records = unserialize(file_get_contents($this->cachePath.$this->cacheFile));
return $records;
}
}
?>

View File

@@ -0,0 +1,476 @@
<?php
/**
* Klasa do obslugi bazy mysql
*
*/
class DbSqlLite implements DBConnection {
protected $user;
protected $pass;
protected $dbHost;
protected $dbName;
protected $dbh;
protected $fileName;
protected $mode = '0666';
protected $characterset = 'utf-8';
/**
* Konstruktor klasy
*
* @param string $user
* @param string $pass
* @param string $dbHost
* @param string $dbName
*/
public function __construct($file) {
$this->fileName = $file;
}
/*Nawiazywanie polaczenia z baza*/
protected function Connect() {
try {
$this->DbConnect();
$this->SetCharacterset();
} catch (Exception $e) {
MFLog::Fatal("Line: ".$e->getLine()." Message: ".$e->getMessage()." Referer: ".getenv('HTTP_REFERER'));
MFLog::Error("Switching app to safe mode");
Core::SetAppSafeMode();
}
}
protected function DbConnect() {
$this->dbh = sqlite_open($this->fileName, $this->mode, $errorMessage);
if(empty($this->dbh)) {
throw new CoreException('Cannot connect to database! '.$errorMessage);
}
}
protected function SetCharacterset() {
//sqlite_query($this->dbh, "SET CHARACTER SET ".$this->characterset);
//sqlite_query($this->dbh, "SET NAMES '".$this->characterset."'");
//sqlite_query($this->dbh, "SET CHARACTER_SET_CLIENT = ".$this->characterset);
//sqlite_query($this->dbh, "SET character_set_results = ".$this->characterset);
//sqlite_query($this->dbh, "SET character_set_connection = ".$this->characterset);
}
public function Escape($string) {
if(Enviroment::CheckMagicQuotes()) {
$return = $string;
} else {
$return = sqlite_escape_string($string);
}
return $return;
}
/*Wykonanie zapytania*/
public function Execute($query) {
if(!$this->dbh) {
$this->Connect();
}
MFLog::Debug($query);
$ret = 'unexecuted';
if($this->dbh) {
$ret = sqlite_query($this->dbh, $query);
}
if(!$ret && $ret!='unexecuted') {
throw new CoreException(sqlite_error_string(sqlite_last_error($this->dbh)).$query);
}
else {
$stmt = new DbSqlLiteStatement($this->dbh, $query);
$stmt->result = $ret;
return $stmt;
}
}
/*Przygotowanie zapytania zwraca obiekt klasy DBMysqlStatement*/
public function Prepare($query) {
if(!$this->dbh) {
$this->Connect();
}
return new DbSqlLiteStatement($this->dbh, $query);
}
/**
* Rozpoczyna transakcje
*
*/
public function BeginTransaction() {
if(!$this->dbh) {
$this->Connect();
}
@sqlite_query("START TRANSACTION ");
}
/**
* Zartwierdza transakcje
*
*/
public function CommitTransaction() {
if(!$this->dbh) {
$this->Connect();
}
@sqlite_query("COMMIT");
}
/**
* Wycofuje transakcje
*
*/
public function Rollback() {
if(!$this->dbh) {
$this->Connect();
}
@sqlite_query("ROLLBACK");
}
/**
* Destruktor zamykajacy polaczenie
*
*/
public function __destruct() {
if(isset($this->dbh) && is_resource($this->dbh)) {
sqlite_close($this->dbh);
}
}
public function GetDbh() {
return $this->dbh;
}
}
/**
* Klasa implementujaca interfejs DBStatement dla mysqla
*
*/
class DbSqlLiteStatement implements DBStatement {
public $result;
public $binds;
public $query;
public $dbh;
private $cacheTime = 30;
private $cacheFile;
private $cachePath = DBCACHE_PATH;
private $cacheEnable = DBCACHE_ENABLE;
private $cacheQuery = false;
/**
* KOnstruktor klasy
*
* @param mysql $dbh
* @param string $query
*/
public function __construct($dbh, $query) {
$this->query = $query;
$this->dbh = $dbh;
if(!$dbh) {
Core::SetAppSafeMode();
//throw new MysqlException("No db connection");
}
}
/**
* Zwraca tresc zapytania
*
* @return unknown
*/
public function GetQuery()
{
return $this->query;
}
/*Zamienia zmienne w zapytaniu na podane wartosci*/
public function BindParam($ph, $pv) {
$this->binds[$ph] = $pv;
return $this;
}
/*Wykonanie zapytania*/
public function Execute() {
$binds = func_get_args();
foreach($binds as $index => $name) {
$this->binds[$index + 1] = $name;
}
$cnt = count($binds);
$query = $this->query;
if (count($this->binds)>0) {
foreach ($this->binds as $ph => $pv) {
// $query = str_replace(":$ph", "'".mysql_escape_string($pv)."'", $query);
$query = str_replace(":$ph", '\''.sqlite_escape_string($pv).'\'', $query);
}
}
MFLog::Debug(__FUNCTION__.' query: '.$query);
if($this->dbh) {
$this->result = sqlite_query($this->dbh, $query);
if(!$this->result) {
throw new MysqlException($query . "<br /><br />" . mysql_error());
}
}
return $this;
}
/*Zwraca wiersz*/
public function FetchRow() {
if(!$this->result) {
throw new MysqlException("Query failed");
}
$this->SetCacheFile($this->query.'FetchRow');
if($this->cacheQuery==false) {
$result = sqlite_fetch_row($this->result);
}
else if ($this->cacheQuery==true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
$result = sqlite_fetch_row($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/*Zwraca wiersz jako tablice asocjacyjna*/
public function FetchAssoc() {
$this->SetCacheFile($this->query.'FetchAssoc');
if($this->cacheQuery==false) {
$result = sqlite_fetch_assoc($this->result);
}
else if(($this->cacheQuery==true && !$this->CacheCheck() && !Core::GetAppSafeMode())) {
$result = sqlite_fetch_assoc($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/*Zwraca ca<63>y wynik jako tablica asocjacyjna*/
public function FetchAllAssoc() {
$this->SetCacheFile($this->query.'FetchAllAssoc');
if($this->cacheQuery==false) {
$result = array();
while($row = $this->fetchAssoc()) {
$result[] = $row;
}
}
else if($this->cacheQuery==true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
$result = array();
$this->cacheQuery = false;
while($row = $this->fetchAssoc()) {
$result[] = $row;
}
$this->SetCacheFile($this->query.'FetchAllAssoc');
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/*Zwraca ca<63>y wynik jako tablica asocjacyjna*/
public function FetchAllRow() {
$this->SetCacheFile($this->query.'FetchAllRow');
if($this->cacheQuery==false) {
$result = array();
while($row = $this->fetchRow()) {
$result[] = $row;
}
}
else if($this->cacheQuery==true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
$result = array();
$this->cacheQuery = false;
while($row = $this->fetchRow()) {
$result[] = $row;
}
$this->SetCacheFile($this->query.'FetchAllRow');
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/*Zwraca liczbe wierszy*/
public function NumRows() {
if(!$this->result) {
throw new MysqlException("Query failed");
}
$this->SetCacheFile($this->query.'NumRows');
if($this->cacheQuery==false) {
$result = sqlite_num_rows($this->result);
}
else if($this->cacheQuery==true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
$result = sqlite_num_rows($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/*Zwraca wiersz w postaci tablicy*/
public function FetchArray() {
if(!$this->result) {
throw new MysqlException("Query failed");
}
$this->SetCacheFile($this->query.'FetchArray');
if($this->cacheQuery==false) {
$result = sqlite_fetch_array($this->result);
}
else if($this->cacheQuery==true && !$this->CacheCheck() && !Core::GetAppSafeMode()) {
$result = sqlite_fetch_array($this->result);
$this->CacheWrite($result);
} else {
$result = $this->CacheRead();
}
return $result;
}
/**
* Zwraca id ostatnio zmienionego rekordu
*
* @return integer
*/
public function GetInsertionId() {
if(!$this->result) {
throw new MysqlException("Query failed");
}
return sqlite_last_insert_rowid($this->dbh);
}
/**
* Zwraca liczb<7A> zmienionych rekord<72>w w ostatnim zapytaniu modyfikuj<75>cym dane.
*
* @return integer
*/
public function GetAffectedRows()
{
if(!$this->result) {
throw new MysqlException("Query failed");
}
return sqlite_affected_rows();
}
/**
* Sprawdza czy zaoytanie jest cacheowane
*
* @return boolean
*/
public function CacheCheck() {
if($this->cacheEnable == false || ($this->cacheEnable == true && (is_file($this->cachePath.$this->cacheFile) && filemtime($this->cachePath.$this->cacheFile) > (time() - $this->cacheTime)))) {
return true;
} else {
return false;
}
}
/**
* Zapisuje cache do pliku
*
* @param obj $result
*/
public function CacheWrite($result) {
if($this->cacheEnable != false) {
$records = serialize($result);
$fp = fopen($this->cachePath.$this->cacheFile, "w");
fputs($fp, $records);
fclose($fp);
$this->cacheQuery = false;
}
}
/**
* Odczytuje cache z pliku
*
* @return obj
*/
public function CacheRead() {
if(is_file($this->cachePath.$this->cacheFile)) {
$records = unserialize(file_get_contents($this->cachePath.$this->cacheFile));
$this->cacheQuery = false;
return $records;
} else {
throw new MysqlException('File does not exist: '.$this->cachePath.$this->cacheFile);
}
}
/**
* Uruchamia cacheowanie
*
* @param integer $time
*/
public function CacheStart($time=null) {
if($time!=null && $this->cacheEnable != false) {
$this->cacheTime = $time;
}
if($this->cacheEnable != false)
$this->cacheQuery = true;
else
$this->cacheQuery = false;
return $this;
}
/**
* Ustanawia nazw<7A> pliku cache
*
* @param unknown_type $fileName
*/
public function SetCacheFile($fileName) {
$this->cacheFile=md5($fileName);
}
}
class DBTemp extends DbSqlLite {
/**
* Pusty konstruktor
*
*/
public function __construct() {
$this->fileName = '../SqlLite/sql';
}
public function GetDbh() {
if(empty($this->dbh)) {
$this->Connect();
}
return $this->dbh;
}
}
?>

View File

@@ -0,0 +1,78 @@
<?php
/*
* Singleton slownika
*/
class Dictionary {
public static $rowSet = array();
public static $lang;
public static $allLangs = array();
public static function Init($lang, $location = '0') {
if (!in_array($lang, Router::$arrayLang)) {
throw new LangException('Incorrect language.');
}
self::$rowSet = MfDictionaryDAL::GetAllVariables($lang, 0, $location);
self::$lang = $lang;
self::$allLangs == array();
self::$allLangs[$lang] = self::$rowSet;
$langs = Router::$arrayLang;
//$langs = array_filter($langs, create_function('$x', 'return $x != "' . $lang . '";'));
$langs = array_filter($langs, function($x) {return $x != "' ".self::$lang.'"';});
foreach ($langs as $lang) {
self::$allLangs[$lang] = MfDictionaryDAL::GetAllVariables($lang, 0, $location);
}
//Utils::ArrayDisplay(self::$allLangs);
}
public static function Translate($keyword, $location = 0) {
self::CheckAndAdd($keyword, $location);
if($keyword!='' && isset(self::$rowSet[$keyword])) {
return nl2br(self::$rowSet[$keyword]);
//Utils::ArrayDisplay(self::$rowSet);
} else {
//Utils::ArrayDisplay(self::$rowSet);
return nl2br($keyword);
}
}
public static function CheckAndAdd($keyword, $location) {
// $lang = 'pl';
$lang = Router::$curLang;
if (!key_exists($keyword, self::$rowSet)) {
//Utils::ArrayDisplay(self::$rowSet);
$isVariables = MfDictionaryDAL::IsVariables($keyword, $lang, $location);
if (!$isVariables) {
$arrayLang = Router::GetArrayLang();
foreach ($arrayLang as $langItem) {
if ($langItem != 'pl') {
$replacement = $langItem.'_'.$keyword;
} else {
$replacement = $keyword;
}
$objDictionary = new MfDictionary(-1);
$objDictionary->SetId(-1);
$objDictionary->SetKeyword($keyword);
$objDictionary->SetReplacement($replacement);
$objDictionary->SetLang($langItem);
$objDictionary->SetLocation($location);
//Utils::ArrayDisplay($objDictionary);
MfDictionaryDAL::Save($objDictionary);
}
}
}
}
}
?>

View File

@@ -0,0 +1,39 @@
<?php
/**
* Description of Enviromentclass
*
* @author Pawel
*/
class Enviroment {
public static function CheckMagicQuotes() {
return get_magic_quotes_gpc();
}
public static function CheckSoapClient() {
if(class_exists('SoapClient')) {
return true;
} else {
return false;
}
}
public static function CheckGDSupport() {
if (extension_loaded('gd') && function_exists('gd_info')){
return true;
} else {
return false;
}
}
public static function CheckMemcache() {
if(class_exists('Memcache')) {
return true;
} else {
return false;
}
}
}
?>

View File

@@ -0,0 +1,162 @@
<?
/**
* $Id: Exception.class.php 863 2008-07-08 08:05:50Z pawy $
* Obsluga wyjatkow jadra
*
*/
class CoreException extends Exception {
/**
* Backtrace
*
* @var array
*/
public $backtrace;
/**
* Konstruktor
*
* @param string $message
* @param integer $code
*/
public function __construct($message=false, $code=false) {
$this->message = $message;
$this->backtrace = debug_backtrace();
}
public function __toString() {
$out = '<br />';
$c = count($this->backtrace);
foreach($this->backtrace as $line) {
$out .= '<b>[ #'. $c.' ]</b><br /> ';
$out .= '<b>[ method ]</b>' . $line['function'] . '()<br /><b>[ file ]</b> ' . $line['file'] . ' (line: ' . $line['line'] .')<br /><br />';
$c--;
}
$out .= '<br />';
return $out;
}
}
/**
* Obsluga wyjatkow plikowych
*
*/
class FileException extends CoreException {
/**
* Backtrace
*
* @var array
*/
public $backtrace;
/**
* Konstruktor
*
* @param string $message
* @param integer $code
*/
public function __construct($message=false, $code=false) {
$this->message = $message;
$this->backtrace = debug_backtrace();
}
}
/**
* Obsluga wyjatkow mysql
*
*/
class MysqlException extends FileException {
/**
* Backtrace
*
* @var array
*/
public $backtrace;
/**
* Konstruktor
*
* @param string $message
* @param integer $code
*/
public function __construct($message=false, $code=false) {
if(!$message) {
$this->message = mysql_error();
}
else
$this->message = $message;
if(!$code) {
$this->code = mysqli_errno(1);
}
else
$this->code = $code;
$this->backtrace = debug_backtrace();
}
}
/**
* Obsluga wyjatkow autoryzacji
*
*/
class AuthException extends MysqlException {
/**
* Backtrace
*
* @var array
*/
public $backtrace;
/**
* Konstruktor
*
* @param string $message
* @param integer $code
*/
public function __construct($message=false, $code=false) {
$this->backtrace = debug_backtrace();
}
}
/**
* Obsluga wyjatkow uzytkownika
*
*/
class UserException extends AuthException {
/**
* Backtrace
*
* @var array
*/
public $backtrace;
/**
* Konstruktor
*
* @param string $message
* @param integer $code
*/
public function __construct($message=false, $code=false) {
$this->message = $message;
$this->backtrace = debug_backtrace();
}
}
/**
* Wyjatek ApiException.
*
* @author WP
*/
class ApiException extends Exception {
}
/**
* Wyjatek SecurityException.
*
* @author WP
*/
class SecurityException extends ApiException {
}
?>

View File

@@ -0,0 +1,49 @@
<?php
class FileGenerator {
private $lines = array();
public function __construct() {
}
public function AddLine($string) {
$this->lines[] = $string;
}
public function GenerateFileContents() {
$output = null;
if(count($this->lines)>1) {
foreach($this->lines as $line) {
$output .= $line.'\n';
}
} else {
$output = $this->lines[0];
}
return $output;
}
public function SaveFile($file) {
if (is_writable($file)) {
if (!$fh = fopen($file, 'w')) {
throw new UserException('Nie moge utworzyc pliku: '.$file);
}
if (fwrite($fh, $this->GenerateFileContents()) === FALSE) {
throw new UserException('Nie moge pisac do pliku pliku: '.$file);
}
fclose($fh);
} else {
throw new UserException('Nie moge pisac do pliku: '.$file);
}
}
}
?>

View File

@@ -0,0 +1,654 @@
<?
/**
* Klasa FrontControllera
*
*/
class FrontController {
private $loadError = false;
/**
* Parametry przekazane przez Router
*
* @var array
*/
private $route;
/**
* Katalog z kontrolerami
*
* @var string
*/
private $directory = 'controller';
/**
* Kontroler do uruchomienia
*
* @var string
*/
private $controller;
/**
* Metoda do wywolania
*
* @var string
*/
private $method;
/**
* Parametry dla metody
*
* @var array
*/
private $param;
/**
* Obiekt kontrolera
*
* @var Object
*/
private $controllerObj;
/**
* Domyslny kontroler
*
* @var string
*/
private $defaultController = 'IndexController';
/**
* Konfiguracja kontrolera
*
* @var array
*/
private $config;
/**
* Delimiter tytulu strony
*
* @var string
*/
private $titleDelimiter;
/**
* Czy tytul ma byc generowany w odwrotnej kolejnosci
*
* @var bool
*/
private $titleReverse = false;
/**
* Konstruktor
*
*/
public function __construct() {
$this->route = Router::GetParam();
//print_r($this->route);
if(isset($this->route['controller'])) {
$this->controller = ucfirst($this->route['controller']);
}
if(isset($this->route['param'])) {
$this->param = $this->route['param'];
}
if(isset($this->route['method'])) {
$this->method = ucfirst($this->route['method']);
$this->param['methodToRun'] = $this->method;
}
if(isset($this->route['config'])) {
$this->config = $this->route['config'];
}
}
public static function dispatchChecker($smarty, $tplFile, $param, $lifetime) {
if(!$smarty->CacheControl($tplFile, array('cache_id'=> md5($param), 'lifetime'=>$lifetime)) && !Core::GetAppSafeMode()) {
$smarty->CacheControl($tplFile, array('cache_id'=> md5($param), 'write'=>true));
return true;
} else {
return false;
}
}
public function dispatchTemplate($smarty, $tplFile, $param, $lifetime) {
}
/**
* Zmienia domyslny katalog z kontrolerami
*
* @param string $dir
*/
public function SetDirectory($dir) {
$this->directory = $dir;
}
/**
* Laduje plik z klasa kontrolera
*
*/
private function LoadController() {
//print_r(Config::Get('PATH_MAIN_APP').$this->directory.'/'.str_replace('_', '/', ucfirst($this->controller)).'.php');
if(is_file(Config::Get('PATH_MAIN_APP').$this->directory.'/'.str_replace('_', '/', ucfirst($this->controller)).'.php')) {
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/'.str_replace('_', '/', ucfirst($this->controller)).'.php');
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/SharedController.php');
MFLog::Debug('Loading controller: '.$this->controller);
} else {
//print_r(Config::Get('PATH_MAIN_APP').$this->directory.'/'.ucfirst($this->defaultController).'.php');
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/'.ucfirst($this->defaultController).'.php');
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/SharedController.php');
MFLog::Debug('Unable to load controller: '.$this->controller.' Loading controller: '.$this->defaultController);
$this->controller = $this->defaultController;
$this->loadError = true;
}
}
/**
* Laduje plik z klasa kontrolera
*
*/
private function LoadModule() {
//print_r(Config::Get('PATH_MAIN_APP').$this->directory.'/'.$this->config['module'].'/'.str_replace($this->config['module'].'_', '', ucfirst($this->controller)).'.php');
if(is_file(Config::Get('PATH_MAIN_APP').$this->directory.'/'.$this->config['module'].'/'.str_replace($this->config['module'].'_', '', ucfirst($this->controller)).'.php')) {
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/'.$this->config['module'].'/'.str_replace($this->config['module'].'_', '', ucfirst($this->controller)).'.php');
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/SharedController.php');
MFLog::Debug('Loading module: '.$this->config['module'].': '.$this->controller);
} else {
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/'.ucfirst($this->defaultController).'.php');
Core::RequireOnce(Config::Get('PATH_MAIN_APP').$this->directory.'/SharedController.php');
$this->controller = $this->defaultController;
MFLog::Debug('Unable to load module, Loading controller: '.$this->controller);
}
}
/**
* Uruchamia obiekt kontrolera
*
*/
private function RunController() {
$exp = explode('_', $this->controller);
$className = $this->controller;
if ($this->ValidControllerClass($className)) {
$this->controllerObj = new $className();
$method = $this->method;
if((!method_exists($this->controllerObj, $method) && !method_exists($this->controllerObj, $method.'Action'))) {
$this->method = 'Index';
}
if($this->loadError && ($this->method=='Index' && $this->route['param']['urlParam']!='')) {
//Utils::ArrayDisplay($this->route, __FILE__.' Line: '.__LINE__);
$this->method = 'Error404';
}
} else {
throw new Exception('Brak klasy lub brak dziedziczenia!');
}
}
/**
* Uruchamia obiekt modulu
*
*/
private function RunModule() {
$className = $this->controller;
if ($this->ValidControllerClass($className, true)) {
$this->controllerObj = new $className();
$method = $this->method;
if(!method_exists($this->controllerObj, $method) && !method_exists($this->controllerObj, $method.'Action')) {
$this->method = 'Index';
}
} else {
throw new Exception('Brak klasy lub brak dziedziczenia!');
}
}
/**
* Przypisuje delimiter tytulu strony
*
* @param string $titleDelimiter
*/
public function SetTitleDelimiter($titleDelimiter) {
$this->titleDelimiter = $titleDelimiter;
}
/**
* Dodaje element tytulu strony
*
* @param string $title
*/
public function AddTitle($title) {
//$t = Registry::Get('title');
//$t[] = $title;
//Registry::Remove('title');
//Registry::Set('title', $t);
$headers = Registry::Get('headers');
$headers['title'][] = $title;
Registry::Remove('headers');
Registry::Set('headers', $headers);
}
private function GenerateScriptsVar($t) {
$script = array();
if ($t && is_array($t) && sizeof($t)) {
ksort($t);
if (count($t)>0) {
foreach($t as $prio) {
if ( $prio && is_array($prio) && sizeof($prio) > 0) {
foreach ($prio as $item) {
//Utils::ArrayDisplay($item);
if(isset($item['file']) && $item['file']!='' && !preg_match("((http)(.*))", $item['file'])) {
$item['file'] = URL_STATIC_CONTENT.'/script/'.$item['file'];
}
$script[] = $item;
}
}
}
}
} else {
$script = array();
}
return $script;
}
private function GenerateCSSVar($t) {
$script = array();
if ($t && is_array($t) && sizeof($t)) {
ksort($t);
if (count($t)>0) {
foreach($t as $prio) {
if ( $prio && is_array($prio) && sizeof($prio) > 0) {
foreach ($prio as $item) {
if($item['file']!='' && !preg_match("((http)(.*))", $item['file'])) {
$item['file'] = URL_STATIC_CONTENT.'/css/'.$item['file'];
}
$script[] = $item;
}
}
}
}
} else {
$script = array();
}
return $script;
}
/**
* Generuje liste skryptow do wyswietlenia w naglowku
*
*/
public function GenerateScripts() {
$t = Registry::Get('javascript');
$script = $this->GenerateScriptsVar($t);
$smarty = Registry::Get('smarty');
$smarty->assign('javaScript', $script);
$t = Registry::Get('footerJavascript');
$script = $this->GenerateScriptsVar($t);
$smarty = Registry::Get('smarty');
$smarty->assign('footerJavaScript', $script);
}
/**
* Generuje liste CSS do wyswietlenia w naglowku
*
*/
public function GenerateCSS() {
$t = Registry::Get('headerCSS');
$script = $this->GenerateCSSVar($t);
$smarty = Registry::Get('smarty');
$smarty->assign('headerCSS', $script);
}
/**
* Generuje opis strony
*
* @return string
*/
private function GenerateDescription() {
$headers = Registry::Get('headers');
if(isset($headers['description'])) {
$desc = $headers['description'];
$headers['description']=null;
Registry::Remove('headers');
Registry::Set('headers', $headers);
if(is_array($desc[0])) {
return "";
} else {
$desc = strtr($desc[0], "'", "`");
$desc = stripslashes($desc);
return $desc;
}
}
}
/**
* Odwraca kolejnosc generowania tytulu strony
*
*/
private function ReverseTitle() {
$t = null;
$headers = Registry::Get('headers');
if(isset($headers['title'])) {
$t = $headers['title'];
}
//Utils::ArrayDisplay($headers);
if(is_array($t)) {
$t = array_reverse($t);
}
$headers['title']=$t;
Registry::Remove('headers');
Registry::Set('headers', $headers);
}
/**
* Zmienia parametr generowania tytulu strony
*
*/
public function FlipTitle() {
$this->titleReverse = true;
}
/**
* Generuje tytul strony
*
* @return string
*/
private function GenerateTitle() {
$headers = Registry::Get('headers');
//Utils::ArrayDisplay($headers);
$t = $headers['title'];
if(is_array($t) && count($t)>1) {
$title = implode($this->titleDelimiter, $t);
} else if (is_array($t) && count($t) == 1) {
$title = $t[0];
} else {
$title = '';
}
$headers['title']=null;
Registry::Remove('headers');
Registry::Set('headers', $headers);
return $title;
}
/**
* Generuje strone
*
* @return string
*/
public function Dispatch() {
$contentCheckout = true;
$smarty = Registry::Get('smarty');
$this->devMode();
$smarty->assign('controller', strtolower(str_replace('Controller', '', $this->controller)));
$smarty->assign('method', strtolower($this->method));
//Utils::ArrayDisplay($this->param);
if(is_array($this->param)) {
$cacheParam = implode('-', $this->param);
} else {
$cacheParam = $this->method;
}
if(isset($_POST)) {
foreach($_POST as $postParam=>$postValue) {
//Utils::ArrayDisplay($postParam);
//Utils::ArrayDisplay($postValue);
if (!is_array($postValue)) {
$cacheParam.='-'.$postParam.'-'.$postValue;
}
}
}
$cacheParam = md5($cacheParam);
if(isset($this->config['module']) && $this->config['module'] != '') {
$this->LoadModule();
$this->RunModule();
$partialPath = ucfirst($this->config['module']).'/';
$executeAdditional = true;
if(isset($this->config['actionSet']) && is_array($this->config['actionSet'])) {
$this->controllerObj->SetActionSet($this->config['actionSet']);
}
} else {
$partialPath = null;
$this->LoadController();
$this->RunController();
$executeAdditional = false;
if(isset($this->config['actionSet']) && is_array($this->config['actionSet'])) {
$this->controllerObj->SetActionSet($this->config['actionSet']);
$executeAdditional = true;
}
}
$method = $this->method;
$this->controllerObj->SetSmarty($smarty);
$this->controllerObj->partialTemplate = $method.'.tpl';
$templatePartialPath = null;
if(isset($this->config['module'])) {
$templatePartialPath = $this->config['module'].'/'.str_replace($this->config['module'].'_', '', str_replace('Controller', '', $this->controller));
} else {
$templatePartialPath = str_replace('Controller', '', $this->controller);
}
$this->controllerObj->templatePath = 'partial/' . str_replace('_', '/', $templatePartialPath) . '/';
if(Config::Get('SMARTY_INTERNAL_CACHING') == false) {
$smarty->caching = Config::Get('SMARTY_CACHING_METHOD');
}
$template = Registry::Get('smartyTemplate');
if((Config::Get('SMARTY_INTERNAL_CACHING') == false && !$smarty->CacheControl($template, array('cache_id'=>$this->controller.$this->method.md5($cacheParam), 'lifetime'=>CacheParam::Get('global')))) || Config::Get('SMARTY_INTERNAL_CACHING') != false) {
//echo"pyk";
if(Config::Get('SMARTY_INTERNAL_CACHING') == false) {
$smarty->caching = 0;
}
$this->controllerObj->preDispatch($this->param);
//$smarty->cache_lifetime = CacheParam::Get('global');
if($this->controllerObj->GetActionRedirect()!=true && $this->controllerObj->GetActionRedirect()!=false) {
$method = $this->controllerObj->GetActionRedirect();
}
$initMethod = $method . 'Init';
if (method_exists($this->controllerObj, $initMethod)) {
$this->controllerObj->$initMethod($this->param);
}
// -->
//--MAKL: odpalam wczesniej
if($executeAdditional == true) {
$this->controllerObj->ExecuteAdditionalActions($this->param);
}
if((!$this->controllerObj->Init($method, $cacheParam) || $this->controllerObj->CheckLiveMethod($method, $this->param)) && $this->controllerObj->GetActionRedirect()!=true) {
if($this->controllerObj->CheckLiveMethod($method, $this->param)) {
$smarty->cache_lifetime = 0;
}
$methodAction = $method . 'Action';
$this->controllerObj->$methodAction($this->param);
$methodRun = true;
Registry::Set('methodRun',$methodRun);
} else {
$cachedMethod = $method . 'Cached';
if (method_exists($this->controllerObj, $cachedMethod)) {
$this->controllerObj->$cachedMethod($this->param);
}
}
//Utils::ArrayDisplay($this->controllerObj);
//Utils::ArrayDisplay($this->controllerObj->GetRedirect());
$redirectArray = $this->controllerObj->GetRedirect();
//--MAKL: Przniosłem do odpalenia wczesniej
if(!isset($this->controllerObj->content) && ($redirectArray['time']==='' || ($redirectArray['time']!=='' && $redirectArray['time']>0))){
//$smarty->assign('breadCrumbs', $this->controllerObj->GetBreadCrumbs());
//$smarty->cache_lifetime = $this->controllerObj->cacheTime;
//echo $smarty->cache_lifetime;
$this->controllerObj->content = $smarty->fetch($this->controllerObj->templatePath.$this->controllerObj->partialTemplate, md5($method.$cacheParam));
//echo $this->controllerObj->templatePath.$this->controllerObj->partialTemplate;
}
$contentCheckout = true;
if($this->controllerObj->content=='') {
$contentCheckout = false;
}
$smarty->assign('content', $this->controllerObj->content);
$this->controllerObj->postDispatch($this->param);
} else {
//echo"myk";
if(Config::Get('SMARTY_INTERNAL_CACHING') == false) {
if($executeAdditional == true) {
$actionSet = $this->controllerObj->GetActionSet();
$newActionSet = array();
foreach($actionSet as $set) {
if(isset($set['liveMethod']) && $set['liveMethod']==1) {
$newActionSet[] = $set;
}
}
if(count($newActionSet)>0) {
$this->controllerObj->SetActionSet($newActionSet);
$this->controllerObj->ExecuteAdditionalActions($this->param);
}
}
}
}
// -->
$redirectArray = $this->controllerObj->GetRedirect();
$smarty->assign('headerRedirect', $redirectArray);
if(isset($redirectArray['time']) && $redirectArray['time']==0 && isset($redirectArray['url']) && $redirectArray['url']!='') {
// Header('Location: '.$redirectArray['url']);
Header('Location: '.$redirectArray['url'], true, $redirectArray['code']);
die();
}
if($this->titleReverse == true) {
$this->ReverseTitle();
}
$smarty->assign('pageTitle', $this->GenerateTitle());
$smarty->assign('pageDescription', $this->GenerateDescription());
$smarty->assign('pageHeaders', Registry::Get('headers'));
$this->GenerateScripts();
$this->GenerateCSS();
//echo $smarty->cache_lifetime;
$template = Registry::Get('smartyTemplate');
if(Config::Get('SMARTY_INTERNAL_CACHING') == false) {
$smarty->caching = Config::Get('SMARTY_CACHING_METHOD');
}
if($this->controllerObj->disableTemplates == false && ($this->controllerObj->CheckLiveMethod($method, $this->param) || !$smarty->CacheControl($template, array('cache_id'=>$this->controller.$this->method.md5($cacheParam), 'lifetime'=>CacheParam::Get('global'))))) {
if(!Core::GetAppSafeMode()) {
// echo"pyk";
//if($contentCheckout!=false) {//echo"renegerate";
//$smarty->CacheControl($template, array('cache_id'=>$this->controller.$this->method.md5($cacheParam), 'write'=>true,'methodRun' => true));
//} else {
// $cacheFile = $smarty->generateFileName($this->controller.$this->method.md5($cacheParam), $template);
// $smarty->touchCacheFile($cacheFile);
//}
//return $smarty->Display($template, $this->controller.$this->method.md5($cacheParam), $this->controller.$this->method.md5($cacheParam));
//if($this->controllerObj->CheckLiveMethod($method, $this->param)) {
//$a = $this->controllerObj->content;
//} else {
$a = $smarty->Fetch($template, $this->controller.$this->method.md5($cacheParam));
//}
//echo"pyk".$template;
if ($this->controllerObj->utf8) {
$a = iconv('iso-8859-2', 'utf-8', $a);
}
echo $a;
} else {
//totalny wylot
Header('Location: '.Config::Get('FATAL_ERROR_URL'));
}
} else if($this->controllerObj->disableTemplates == false) {
$a = $smarty->Fetch($template, $this->controller.$this->method.md5($cacheParam));
if ($this->controllerObj->utf8) {
$a = iconv('iso-8859-2', 'utf-8', $a);
}
echo $a;
}
}
/**
* Sprawdza czy klasa istnieje i ma poprawne dziedziczenie.
*
*/
private function ValidControllerClass($className, $module = false) {
if (!class_exists($className)) {
return false;
}
if (!class_parents($className) == Array('MainController'=>'MainController', 'Controller'=>'Controller')) {
if ($module !== true || !class_parents($className) == Array('ModuleController' => 'ModuleController', 'MainController'=>'MainController', 'Controller'=>'Controller')) {
return false;
}
}
if (!class_implements($className) == Array('ControllerInterface'=>'ControllerInterface')) {
return false;
}
return true;
}
/**
* Generuje flagę devMode
*
*/
public function devMode() {
$smarty = Registry::Get('smarty');
if (defined('DEVELOPER_MODE')) {
$smarty->assign('devMode', DEVELOPER_MODE);
} else {
$smarty->assign('devMode', false);
}
}
}
?>

View File

@@ -0,0 +1,21 @@
<?
/*
* Klasa buttonow html
*/
class HtmlButton extends HtmlElement {
/*
* Pusty konstruktor
*/
public function __construct() {
}
public function AddButton($id, $class, $text, $onclick, $rel=null) {
$this->AddElement(array('tag'=>'input', 'type'=>'button', 'id'=>$id, 'class'=>$class, 'text'=>$text, 'onclick'=>$onclick, 'rel'=>$rel));
}
}

View File

@@ -0,0 +1,34 @@
<?php
/*
* Klasa elementow html
*/
class HtmlElement {
private $elements;
/*
* Pusty konstruktor
*/
public function __construct() {
}
public function GetElements() {
return $this->elements;
}
public function SetElements($elements) {
$this->elements = $elements;
}
public function AddElement($element) {
$this->elements[] = $element;
}
}
?>

View File

@@ -0,0 +1,37 @@
<?
/**
* Interfejs do obs<62>ugi dost<73>pu do danych dla wybranego obiektu
*
*/
interface IDefaultDAL {
/**
* Zapis obiektu do bazy
*
* @param Obj $obj
*/
public static function Save($obj);
/**
* Usuni<6E>cie rekordu/obiektu z bazy
*
* @param int $id
*/
public static function Delete($id);
/**
* Pobranie obiektu na podstawie ID
*
* @param int $id
*/
public static function GetById($id);
/**
* Pobranie wszystkich obiekt<6B>w/rekord<72>w
*
*/
public static function GetArrayObjAll();
public static function Insert($obj);
public static function Update($obj);
}
?>

204
core/class/MFLog.class.php Normal file
View File

@@ -0,0 +1,204 @@
<?php
/*
* Log frameworka
*/
class MFLog {
private static $logLevel = 0;
private static $logLevels = array('0'=>'DEBUG','1'=>'INFO','2'=>'WARN','3'=>'ERROR', '4'=>'FATAL');
public static $fileLog = false;
private static $consoleLog = false;
private static $consolePrivateIp = null;
private static $sqliteLog = false;
public function __construct() {
}
/*
* UStawianie poziomu logowania
*/
public static function SetLogLevel($level) {
self::$logLevel = $level;
}
/*
* Metoda Debug
*/
public static function Debug($data) {
//self::DataLog($data, 0);
}
/*
* Metoda Info
*/
public static function Info($data) {
self::DataLog($data, 1);
}
/*
* Metoda Warn
*/
public static function Warn($data) {
self::DataLog($data, 2);
}
/*
* Metoda Error
*/
public static function Error($data) {
self::DataLog($data, 3);
}
/*
* Metoda Fatal
*/
public static function Fatal($data) {
self::DataLog($data, 4);
}
/*
* Logowanie do pliku
*/
private static function FileLog($data, $type) {
$logger = LoggerManager::getLogger(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : __FILE__);
switch ($type) {
case 0:
$logger->warn($data);
break;
case 1:
$logger->info($data);
break;
case 2:
$logger->warn($data);
break;
case 3:
$logger->error($data);
break;
case 4:
$logger->fatal($data);
break;
}
}
/*
* Logowanie an konsole
*/
private static function ConsoleLog($data, $type) {
if(self::$consolePrivateIp==null || (self::$consolePrivateIp!=null && $_SERVER['REMOTE_ADDR'] == self::$consolePrivateIp)) {
if($type<4) {
Core::LoadPlugin('fb');
fb($data, eval('return FirePHP::'.str_replace('DEBUG', 'LOG', self::$logLevels[$type]).';'));
}
}
}
/*
* Metoda proxy logowania
*/
private static function DataLog($data, $type) {
if(self::$consoleLog == true) {
self::ConsoleLog($data, $type);
}
if(self::$fileLog == true) {
self::FileLog($data, $type);
}
if(self::$sqliteLog == true) {
self::SqlliteLog($data, $type);
}
}
/*
* Ustawia logowanie do pliku
*/
public static function SetFileLog($set) {
self::$fileLog = $set;
}
/*
* Ustawia logowanie na konsole
*/
public static function SetConsoleLog($set) {
self::$consoleLog = $set;
}
public static function DbLog($message, $server = null, $type = 0) {
$log = new MfDbLog();
$log->SetMessage($message);
$log->SetServer($server);
$log->SetType($type);
MfDbLogDAL::Save($log);
}
public static function Pack() {
//Core::RequireOnce('../core/lib/phpmailer/class.phpmailer.php');
$fileArray = array();
$zipfile = date("Ymd").".zip";
$zip = new ZipArchive;
$return = '';
//if ($zip->open('../logs/'.$zipfile, ZipArchive::CREATE) === TRUE) {
if ($handle = opendir('../logs')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != ".svn" && date("Ymd", filemtime('../logs/'.$file))==date("Ymd")) {
//echo "$file was last modified: " . date("Ymd", filemtime('../logs/'.$file))."<br>";
// $zip->addFile('../logs/'.$file, $file);
// $fileArray[] = '../logs/'.$file;
$return .= file_get_contents('../logs/'.$file);
}
}
closedir($handle);
}
//$zip->close();
//}
return $return;
// if(is_file('../logs/'.$zipfile)) {
// $mail = new PHPMailer();
// $mail->AddAddress('pawy@formix.pl');
//
//
// $mail->Username = Config::Get('MAIL_USERNAME');
// $mail->Password = Config::Get('MAIL_PASSWORD');
// $mail->Host = Config::Get('MAIL_HOST');
// $mail->SMTPAuth = true;
// $mail->Mailer = 'smtp';
//
// $mail->From = Config::Get('SERVER_MAIL_FROM');
// $mail->FromName = 'Turystyka.wp.pl';
// $mail->WordWrap = 50; // set word wrap
// $mail->IsHTML("type_html"); // send as HTML
// $mail->CharSet = "iso-8859-2";
//
//
//
// $mail->Subject = 'Logi '.date("Ymd");
// $mail->AddAttachment('../logs/'.$zipfile, $zipfile);
//
// $mailingState = $mail->Send();
//
// unlink('../logs/'.$zipfile);
// }
//
// if(!$mail->ErrorInfo) {
// foreach($fileArray as $file) {
// unlink($file);
// }
// } else {
// self::Error('Cant email logs!');
// }
}
public static function SqlliteLog($data, $type) {
$log = new MfSqliteLog();
$log->SetType($type);
$log->SetMessage($data);
$dalObj = MfSqliteLogDAL::GetDalDataObj();
$dalObj->setObj($log);
MfSqliteLogDAL::Save($dalObj);
}
}
?>

101
core/class/Mailer.class.php Normal file
View File

@@ -0,0 +1,101 @@
<?php
require_once("../core/lib/phpmailer/class.phpmailer.php");
/**
* Description of Mailer
*
* @author KoPi
*/
class Mailer extends PHPMailer{
public static $c_name = '__img_mail_container_3456__';
public static $attachImages = true;
private $head;
private $bottom;
function __construct() {
$this->Config();
$this->SetDefaultHtml();
}
private function Config()
{
$this->Host='mediaflex.pl';
$this->IsSMTP();
$this->SetLanguage('pl', '../core/lib/phpmailer/language/');
$this->Mailer='smtp';
$this->Username = 'egw@mediaflex.pl';
$this->Password = 'EgW_2009';
$this->SMTPAuth = true;
$this->From= 'egw@mediaflex.pl';
$this->FromName = 'NASZA MEDYCYNA';
$this->ContentType = 'text/html';
$this->Ishtml(true);
}
private function SetDefaultHtml()
{
}
public function SendEmail($body,$altbody,$subject,$emails = null)
{
$this->Subject = $subject;
if(is_array($emails))
{
foreach ($emails as $index => $value) {
$this->AddAddress($value);
}
}
else {
if(!empty($emails)) {
$this->AddAddress($emails);
}
}
$this->Body = $this->head . $body . $this->bottom;
$this->AltBody = $altbody;
if(Mailer::$attachImages) {
$imgContainer = Registry::Get(Mailer::$c_name);
if(!empty($imgContainer)) {
foreach($imgContainer as $img) {
$this->AddEmbeddedImage(PATH_STATIC_CONTENT . 'image' . DIRECTORY_SEPARATOR . $img['img'], $img['name'], $img['img']);
}
}
}
if(!$this->Send())
{
return false;
}
else
{
$this->ClearAttachments();
$this->ClearAddresses();
$this->ClearAttachments();
return true;
}
}
public function GetHead() {
return $this->head;
}
public function SetHead($head) {
$this->head = $head;
}
public function GetBottom() {
return $this->bottom;
}
public function SetBottom($bottom) {
$this->bottom = $bottom;
}
}
?>

View File

@@ -0,0 +1,530 @@
<?php
/**
* Description of MainController
*
* @author MAKL
*/
abstract class MainController extends Controller {
protected $user;
public function AdminLoginRedirectAction($param) {
$this->AddRedirect(Router::GenerateUrl(array('login' => 'index')), 0);
}
/**
* Dodatkowy starter kontrolera
*
*/
protected function Run($param = array()) {
//$this->SetAjaxRender();
$urlMain = URL_MAIN;
$this->smarty->assign('urlMain', $urlMain);
$this->smarty->assign('pathStatic', PATH_STATIC_CONTENT);
// $logger = LoggerManager::getLogger(__CLASS__ . ' - ' . __METHOD__);
// $logger->debug(' ' . serialize($param));
//Utils::ArrayDisplay($param);
$location = Config::Get('site');
switch ($location) {
case 'Strona':
session_start();
if ($param['lang'] == '') {
$param['lang'] = 'pl';
Router::$curLang = $param['lang'];
}
$searchLabel = 'search'.$param['lang'];
$this->smarty->assign('searchLabel', $searchLabel);
$analyticsCode = Registry::Get('analytics_code');
$this->smarty->assign('analyticsCode', $analyticsCode);
//=====Coockie========================================================
if (isset($_COOKIE['polityka_akceptacja'])) {
$polityka_akceptacja = $_COOKIE['polityka_akceptacja'];
}
if (isset($polityka_akceptacja)) {
$this->smarty->assign('polityka_akceptacja', true);
}
//--------------------------------------------------------------------
if (!isset($param['idStructure'])) {
$getContent = true;
}
Dictionary::Init($param['lang']);
$this->GetRedirectInfo();
$this->AddTitle(Dictionary::Translate(HEAD_TITLE));
if (isset($param['idStructure']) && !Utils::CheckPublication($param['idStructure'], 'mf_structure', 'id_mf_structure')) {
//$logger->debug('nie ma takiej strony, przekierowanie');
$this->addRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('mainUrl', array()), 0);
}
$this->smarty->assign('lang', $param['lang']);
$this->smarty->assign('title', Dictionary::Translate(HEAD_TITLE));
//====Script=Loader=========================================================
$this->addScript('jQuery/jquery.js', 'file', 'top', 1);
$this->addScript('jQuery/jquery-migrate.min.js', 'file', 'top', 2);
// $this->AddScript('jQuery/jquery-ui.min.js', 'file', 'top', 7);
// $this->AddScript('jQuery/jquery.ui.datepicker-pl.js', 'file', 'top', 7);
$this->AddScript('jQuery/jquery.swipebox.js', 'file', 'top', 2);
$this->AddScript('gray.js', 'file', 'top', 3);
$this->AddScript('jQuery/bjqs-1.3.js', 'file', 'top', 4);
$this->AddScript('init.js', 'file', 'top', 5);
//$this->AddScript('doubletaptogo.js', 'file', 'top', 6);
$this->AddScript('jQuery/jquery.sticky.js', 'file', 'top', 7);
$this->addScript('jQuery/jquery.validate.js', 'file', 'top', 8);
$this->addScript('jQuery/jquery.flexslider.js', 'file', 'top', 9);
$this->addScript('jQuery/jquery.scrollex.min.js', 'file', 'top', 10);
$this->AddScript('jQuery/jquery.scrollme.js', 'file', 'top', 11);
$this->AddScript('jQuery/jquery.transit.min.js', 'file', 'top', 12);
$this->AddScript('jQuery/jquery.visible.js', 'file', 'top', 13);
$this->AddScript('bootstrap/bootstrap.js', 'file', 'top', 14);
//--------------------------------------------------------------------------
//===Run=Structure=element==================================================
if (isset($param['idStructure'])) {
$objElement = StructureDAL::GetById($param['idStructure'], true);
if (!is_object($objElement)) {
MFLog::Debug('brak obiektu, przekierowanie');
$this->addRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('Index', array()), 0);
}
$router = MfRouterDAL::GetById($objElement->GetIdRouter());
$this->smarty->assign('idModule', $router->GetIdMfModule());
$param['idModule'] = $router->GetIdMfModule();
//Utils::ArrayDisplay($param);
//Utils::ArrayDisplay($objElement);
//==TODO==Zmianić=na=automat========================
if (isset($param['idModule']) && $param['idModule'] == 16) {
$this->smarty->assign('showGallery', true);
}
//--end-TODO----------------------------------------
$this->smarty->assign('title', $objElement->GetName());
$this->smarty->assign('objElement', $objElement);
$this->smarty->assign('contentObj', $objElement->GetContent());
$this->AddTitle($objElement->GetName());
$this->smarty->assign('labelDetal', $objElement->GetUrlLabel().'Detail');
$this->smarty->assign('labelPagi', $objElement->GetUrlLabel().'Page');
$this->smarty->assign('labelUrl', $objElement->GetUrlLabel());
$this->smarty->assign('urlPostOnPage', Router::GenerateUrl($objElement->GetUrlLabel()));
$this->smarty->assign('urlPagi', $objElement->GetUrl());
$param['idContent'] = $objElement->GetIdContent();
if (isset($param['urlDetailLabel'])) {
$this->smarty->assign('labelDetal', $param['urlDetailLabel']);
}
//==meta-do-elementu======================
$objMetaTag = MfMetaTagDAL::GetResult(array('id_source' => $param['idStructure'], 'source_type' => "'mf_structure'"), array());
if (isset($objMetaTag[0])) {
$objMetaTag = $objMetaTag[0];
$descriptionObj = $objMetaTag->GetDescriptionObj();
$this->smarty->assign('metaDescription', $descriptionObj->GetDescription());
$this->smarty->assign('metaKeywords', $descriptionObj->GetKeywords());
$this->smarty->assign('statistic', $descriptionObj->GetStatistic());
} else {
$this->smarty->assign('metaDescription', HEAD_DESCRIPTION);
$this->smarty->assign('metaKeywords', HEAD_KEYWORDS);
$this->smarty->assign('statistic', '');
}
//====Moduły=actionSet==================================================================================================
/**
* Pobieranie bazy i generowanie okienek modułowych
* TODO: Poprawić Kategorie
*
*/
$config = unserialize($router->GetConfig());
//Utils::ArrayDisplay($config);
$moduleAdd = true;
//Sprawdzanie czy jest url w parami jesli tak to nie jest to główny router i nie wyswietla modułów
//Potrzebne gdy wyswietlamy listę i mamy paginację lub element/detal
// if (isset($param[$router->GetUrl()])) {
// $moduleAdd = false;
// }
$actionSet = array();
$moduleSharedVariableArray = array();
$arrayModuleIdName = array();
$arrayModuleCategoryByModuleId = array();
if (isset($config['actionSet']) && $moduleAdd) {
//Utils::ArrayDisplay($router->GetName());
//Utils::ArrayDisplay($router);
if (is_array($config['actionSet'])) {
foreach ($config['actionSet'] as $addModulekey => $addModuleValue) {
if ($addModuleValue['modulePublication']>0) {
//Utils::ArrayDisplay($addModulekey);
$objModuleAdd = MfModuleDAL::GetById($addModuleValue['moduleId']);
$arrayModuleCategory = Utils::GetArrayList($objModuleAdd->GetTableModuleName() . '_category_description', 'id_' . $objModuleAdd->GetTableModuleName() . '_category', 'name', $param['lang'], '');
// $addModuleValue['moduleMetodAdmin'] = $addModuleValue['moduleMetodAdmin'] == 'Edit' ? 'Add' : $addModuleValue['moduleMetod'];
$paramModule['runSharedVariable'] = 'addModule_'.$addModulekey;
$paramModule['moduleName'] = $addModuleValue['moduleName'];
if (isset($arrayModuleCategory[$addModuleValue['moduleCategoryId']])) {
$paramModule['moduleName'] .= " - ".$arrayModuleCategory[$addModuleValue['moduleCategoryId']];
$arrayModuleCategoryByModuleId['addModule_'.$addModulekey] = $arrayModuleCategory[$addModuleValue['moduleCategoryId']];
}
$moduleSharedVariableArray[$addModulekey] = 'addModule_'.$addModulekey;
$arrayModuleIdName[] = 'addModule_'.$addModulekey;
$actionSet = array(
'moduleId' => $addModuleValue['moduleId'],
'moduleName' => $addModuleValue['moduleName'],
'moduleController' =>$addModuleValue['moduleController'],
'moduleMetod' =>$addModuleValue['moduleMetod'],
'moduleMetodAdmin' => $addModuleValue['moduleMetodAdmin'],
'moduleCategoryId' => $addModuleValue['moduleCategoryId'],
'moduleElementId' => $addModuleValue['moduleElementId']
);
$paramMerge = array_merge($paramModule, $param);
$paramMerge = array_merge($paramMerge, $actionSet);
//Utils::ArrayDisplay($paramMerge);
$this->RunModuleController($addModuleValue['moduleController'], $addModuleValue['moduleMetod'].'Module', $paramMerge, true);
}
}
$this->smarty->assign('moduleSharedVariableArray', $moduleSharedVariableArray);
$this->smarty->assign('actionSetModule', $actionSet);
$this->smarty->assign('arrayModuleIdName', $arrayModuleIdName);
$this->smarty->assign('arrayModuleCategoryByModuleId', $arrayModuleCategoryByModuleId);
//Utils::ArrayDisplay($actionSet);
}
}
//-----Moduły-actionSet-KONIEC--------------------------------------------------------------------------------------------
//-----------------------------------------------------------------
} else {
$this->smarty->assign('metaDescription', HEAD_DESCRIPTION);
$this->smarty->assign('metaKeywords', HEAD_KEYWORDS);
$this->smarty->assign('statistic', STATISTIC);
}
$this->smarty->assign('defaultKeywords', Dictionary::Translate('defaultKeywords'));
$this->smarty->assign('defaultDescription', Dictionary::Translate('defaultDescription'));
//Utils::ArrayDisplay($param);
//$this->RunShared('SoteMenuLeft', $param);
$this->RunShared('MenuBox', $param);
$this->RunShared('BanerBox', $param);
$this->RunShared('MenuLangBox', $param);
$this->RunShared('GetUrlLang', $param);
// $this->RunShared('Boxs', $param);
// $this->RunShared('LogoBoxMedia', $param);
// $this->RunShared('LogoBox', $param);
$this->smarty->assign('lang', $param['lang']);
break;
case 'Admin':
/*
* TODO: dorobić panel do kofiguracji może być w pliku configu
* TODO: dodrobić usuwanie modułu już dodoanego.
*
*/
$moduleBoxConfg = array('element_list' => array('delete', 'publication', 'sort'), 'files' => array('delete', 'publication', 'sort'), 'form' => array('publication', 'sort'));
$this->smarty->assign('moduleBoxConfg', $moduleBoxConfg);
$this->GetRedirectInfo();
Dictionary::Init('pl', 1);
$this->AddScript('../../Admin/plugins/ckeditor/ckeditor.js');
$this->smarty->assign('projectName', Dictionary::Translate(PROJECT_NAME, 1));
if (SessionProxy::GetValue('lang')) {
$param['lang'] = SessionProxy::GetValue('lang');
Router::$curLang = $param['lang'];
}
if (isset($param['lang'])) {
if ($param['lang'] == '') {
$param['lang'] = 'pl';
Router::$curLang = $param['lang'];
SessionProxy::SetValue('lang', $param['lang']);
} else {
Router::$curLang = $param['lang'];
SessionProxy::SetValue('lang', $param['lang']);
}
} else {
if (!SessionProxy::GetValue('lang')) {
$param['lang'] = 'pl';
Router::$curLang = $param['lang'];
SessionProxy::SetValue('lang', $param['lang']);
} else {
$param['lang'] = SessionProxy::GetValue('lang');
Router::$curLang = $param['lang'];
}
}
if (isset($param['location'])) {
if ($param['location'] == '') {
$param['location'] = '1';
SessionProxy::SetValue('location', $param['location']);
} else {
SessionProxy::SetValue('location', $param['location']);
}
} else {
if (!SessionProxy::GetValue('location')) {
$param['location'] = '1';
SessionProxy::SetValue('location', $param['location']);
} else {
$param['location'] = SessionProxy::GetValue('location');
}
}
if (SessionProxy::GetValue('location')) {
$param['location'] = SessionProxy::GetValue('location');
}
$this->RunShared('DefaultPanel', $param);
//Utils::ArrayDisplay($param);
if ((isset($param['Structure']) || isset($param['structure'])) && isset($param['id']) && $param['id'] != -1) {
$id = $param['id'];
$objElement = StructureDAL::GetById($id);
if (is_object($objElement)) {
$router = MfRouterDAL::GetById($objElement->GetIdRouter());
if ($objElement->GetIdRouter() > 0) {
if (($router->GetLang() != $param['lang'])) {
$idRouter = MfRouterDAL::AddRouterByStructure($router, $objElement, $param['lang']);
$router = MfRouterDAL::GetById($idRouter);
}
}
if ($objElement->GetIdRouter() == 0) {
$objModule = MfModuleDAL::GetById(22);
} else {
$unserializedParam = unserialize($router->GetParam());
SessionProxy::SetValue('idCategory', $unserializedParam['idCategory']);
SessionProxy::SetValue('router', $router);
SessionProxy::SetValue('idStructure', $id);
$objModule = MfModuleDAL::GetById($router->GetIdMfModule());
}
SessionProxy::SetValue('objModule', $objModule);
} else {
Utils::Redirect(Router::GenerateUrl('Index', array()));
}
}
$this->AddScript('jQuery/jquery.js', 'file', 'top', 1);
$this->AddScript('jQueryUi/jquery-ui.js', 'file', 'top', 2);
$this->AddScript('jQuery/jquery-ui-timepicker-addon.js', 'file', 'top', 3);
$this->AddScript('jQuery/jquery.uploadify.v2.1.4.min.js', 'file', 'top', 4);
$this->AddScript('dropDown.js', 'file', 'top', 5);
$this->AddScript('initAdmin.js', 'file', 'top', 6);
$this->smarty->assign('lang', SessionProxy::GetValue('lang'));
$this->smarty->assign('admin', Registry::Get('admin'));
$this->smarty->assign('galleryUrlLabel', 'customerEdit' . SessionProxy::GetValue('lang'));
break;
}
}
protected function Seo($class = __CLASS__, $method = __METHOD__) {
$seoObj = WpSeoDAL::GetByType(WpSeo::GetMapByController($class . $method));
if (isset($seoObj) && is_object($seoObj)) {
if ($seoObj->getTitle() != '') {
$this->AddTitle($seoObj->getTitle());
}
if ($seoObj->getDescription() != '') {
$this->AddDescription($seoObj->getDescription());
}
if ($seoObj->getKeywords() != '') {
$this->AddKeywords($seoObj->getKeywords());
}
}
}
public function Error404Action($param) {
$this->SetAjaxRender();
//Utils::ArrayDisplay($param);
//$this->SetNoRender();
//header("Status: 404 Not Found");
//Utils::ArrayDisplay($param);
//$this->content=file_get_contents('error.html');
//include("error.html");
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
//$this->AddRedirect('error.html', 0);
//$this->AddRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('urlMain', array('lang' => $param['lang'])), 0, 404);
}
/**
* informacjay o przekierowaniu
*
* @param string $url
* @param string $info
*/
protected function AddRedirectInfo($info, $type = null, $url = null, $jsRedirect = false) {
//Utils::ArrayDisplay($info);
SessionProxy::SetValue("frameInfo", $info);
if ($type != null) {
SessionProxy::SetValue("frameType", $type);
}
if ($url != null && $jsRedirect == false)
$this->AddRedirect($url, 0);
else if ($url != null)
$this->content = "document.location.href='$url';";
}
protected function AddInfo($info, $type) {
$this->RunShared('infoFrame', array('type' => $type, 'info' => $info), true, true);
}
/**
* Pobranie informacji o przekierowaniu
*
*/
private function GetRedirectInfo() {
if (SessionProxy::GetValue("frameInfo") != "") {
$this->AddInfo(SessionProxy::GetValue("frameInfo"), SessionProxy::GetValue('frameType'));
SessionProxy::ClearValue('frameType');
SessionProxy::ClearValue('frameInfo');
SessionProxy::ClearValue('sendFormInfo');
}
}
/**
* Kontrola sesji usera
*
*/
public function CheckLogin() {
// session_start();
//Utils::ArrayDisplay('sds');
$this->user = AuthDAL::GetUser();
Registry::Set('user', $this->user);
$this->smarty->assign('userObj', $this->user);
$this->UserSession();
}
/**
* Weryfikacja czy user jest zalogowany
*
* @return boolean
*/
public function IsUser() {
if (is_object($this->user)) {
return true;
} else {
return false;
}
}
protected function UserSession() {
if ($this->user) {
$id = $this->user->GetId();
if (!empty($id) && (int) $id > 0) {
ActiveChecker::Touch($id);
}
}
}
protected function RemoveUserSession() {
if ($this->user) {
$id = $this->user->GetId();
if (!empty($id) && (int) $id > 0) {
ActiveChecker::Remove($id);
}
}
}
protected function FormatAjaxOutput($errors, $param) {
$out = array();
$validateField = null;
if (Request::Check('validate'))
$validateField = Request::GetPost('validate');
if (isset($param['redirect']) && !isset($param['field'])) {
$out['redirect'] = $param['redirect'];
}
if (empty($errors)) {
$out['success'] = true;
} else {
$out['fields'] = array();
foreach ($errors as $row) {
if (isset($param['field'])) {
if ($param['field'] == $row['field'] || $row['field'] == urldecode($param['field'])) {
$out['fields'][$param['field']] = $row;
} elseif ($validateField == $row['field']) {
$out['fields'][$validateField] = $row;
}
} else {
$out['fields'][$row['field']] = $row;
}
}
if (!empty($out['fields'])) {
$out['success'] = false;
} else {
$out['success'] = true;
}
}
if (isset($param['msg'])) {
$out['msg'] = $param['msg'];
}
if (isset($param['hide'])) {
$out['hide'] = $param['hide'];
}
return json_encode($out);
}
public final function GeneratePopover($title, $image, $message, $buttons, $inputText = false) {
$this->SetAjaxRender(true);
$this->smarty->assign('popoverButtons', $buttons);
$this->smarty->assign('popoverTitle', $title);
$this->smarty->assign('popoverImage', $image);
$this->smarty->assign('popoverMessage', $message);
$this->smarty->assign('popoverInputText', $inputText);
return $this->smarty->fetch('partial/Popover/PopoverSmall.tpl');
}
public function GetDictionary($keyword, $replacement = array()) {
$dictionaryArray = Registry::Get("dictionary");
return vsprintf($dictionaryArray[$keyword], $replacement);
}
private function LoadDictionary($lang = "pl") {
Registry::Set("dictionary", MfDictionaryDAL::GetAllVariables($lang, 36000));
}
}
?>

View File

@@ -0,0 +1,553 @@
<?php
/**
* Description of MainController
*
* @author MAKL
*/
abstract class MainController extends Controller {
protected $user;
public function AdminLoginRedirectAction($param) {
$this->AddRedirect(Router::GenerateUrl(array('login' => 'index')), 0);
}
/**
* Dodatkowy starter kontrolera
*
*/
protected function Run($param = array()) {
//$this->SetAjaxRender();
$urlMain = URL_MAIN;
$this->smarty->assign('urlMain', $urlMain);
$this->smarty->assign('pathStatic', PATH_STATIC_CONTENT);
// $logger = LoggerManager::getLogger(__CLASS__ . ' - ' . __METHOD__);
// $logger->debug(' ' . serialize($param));
//Utils::ArrayDisplay($param);
$location = Config::Get('site');
switch ($location) {
case 'Strona':
session_start();
if ($param['lang'] == '') {
$param['lang'] = 'pl';
Router::$curLang = $param['lang'];
}
$searchLabel = 'search' . $param['lang'];
$this->smarty->assign('searchLabel', $searchLabel);
$analyticsCode = Registry::Get('analytics_code');
$this->smarty->assign('analyticsCode', $analyticsCode);
//=====Coockie========================================================
if (isset($_COOKIE['polityka_akceptacja'])) {
$polityka_akceptacja = $_COOKIE['polityka_akceptacja'];
}
if (isset($polityka_akceptacja)) {
$this->smarty->assign('polityka_akceptacja', true);
}
//--------------------------------------------------------------------
if (!isset($param['idStructure'])) {
$getContent = true;
}
Dictionary::Init($param['lang']);
$this->GetRedirectInfo();
$this->AddTitle(Dictionary::Translate(HEAD_TITLE));
if (isset($param['idStructure']) && !Utils::CheckPublication($param['idStructure'], 'mf_structure', 'id_mf_structure')) {
//$logger->debug('nie ma takiej strony, przekierowanie');
$this->addRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('mainUrl', array()), 0);
}
$this->smarty->assign('lang', $param['lang']);
$this->smarty->assign('title', Dictionary::Translate(HEAD_TITLE));
//====Script=Loader=========================================================
$this->addScript('jQuery/jquery.js', 'file', 'top', 1);
$this->addScript('jQuery/jquery-migrate.min.js', 'file', 'top', 2);
// $this->AddScript('jQuery/jquery-ui.min.js', 'file', 'top', 7);
// $this->AddScript('jQuery/jquery.ui.datepicker-pl.js', 'file', 'top', 7);
$this->AddScript('jQuery/jquery.swipebox.js', 'file', 'top', 2);
$this->AddScript('gray.js', 'file', 'top', 3);
$this->AddScript('jQuery/bjqs-1.3.js', 'file', 'top', 4);
$this->AddScript('init.js', 'file', 'top', 5);
//$this->AddScript('doubletaptogo.js', 'file', 'top', 6);
$this->AddScript('jQuery/jquery.sticky.js', 'file', 'top', 7);
$this->addScript('jQuery/jquery.validate.js', 'file', 'top', 8);
$this->addScript('jQuery/jquery.flexslider.js', 'file', 'top', 9);
$this->addScript('jQuery/jquery.scrollex.min.js', 'file', 'top', 10);
$this->AddScript('jQuery/jquery.scrollme.js', 'file', 'top', 11);
$this->AddScript('jQuery/jquery.transit.min.js', 'file', 'top', 12);
$this->AddScript('jQuery/jquery.visible.js', 'file', 'top', 13);
$this->AddScript('bootstrap/bootstrap.js', 'file', 'top', 14);
//--------------------------------------------------------------------------
//===Run=Structure=element==================================================
if (isset($param['idStructure'])) {
$objElement = StructureDAL::GetById($param['idStructure'], true);
if (!is_object($objElement)) {
MFLog::Debug('brak obiektu, przekierowanie');
$this->addRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('Index', array()), 0);
}
$router = MfRouterDAL::GetById($objElement->GetIdRouter());
$this->smarty->assign('idModule', $router->GetIdMfModule());
$param['idModule'] = $router->GetIdMfModule();
//Utils::ArrayDisplay($param, "param: ".__FILE__.' - '.__LINE__);
// Utils::ArrayDisplay($param);
// Utils::ArrayDisplay($param);
// Utils::ArrayDisplay($objElement);
//==TODO==Zmianić=na=automat========================
if (isset($param['idModule']) && $param['idModule'] == 16) {
$this->smarty->assign('showGallery', true);
}
//--end-TODO----------------------------------------
$this->smarty->assign('title', $objElement->GetName());
$this->smarty->assign('objElement', $objElement);
$this->smarty->assign('contentObj', $objElement->GetContent());
$this->AddTitle($objElement->GetName());
$this->smarty->assign('labelDetal', $objElement->GetUrlLabel() . 'Detail');
//Utils::ArrayDisplay($param);
//Utils::ArrayDisplay($objElement->GetContent());
$param['idContent'] = $objElement->GetIdContent();
if (isset($param['urlDetailLabel'])) {
$this->smarty->assign('labelDetal', $param['urlDetailLabel']);
}
//==meta-do-elementu======================
$objMetaTag = MfMetaTagDAL::GetResult(array('id_source' => $param['idStructure'], 'source_type' => "'mf_structure'"), array());
if (isset($objMetaTag[0])) {
$objMetaTag = $objMetaTag[0];
$descriptionObj = $objMetaTag->GetDescriptionObj();
$this->smarty->assign('metaDescription', $descriptionObj->GetDescription());
$this->smarty->assign('metaKeywords', $descriptionObj->GetKeywords());
$this->smarty->assign('statistic', $descriptionObj->GetStatistic());
} else {
$this->smarty->assign('metaDescription', HEAD_DESCRIPTION);
$this->smarty->assign('metaKeywords', HEAD_KEYWORDS);
$this->smarty->assign('statistic', '');
}
//====Moduły=actionSet==================================================================================================
/**
* Pobieranie bazy i generowanie okienek modułowych
* TODO: Poprawić Kategorie
*
*/
$config = unserialize($router->GetConfig());
//Utils::ArrayDisplay($config, "config: ".__FILE__.' - '.__LINE__);
//Utils::ArrayDisplay($router->GetUrl(), "router-url: ".__FILE__.' - '.__LINE__);
$moduleAdd = true;
//Sprawdzanie czy jest url w parami jesli tak to nie jest to główny router i nie wyswietla modułów
//Potrzebne gdy wyswietlamy listę i mamy paginację lub element/detal
// if (isset($param[$router->GetUrl()])) {
// $moduleAdd = false;
// }
$actionSet = array();
$moduleSharedVariableArray = array();
$arrayModuleIdName = array();
$arrayModuleCategoryByModuleId = array();
if (isset($config['actionSet']) && $moduleAdd) {
//Utils::ArrayDisplay($router->GetName());
//Utils::ArrayDisplay($router);
if (is_array($config['actionSet'])) {
$countPublicModule = 0;
foreach ($config['actionSet'] as $addModulekey => $addModuleValue) {
if ($addModuleValue['modulePublication'] > 0 && !($addModuleValue['moduleId'] == 20 && $countPublicModule == 0) && $addModuleValue['moduleId'] != 23) {
$countPublicModule++;
}
}
$k = 1;
foreach ($config['actionSet'] as $addModulekey => $addModuleValue) {
//Utils::ArrayDisplay($addModuleValue);
//Utils::ArrayDisplay($addModulekey);
if ($addModuleValue['modulePublication'] > 0) {
$objModuleAdd = MfModuleDAL::GetById($addModuleValue['moduleId']);
$arrayModuleCategory = Utils::GetArrayList($objModuleAdd->GetTableModuleName() . '_category_description', 'id_' . $objModuleAdd->GetTableModuleName() . '_category', 'name', $param['lang'], '');
// $addModuleValue['moduleMetodAdmin'] = $addModuleValue['moduleMetodAdmin'] == 'Edit' ? 'Add' : $addModuleValue['moduleMetod'];
$paramModule['runSharedVariable'] = 'addModule_' . $addModulekey;
$paramModule['moduleName'] = $addModuleValue['moduleName'];
if (isset($arrayModuleCategory[$addModuleValue['moduleCategoryId']])) {
$paramModule['moduleName'] .= " - " . $arrayModuleCategory[$addModuleValue['moduleCategoryId']];
$arrayModuleCategoryByModuleId['addModule_' . $addModulekey] = $arrayModuleCategory[$addModuleValue['moduleCategoryId']];
}
$moduleSharedVariableArray[$addModulekey] = 'addModule_' . $addModulekey;
$arrayModuleIdName[] = 'addModule_' . $addModulekey;
$actionSet = array(
'moduleId' => $addModuleValue['moduleId'],
'moduleName' => $addModuleValue['moduleName'],
'moduleController' => $addModuleValue['moduleController'],
'moduleMetod' => $addModuleValue['moduleMetod'],
'moduleMetodAdmin' => $addModuleValue['moduleMetodAdmin'],
'moduleCategoryId' => $addModuleValue['moduleCategoryId'],
'moduleElementId' => $addModuleValue['moduleElementId'],
'moduleBox' => $addModuleValue['moduleBox'],
'moduleKey' => $k
);
$paramMerge = array_merge($paramModule, $param);
$paramMerge = array_merge($paramMerge, $actionSet);
//Utils::ArrayDisplay($addModuleValue['moduleName']);
$this->smarty->assign('moduleKey', $k);
$this->smarty->assign('moduleKeyLast', $countPublicModule);
if ($countPublicModule%2==0) {
$this->smarty->assign('moduleKeyEeven', $countPublicModule);
}
$this->smarty->assign('moduleId', $addModuleValue['moduleId']);
$this->RunModuleController($addModuleValue['moduleController'], $addModuleValue['moduleMetod'] . 'Module', $paramMerge, true);
if (!($addModuleValue['moduleId'] == 20 && $k == 1)) {
$k++;
}
}
}
$this->smarty->assign('moduleKeyLast', $k);
$this->smarty->assign('moduleSharedVariableArray', $moduleSharedVariableArray);
$this->smarty->assign('actionSetModule', $actionSet);
$this->smarty->assign('arrayModuleIdName', $arrayModuleIdName);
$this->smarty->assign('arrayModuleCategoryByModuleId', $arrayModuleCategoryByModuleId);
$this->smarty->assign('arrayModuleCategoryByModuleId', $arrayModuleCategoryByModuleId);
//Utils::ArrayDisplay($actionSet);
}
}
//-----Moduły-actionSet-KONIEC--------------------------------------------------------------------------------------------
//-----------------------------------------------------------------
} else {
$this->smarty->assign('metaDescription', HEAD_DESCRIPTION);
$this->smarty->assign('metaKeywords', HEAD_KEYWORDS);
$this->smarty->assign('statistic', STATISTIC);
}
$this->smarty->assign('defaultKeywords', Dictionary::Translate('defaultKeywords'));
$this->smarty->assign('defaultDescription', Dictionary::Translate('defaultDescription'));
//Utils::ArrayDisplay($param);
//$this->RunShared('SoteMenuLeft', $param);
$this->RunShared('MenuBox', $param);
$this->RunShared('BanerBox', $param);
//$this->RunShared('News', $param);
$this->RunShared('GetUrlLang', $param);
// $this->RunShared('Boxs', $param);
// $this->RunShared('LogoBoxMedia', $param);
// $this->RunShared('LogoBox', $param);
$this->smarty->assign('lang', $param['lang']);
break;
case 'Admin':
/*
* TODO: dorobić panel do kofiguracji może być w pliku configu
* TODO: dodrobić usuwanie modułu już dodoanego.
*
*/
$moduleBoxConfg = array('element_list' => array('delete', 'publication', 'sort'), 'files' => array('delete', 'publication', 'sort'), 'form' => array('publication', 'sort'));
$this->smarty->assign('moduleBoxConfg', $moduleBoxConfg);
$this->GetRedirectInfo();
Dictionary::Init('pl', 1);
$this->AddScript('../../Admin/plugins/ckeditor/ckeditor.js');
$this->AddScript('../../Admin/plugins/ckeditor5/ckeditor.js');
$this->AddScript('../../Admin/plugins/ckeditor5/ckeditor.js.map');
$this->smarty->assign('projectName', Dictionary::Translate(PROJECT_NAME, 1));
if (SessionProxy::GetValue('lang')) {
$param['lang'] = SessionProxy::GetValue('lang');
Router::$curLang = $param['lang'];
}
if (isset($param['lang'])) {
if ($param['lang'] == '') {
$param['lang'] = 'pl';
Router::$curLang = $param['lang'];
SessionProxy::SetValue('lang', $param['lang']);
} else {
Router::$curLang = $param['lang'];
SessionProxy::SetValue('lang', $param['lang']);
}
} else {
if (!SessionProxy::GetValue('lang')) {
$param['lang'] = 'pl';
Router::$curLang = $param['lang'];
SessionProxy::SetValue('lang', $param['lang']);
} else {
$param['lang'] = SessionProxy::GetValue('lang');
Router::$curLang = $param['lang'];
}
}
if (isset($param['location'])) {
if ($param['location'] == '') {
$param['location'] = '1';
SessionProxy::SetValue('location', $param['location']);
} else {
SessionProxy::SetValue('location', $param['location']);
}
} else {
if (!SessionProxy::GetValue('location')) {
$param['location'] = '1';
SessionProxy::SetValue('location', $param['location']);
} else {
$param['location'] = SessionProxy::GetValue('location');
}
}
if (SessionProxy::GetValue('location')) {
$param['location'] = SessionProxy::GetValue('location');
}
$this->RunShared('DefaultPanel', $param);
//Utils::ArrayDisplay($param);
if ((isset($param['Structure']) || isset($param['structure'])) && isset($param['id']) && $param['id'] != -1) {
$id = $param['id'];
$objElement = StructureDAL::GetById($id);
if (is_object($objElement)) {
$router = MfRouterDAL::GetById($objElement->GetIdRouter());
if ($objElement->GetIdRouter() > 0) {
if (($router->GetLang() != $param['lang'])) {
$idRouter = MfRouterDAL::AddRouterByStructure($router, $objElement, $param['lang']);
$router = MfRouterDAL::GetById($idRouter);
}
}
if ($objElement->GetIdRouter() == 0) {
$objModule = MfModuleDAL::GetById(22);
} else {
$unserializedParam = unserialize($router->GetParam());
SessionProxy::SetValue('idCategory', $unserializedParam['idCategory']);
SessionProxy::SetValue('router', $router);
SessionProxy::SetValue('idStructure', $id);
$objModule = MfModuleDAL::GetById($router->GetIdMfModule());
}
SessionProxy::SetValue('objModule', $objModule);
} else {
Utils::Redirect(Router::GenerateUrl('Index', array()));
}
}
$this->AddScript('jQuery/jquery.js', 'file', 'top', 1);
$this->AddScript('jQueryUi/jquery-ui.js', 'file', 'top', 2);
$this->AddScript('jQuery/jquery-ui-timepicker-addon.js', 'file', 'top', 3);
$this->AddScript('jQuery/jquery.uploadify.v2.1.4.min.js', 'file', 'top', 4);
$this->AddScript('dropDown.js', 'file', 'top', 5);
$this->AddScript('initAdmin.js', 'file', 'top', 6);
$this->smarty->assign('lang', SessionProxy::GetValue('lang'));
$this->smarty->assign('admin', Registry::Get('admin'));
$this->smarty->assign('galleryUrlLabel', 'customerEdit' . SessionProxy::GetValue('lang'));
break;
}
}
protected function Seo($class = __CLASS__, $method = __METHOD__) {
$seoObj = WpSeoDAL::GetByType(WpSeo::GetMapByController($class . $method));
if (isset($seoObj) && is_object($seoObj)) {
if ($seoObj->getTitle() != '') {
$this->AddTitle($seoObj->getTitle());
}
if ($seoObj->getDescription() != '') {
$this->AddDescription($seoObj->getDescription());
}
if ($seoObj->getKeywords() != '') {
$this->AddKeywords($seoObj->getKeywords());
}
}
}
public function Error404Action($param) {
$this->SetAjaxRender();
//Utils::ArrayDisplay($param);
//$this->SetNoRender();
//header("Status: 404 Not Found");
//Utils::ArrayDisplay($param);
//$this->content=file_get_contents('error.html');
//include("error.html");
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
//$this->AddRedirect('error.html', 0);
//$this->AddRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('urlMain', array('lang' => $param['lang'])), 0, 404);
}
/**
* informacjay o przekierowaniu
*
* @param string $url
* @param string $info
*/
protected function AddRedirectInfo($info, $type = null, $url = null, $jsRedirect = false) {
//Utils::ArrayDisplay($info);
SessionProxy::SetValue("frameInfo", $info);
if ($type != null) {
SessionProxy::SetValue("frameType", $type);
}
if ($url != null && $jsRedirect == false)
$this->AddRedirect($url, 0);
else if ($url != null)
$this->content = "document.location.href='$url';";
}
protected function AddInfo($info, $type) {
$this->RunShared('infoFrame', array('type' => $type, 'info' => $info), true, true);
}
/**
* Pobranie informacji o przekierowaniu
*
*/
private function GetRedirectInfo() {
if (SessionProxy::GetValue("frameInfo") != "") {
$this->AddInfo(SessionProxy::GetValue("frameInfo"), SessionProxy::GetValue('frameType'));
SessionProxy::ClearValue('frameType');
SessionProxy::ClearValue('frameInfo');
SessionProxy::ClearValue('sendFormInfo');
}
}
/**
* Kontrola sesji usera
*
*/
public function CheckLogin() {
// session_start();
//Utils::ArrayDisplay('sds');
$this->user = AuthDAL::GetUser();
Registry::Set('user', $this->user);
$this->smarty->assign('userObj', $this->user);
$this->UserSession();
}
/**
* Weryfikacja czy user jest zalogowany
*
* @return boolean
*/
public function IsUser() {
if (is_object($this->user)) {
return true;
} else {
return false;
}
}
protected function UserSession() {
if ($this->user) {
$id = $this->user->GetId();
if (!empty($id) && (int) $id > 0) {
ActiveChecker::Touch($id);
}
}
}
protected function RemoveUserSession() {
if ($this->user) {
$id = $this->user->GetId();
if (!empty($id) && (int) $id > 0) {
ActiveChecker::Remove($id);
}
}
}
protected function FormatAjaxOutput($errors, $param) {
$out = array();
$validateField = null;
if (Request::Check('validate'))
$validateField = Request::GetPost('validate');
if (isset($param['redirect']) && !isset($param['field'])) {
$out['redirect'] = $param['redirect'];
}
if (empty($errors)) {
$out['success'] = true;
} else {
$out['fields'] = array();
foreach ($errors as $row) {
if (isset($param['field'])) {
if ($param['field'] == $row['field'] || $row['field'] == urldecode($param['field'])) {
$out['fields'][$param['field']] = $row;
} elseif ($validateField == $row['field']) {
$out['fields'][$validateField] = $row;
}
} else {
$out['fields'][$row['field']] = $row;
}
}
if (!empty($out['fields'])) {
$out['success'] = false;
} else {
$out['success'] = true;
}
}
if (isset($param['msg'])) {
$out['msg'] = $param['msg'];
}
if (isset($param['hide'])) {
$out['hide'] = $param['hide'];
}
return json_encode($out);
}
public final function GeneratePopover($title, $image, $message, $buttons, $inputText = false) {
$this->SetAjaxRender(true);
$this->smarty->assign('popoverButtons', $buttons);
$this->smarty->assign('popoverTitle', $title);
$this->smarty->assign('popoverImage', $image);
$this->smarty->assign('popoverMessage', $message);
$this->smarty->assign('popoverInputText', $inputText);
return $this->smarty->fetch('partial/Popover/PopoverSmall.tpl');
}
public function GetDictionary($keyword, $replacement = array()) {
$dictionaryArray = Registry::Get("dictionary");
return vsprintf($dictionaryArray[$keyword], $replacement);
}
private function LoadDictionary($lang = "pl") {
Registry::Set("dictionary", MfDictionaryDAL::GetAllVariables($lang, 36000));
}
}
?>

239
core/class/MfCurl.class.php Normal file
View File

@@ -0,0 +1,239 @@
<?php
class MfCurl {
const COOKIE = 'cookie.dat';
private $headers;
private $userAgent;
private $cookieFile;
private $proxy;
private $userName;
private $password;
private $options;
private $lastRequest;
private $lastRequestMethod;
private $lastResponse;
public function __construct($cookies=false,$proxy='',$timeout=30) {
$this->headers[] = 'Connection: Keep-Alive';
$this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$this->userAgent = 'MFFramework MFCurl';
$this->options = array();
$this->proxy = $proxy;
if (is_string($cookies)) {
$this->cookieFile = $cookies;
$cookies = true;
}
if ($cookies === true) {
$this->cookies = true;
$this->SetCookie($this->cookieFile);
} else {
$this->cookies = false;
}
$this->ch = curl_init();
$options = array(
// CURLOPT_HTTPHEADER => $this->headers,
CURLOPT_USERAGENT => $this->userAgent,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
);
if ($this->getUserName() != '' && $this->getPassword() != '') {
$options[CURLOPT_USERPWD] = $this->getUserName() . ":" . $this->getPassword();
}
if ($timeout) {
$options[CURLOPT_TIMEOUT] = $timeout;
}
if ($this->cookies == true) {
$options[CURLOPT_COOKIEFILE] = $this->cookieFile;
$options[CURLOPT_COOKIEJAR] = $this->cookieFile;
}
if ($this->proxy && is_array($this->proxy)) {
$options[CURLOPT_PROXY] = $this->proxy['ip'] . ':' . $this->proxy['port'];
}
$this->SetOption($options);
}
public function __destruct() {
curl_close($this->ch);
}
public function SetUrl($url) {
$this->SetOption(CURLOPT_URL, $url);
}
/**
* Ustawia opcje. Aby ustawiæ wiêcej ni¿ 1 opcje nale¿y do name
* podaæ tablice indexowan± nazwami opcji (definicjami) o warto¶ciach jakie
* chcemy ustawiæ.
*
* @param <string/array> $name
* @param <mixed> $value
*/
public function SetOption($name, $value = null) {
if (is_array($name)) {
foreach ($name as $k => $v) {
$this->options[$k] = $v;
}
} else {
$this->options[$name] = $value;
}
}
public function GetOption($name) {
if (array_key_exists($name, $this->options)) {
return $this->options[$name];
} else {
return null;
}
}
public function DelOption($name) {
if (array_key_exists($name, $this->options)) {
unset($this->options[$name]);
}
}
public function GetInfo($name) {
return curl_getinfo($this->ch, $name);
}
public function GetLastRequest() {
return $this->lastRequest;
}
public function GetLastRequestMethod() {
return $this->lastRequestMethod;
}
public function GetLastResponse() {
return $this->lastResponse;
}
public function GetUserName() {
return $this->userName;
}
public function SetUserName($userName) {
$this->userName = $userName;
}
public function GetPassword() {
return $this->password;
}
public function SetPassword($password) {
$this->password = $password;
}
public function SetCookie($cookieFile) {
if (file_exists($cookieFile)) {
$this->cookieFile=$cookieFile;
} else {
$fh = fopen($cookieFile,'w') or $this->RaiseError('The cookie file could not be opened. Make sure this directory has the correct permissions');
$this->cookieFile=$cookieFile;
fclose($fh);
}
}
public function Exec($url, $method, $data = null) {
$method = strtolower($method);
$this->SetUrl($url);
$this->lastRequest = $url;
$this->lastRequestMethod = $method;
if (ereg("^(https)", $url)) {
$this->SetOption(CURLOPT_SSL_VERIFYPEER, false);
}
if($this->getUserName()!='' && $this->getPassword()!='') {
$this->SetOption(CURLOPT_USERPWD, $this->getUserName() . ":" . $this->getPassword());
}
switch ($method) {
case 'get':
$header = false;
break;
case 'post':
$this->SetOption(CURLOPT_POST, true);
$header = true;
break;
default:
$this->SetOption(CURLOPT_CUSTOMREQUEST, $method);
$header = true;
break;
}
if (!array_key_exists(CURLOPT_HEADER, $this->options)) {
$this->SetOption(CURLOPT_HEADER, $header);
}
if ($data !== null) {
$this->SetOption(CURLOPT_POSTFIELDS, $data);
}
curl_setopt_array($this->ch, $this->options);
$response = curl_exec($this->ch);
$this->lastResponse = $response;
if (!$response) {
throw new MfCurl_Exception('No response', 500);
}
if ($this->GetOption(CURLOPT_HEADER)) {
$headerSize = $this->GetInfo(CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize -4);
$body = substr($response, $headerSize);
$statusCode = array();
preg_match_all('/(HTTP(.*) ([1-5][0-9]{2}) ([^\n\r]*)){1,10}/', $headers, $ret);
$responseCode = (int)$ret[3][sizeof($ret[3])-1];
$responseMsg = $ret[4][sizeof($ret[4])-1];
if ($responseCode >= 100 && $responseCode < 300) {
return new MfCurl_Response($body, $responseCode, $responseMsg);
} else {
throw new MfCurl_Exception($responseMsg, $responseCode);
}
} else {
return MfCurl_Response($response);
}
}
public function Get($url) {
return $this->Exec($url, 'get');
}
public function Post($url, $data) {
return $this->Exec($url, 'post', $data);
}
public function RaiseError($error) {
throw new ApiException($error);
}
}
?>

View File

@@ -0,0 +1,90 @@
<?php
/*
* klasa obslugi memcache
*/
class MfMemcache {
private static $host = 'unix:///var/tmp/memcached.sock';
private static $port = '0';
private static $connection = false;
/*
* pobiera wartosc
*/
public static function get($key) {
self::connect();
if(is_a(self::$connection, 'Memcache'))
return self::$connection->get($key);
}
/*
* ustawia wartosc
*/
public static function set($key, $data) {
self::connect();
//if(!is_a(self::$connection, 'Memcache'))
self::$connection->set($key, $data);
}
/*
* usuwa wartosc
*/
public static function remove($key) {
self::connect();
if(is_a(self::$connection, 'Memcache'))
self::$connection->delete($key);
}
/*
* sprawdza czy istnieje
*/
public static function exists($key) {
self::connect();
if(self::get($key) == FALSE) {
return false;
} else {
return true;
}
}
/*
* zamienia wartosc
*/
public static function replace($key, $value) {
self::connect();
if(is_a(self::$connection, 'Memcache'))
self::$connection->replace($key, $value);
}
/*
* inkrementuje
*/
public static function increment($key, $int) {
self::connect();
if(!is_a(self::$connection, 'Memcache'))
return self::$connection->increment($key, $int);
}
/*
* laczy z demonem
*/
private static function connect() {
if(!is_a(self::$connection, 'Memcache')) {
try {
self::$connection = new Memcache();
self::$connection->pconnect(self::$host, self::$port);
} catch (Exception $e){
MFLog::Error('Can\'t connect to memcache');
}
}
}
}
?>

View File

@@ -0,0 +1,38 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of MfXmlParserclass
*
* @author krun
*/
class MfXmlParser extends SimpleXMLElement {
public function __call($name, $convert = true) {
if (substr($name, 0, 3) == 'Get') {
$var = strtolower(substr($name, 3, 1)) . substr($name, 4);
return $this->Prepare($this->$var, $convert);
}
}
public function __get($data) {
return $this->Prepare(parent::__get($data));
}
private function Prepare($txt, $convert = true) {
if (strlen($txt) > 0) {
$txt = trim($txt);
}
if ($convert) {
$txt = @iconv('UTF-8', 'ISO-8859-2//TRANSLIT', $txt);
}
return $txt;
}
}
?>

View File

@@ -0,0 +1,92 @@
<?php
/**
* Description of ModuleController
*
* @author Pawy
*/
abstract class ModuleController extends MainController
{
private $actionSet = array();
public function SetActionSet($set) {
$this->actionSet = $set;
}
public function LoadAdditionalModule($module, $controller) {
if(is_file('controller/'.$module.'/'.str_replace($module.'_', '', ucfirst($controller)).'.php')) {
Core::RequireOnce('controller/'.$module.'/'.str_replace($module.'_', '', ucfirst($controller)).'.php');
MFLog::Debug('Loading module: '.$module.': '.$controller);
} else {
MFLog::Debug('Unable to load module, Loading controller: '.$controller);
throw new CoreException('Unable to load module, Loading controller: '.$controller);
}
}
public function RunAdditionalModule($controller, $method) {
$controllerObj = null;
if(class_exists($controller) && class_parents($controller) == Array('ModuleController'=>'ModuleController', 'MainController'=>'MainController', 'Controller'=>'Controller') && class_implements($controller) == Array('ControllerInterface'=>'ControllerInterface')) {
$controllerObj = new $controller();
if(!method_exists($controllerObj, $method) && !method_exists($controllerObj, $method.'Action')) {
MFLog::Debug('Method thoes not exists: '.$method);
throw CoreException('Method thoes not exists: '.$method);
}
} else {
throw new CoreException('Brak klasy lub brak dziedziczenia!');
}
return $controllerObj;
}
public function DispatchAdditionalModule($controllerObj, $controller, $method, $module, $param, $liveMethod) {
$controllerObj->SetSmarty($this->smarty);
$controllerObj->partialTemplate = $method.'.tpl';
$controllerObj->templatePath = 'partial/'.str_replace('_', '/', str_replace('Controller', '', $controller)).'/';
if((!$controllerObj->Init($method, md5(implode($param, '-'))) || $controllerObj->CheckLiveMethod($method)) && $controllerObj->GetActionRedirect()!=true) {
$methodAction = $method;
$controllerObj->$methodAction($param);
}
if(!isset($controllerObj->content)){
$this->smarty->cache_lifetime = $controllerObj->cacheTime;
$controllerObj->content
= $this->smarty->fetch($controllerObj->templatePath.$controllerObj->partialTemplate, $method.substr(md5(implode($param, '-')),0,100));
//echo $this->controllerObj->templatePath.$this->controllerObj->partialTemplate;
}
$this->smarty->append('zoneContent', $controllerObj->content);
}
public function GetActionSet() {
return $this->actionSet;
}
public function ExecuteAdditionalActions($param) {
$actionSetArray = $this->GetActionSet();
$this->smarty->assign('zoneContent', '');
foreach($actionSetArray as $actionSet) {
$this->LoadAdditionalModule($actionSet['module'], $actionSet['controller']);
$controllerObj = $this->RunAdditionalModule($actionSet['controller'], $actionSet['method']);
$this->DispatchAdditionalModule($controllerObj, $actionSet['controller'], $actionSet['method'], $actionSet['module'], $param);
}
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,199 @@
<?php
class Profiler {
private static $data = array();
public static $profiling = true;
public static $clientIp = array('127.0.0.1', '83.17.124.90', '212.77.105.136');
public static function pageInfo() {
if(self::init()) {
self::log('page', 'HTTP_HOST', $_SERVER["HTTP_HOST"]);
self::log('page', 'SERVER_ADDR', $_SERVER["SERVER_ADDR"]);
$queries = self::getLog('mysql');
$totalTime = 0;
foreach($queries as $query) {
$totalTime = ($totalTime+$query['value']);
}
self::log('page', 'Sql count', count($queries));
self::log('page', 'Sql total time', $totalTime);
}
}
public static function log($type, $message, $value) {
if(self::init()) {
self::$data[$type][] = array('message'=>$message, 'value'=>$value);
}
}
public static function getLog($type) {
if(isset(self::$data[$type])) {
return self::$data[$type];
} else {
return array();
}
}
public static function navigator() {
if(self::init()) {
if(isset($_GET['profileError'])) {
if($_GET['profileError'] == 'true') {
setcookie('error',1 , 0, '/');
}else {
setcookie('error',null , 0, '/');
unset($_COOKIE['error']);
}
}
if(isset($_COOKIE['error'])) {
error_reporting(E_ALL);
ini_set('display_errors', true);
}
if(isset($_GET['profileSql'])) {
if($_GET['profileSql'] == 'true') {
setcookie('sql',1 , 0, '/');
}else {
setcookie('sql',null , 0, '/');
unset($_COOKIE['sql']);
}
}
if(isset($_GET['profilePhp'])) {
if($_GET['profilePhp'] == 'true') {
setcookie('php',1 , 0, '/');
}else {
setcookie('php',null , 0, '/');
unset($_COOKIE['php']);
}
}
}
}
public static function debugInfo() {
if(self::init()) {
self::pageInfo();
$showError = false;
if(isset($_COOKIE['error'])) {
$showError = true;
}
if(isset($_GET['profileError'])) {
if($_GET['profileError'] == 'true') {
$showError = true;
} else {
$showError = false;
}
}
$showSql = false;
if(isset($_COOKIE['sql'])) {
$showSql = true;
}
if(isset($_GET['profileSql'])) {
if($_GET['profileSql'] == 'true') {
$showSql = true;
} else {
$showSql = false;
}
}
$showPhp = false;
if(isset($_COOKIE['php'])) {
$showPhp = true;
}
if(isset($_GET['profilePhp'])) {
if($_GET['profilePhp'] == 'true') {
$showPhp = true;
} else {
$showPhp = false;
}
}
if($showSql) {
self::sqlDisplay();
}
if($showPhp) {
self::phpInfoDisplay();
}
self::commonDisplay();
}
}
private static function commonDisplay() {
?>
<table style='background-color: white; position:fixed; bottom:0; left:0; border: 1px solid #000000;' onclick="if(document.getElementById('profilerDialog').style.display=='none'){document.getElementById('profilerDialog').style.display='block';}else{document.getElementById('profilerDialog').style.display='none';}">
<tr><td>
<?
foreach(self::getLog('page') as $item) {
echo $item['message'].':'.$item['value'].', ';
}
?>
</td></tr>
</table>
<div id="profilerDialog" style="display: none; background-color: white; position:fixed; bottom:0; left:0; width: 300px; height: 60px; border: 1px solid #000000;">
lista sql: <input type="checkbox" <?if(isset($_COOKIE['sql'])) {echo"checked='checked'";}?> onclick="if(this.checked){document.location.href='?profileSql=true'}else{document.location.href='?profileSql=false';}" />
<br />
phpinfo: <input type="checkbox" <?if(isset($_COOKIE['php'])) {echo"checked='checked'";}?> onclick="if(this.checked){document.location.href='?profilePhp=true'}else{document.location.href='?profilePhp=false';}" />
<br />
errorreporting-all: <input type="checkbox" <?if(isset($_COOKIE['error'])) {echo"checked='checked'";}?> onclick="if(this.checked){document.location.href='?profileError=true'}else{document.location.href='?profileError=false';}" />
</div>
<?
}
private static function sqlDisplay() {
if(self::$profiling == true) {
$queries = self::getLog('mysql');
echo"<table style='background-color: white;'>";
$totalTime = 0;
foreach($queries as $query) {
?>
<tr><td><?= $query['message']; ?></td><td><?= $query['value']; ?></td></tr>
<?
$totalTime = ($totalTime+$query['value']);
}
$sqlStart = self::getLog('mysqlStart');
$sqlEnd = self::getLog('mysqlEnd');
if(isset($sqlEnd[0]['value']) && isset($sqlStart[0]['value'])) {
$sqlTime = (($sqlEnd[0]['value'])+($sqlStart[0]['value']));
}
if(isset($sqlTime)){
echo"<tr><td>Czas nawiazania polaczenia: </td><td>".date("Y-d-m h:i:s", mktime(abs($sqlStart[0]['value'])))."</td></tr>";
echo"<tr><td>Czas trwania polaczenia: </td><td>".$sqlTime."</td></tr>";}
echo"<tr><td><br /></td><td><br /></td></tr>";
echo"</table>";
}
}
private static function phpInfoDisplay() {
phpinfo();
}
private static function init() {
$return = false;
if(self::$profiling) {
$return = true;
}
if(in_array($_SERVER['REMOTE_ADDR'], self::$clientIp) && self::$profiling) {
$return = true;
} else {
$return = false;
}
return $return;
}
}
?>

View File

@@ -0,0 +1,77 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of QueryCache
*
* @author User
*/
class QueryCache {
private $query;
private $cacheQueryName;
private $cachePathFile;
public function __construct($queryCacheName,$query)
{
if(QUERYCACHE_ENABLE == true)
{
$this->cachePathFile = PATH_CORE . "/model/QueryCacheTemp.class.php";
$this->query = $query;
$this->cacheQueryName = $queryCacheName;
$this->Write();
}
}
public function Write()
{
// jesli nie ma query w tablicy i nie bylo juz w tym skrypcie dodawane
if(!isset(QueryCacheTemp::$cacheQuery[$this->cacheQueryName]) && Registry::Get($this->cacheQueryName) != true)
{
$fp = fopen($this->cachePathFile,"r+");
if(count(QueryCacheTemp::$cacheQuery) > 0 || Registry::Get("cacheQueryItems") > 0)
$cacheFile=",";
else
$cacheFile="";
$cacheFile.="
\"$this->cacheQueryName\" => \"$this->query\");}?>";
if(Registry::Get("cacheQueryItems") > 0)
fseek($fp, -5,SEEK_END);
else
fseek($fp, -5,SEEK_END);
fputs($fp, $cacheFile);
fclose($fp);
$item = true;
if(Registry::Exists("cacheQueryItems"))
$cacheQueryItems = Registry::Get("cacheQueryItems");
else
$cacheQueryItems = 0;
Registry::Set($this->cacheQueryName, $item);
Registry::Set("cacheQueryItems", ++$cacheQueryItems);
}
}
public function Clear()
{
$fp = fopen($this->cachePathFile,"r+");
$cacheFile='<?php
class QueryCacheTemp
{
static $cacheQuery = array(
);}?>';
fputs($fp, $cacheFile);
fclose($fp);
}
}
?>

View File

@@ -0,0 +1,109 @@
<?
/**
*
* Singleton rejestru
*
*/
class Registry {
/**
* Index wszystkich wartosci
*
* @var unknown_type
*/
static private $index = array();
/**
* Konstruktor klasy
*
*/
public function __construct() {}
/**
* Zapobiegacz klonowania
*
*/
private function __clone() {}
/**
* Dodawanie wartosci do rejestru np. Registry::Set('zmienna', 'wartosc');
*
* @param string $name
* @param unknown_type $item
* @return unknown
*/
public static function Set($name, &$item)
{
if (!self::Exists($name)) {
self::$index[$name] = $item;
return true;
} else {
return false;
}
}
/**
* Weryfikacja czy zmienna o podanej nazwie istnieje
*
* @param string $name
* @return unknown
*/
public static function Exists($name)
{
if (is_string($name)) {
return array_key_exists($name, self::$index);
} else {
throw new Exception('Musi byc stringiem');
}
}
/**
* Zwraca wartosc podanej zmiennej
*
* @param string $name
* @return misc
*/
public static function &Get($name)
{
if (self::Exists($name)) {
$return = self::$index[$name];
} else {
$return = null;
}
return $return;
}
/**
* Czysci zmienna
*
* @param string $name
* @return unknown
*/
public static function Remove($name)
{
if (self::Exists($name)) {
unset(self::$index[$name]);
}
return true;
}
/**
* UWAGA! Czysci caly rejestr
* @access public
* @return boolean
*/
public static function Clear()
{
self::$index = array();
}
public static function SetIndex($index) {
self::$index = $index;
}
}
?>

View File

@@ -0,0 +1,363 @@
<?
/**
* $Id: Request.class.php 395 2008-05-28 19:41:06Z dakl $
* Obsluga requestow
*
*/
class Request {
/**
* Pobiera warto?<3F> tablicy
*
* @param string $value
* @return unknown
*/
static function GetArray($value, $xssremover = true) {
if (isset($_REQUEST[$value])) {
if ($xssremover == true) {
$func = create_function('$a', 'return Utils::RemoveXss($a);'); //FIXME: Gdy wejdzie php5.3 mo<6D>na to troche przerobi<62> bo wprowadzaj? now? wersj<73> funkcji lambda
return array_map($func, $_REQUEST[$value]);
} else {
return $_REQUEST[$value];
}
}
}
/**
* Pobiera wartosc
*
* @param string $value
* @return unknown
*/
static function Get($value,$xssremover = true){
if(isset($_REQUEST[$value]))
{
if($xssremover == true)
return Utils::RemoveXss(self::QuotesRemover($_REQUEST[$value]));
else
return self::QuotesRemover($_REQUEST[$value]);
}
}
/**
* Sprawdza czy istnieje
*
* @param string $value
* @return unknown
*/
static function Check($value){
if(isset($_REQUEST[$value]) || isset($_POST[$value])) {
return true;
} else {
return false;
}
}
/**
* Sprawdza czy istnieje $_POST
*
* @return bool
*/
static function IsPost() {
if(isset($_POST) && !empty($_POST)) {
return true;
} else {
return false;
}
}
/**
* Sprawdza czy istnieje $_GET
*
* @return bool
*/
static function IsGet() {
if(isset($_GET) && !empty($_GET)) {
return true;
} else {
return false;
}
}
/**
* pobiera cookie z wykorzystaniem xss remove'ra
*
* @param string $value
* @param bool $xssremover = true - czy wykorzystywac xssremovera
*/
static function GetCookie($value,$xssremover = true)
{
if(isset($_COOKIE[$value]))
{
if($xssremover == true)
return Utils::RemoveXss(self::QuotesRemover($_COOKIE[$value]));
else
return self::QuotesRemover($_COOKIE[$value]);
}
}
static function SetCookie($name,$value,$time = null,$path = '/')
{
if ($time == '') $time = null;
setcookie($name, $value, $time, $path);
}
static function GetCookieArray($value,$xssremover = true, $delimiter = '_##_')
{
if(isset($_COOKIE[$value]))
{
if($xssremover == true)
$raw = Utils::RemoveXss(self::QuotesRemover($_COOKIE[$value]));
else
$raw = self::QuotesRemover($_COOKIE[$value]);
return explode($delimiter, $raw);
}
else return array();
}
static function SetCookieArray($name,$array,$time = null, $glue = '_##_')
{
$value = implode($glue, $array);
self::SetCookie($name, $value);
}
static function GetCookieAssocArray($value,$xssremover = false, $delimiter = '_#_', $delimiterKey = '_%_' )
{
if(isset($_COOKIE[$value]))
{
if($xssremover == true)
$raw = Utils::RemoveXss(self::QuotesRemover($_COOKIE[$value]));
else
$raw = self::QuotesRemover($_COOKIE[$value]);
$gluedArray = explode($delimiter, $raw);
$array = array();
foreach ($gluedArray as $val) {
$keyValue = explode($delimiterKey, $val) ;
$array[$keyValue[0]] = $keyValue[1];
}
return $array;
}
else return array();
}
static function SetCookieAssocArray($name,$array,$time = null, $glue = '_#_', $glueKey = '_%_')
{
$gluedArray = $array();
foreach ($array as $key => $val) {
$gluedArray[] = $key . $glueKey . $val;
}
$value = implode($glue, $gluedArray);
self::SetCookie($name, $value);
}
static function GetCookieArrayAssocArray($value,$xssremover = false, $delimiter = '_##_', $delimiterRow = '_#_', $delimiterKey = '_%_' )
{
if(isset($_COOKIE[$value]))
{
if($xssremover == true)
$raw = Utils::RemoveXss(self::QuotesRemover($_COOKIE[$value]));
else
$raw = self::QuotesRemover($_COOKIE[$value]);
$gluedArray = explode($delimiter, $raw);
$finalArray = array();
foreach ($gluedArray as $stringAssoc) {
$arrayAssoc = explode($delimiterRow, $stringAssoc);
$array = array();
foreach ($arrayAssoc as $val) {
$keyValue = explode($delimiterKey, $val) ;
$array[$keyValue[0]] = $keyValue[1];
}
$finalArray[] = $array;
}
return $finalArray;
}
else return array();
}
static function SetCookieArrayAssocArray($name,$array,$time = null, $glue = '_##_', $glueRow = '_#_', $glueKey = '_%_')
{
$gluedArray = array();
foreach ($array as $arrayAssoc) {
$keyArray = array();
foreach ($arrayAssoc as $key => $val) {
$keyArray[] = $key . $glueKey . $val;
}
$gluedArray[] = implode($glueRow,$keyArray);
}
$value = implode($glue, $gluedArray);
self::SetCookie($name, $value);
}
/**
* pobiera post z wykorzystaniem xss remove'ra
*
* @param string|array $value
* @param bool $xssremover = true - czy wykorzystywac xssremovera
*
* @return string|array
*/
static function GetPost($value,$xssremover = true, $striptags = true)
{
if(is_array($value)) {
if(isset($_POST[$value['name']][$value['key']])) {
if($striptags == true) {
$ret = strip_tags($_POST[$value['name']][$value['key']]);
}
else {
$ret = $_POST[$value['name']][$value['key']];
}
if($xssremover == true) {
return self::RemoveXss($ret);
}
else {
return self::QuotesRemover($ret);
}
}
} else {
if(isset($_POST[$value])) {
if($striptags == true) {
if(!is_array($_POST[$value])) {
$ret = strip_tags($_POST[$value]);
} else {
$newarray = array();
foreach($_POST[$value] as $valueItem) {
$newarray[] = strip_tags($valueItem);
}
$ret = $newarray;
}
}
else {
$ret = $_POST[$value];
}
if($xssremover == true) {
return self::RemoveXss(self::QuotesRemover($ret));
}
else {
return self::QuotesRemover($ret);
}
}
}
}
/**
* pobranie calej tablicy POST z wykorzystaniem xss removera
*
* @param boolean $xssremover
*/
static function GetAllPost($xssremover = true) {
if($xssremover == true) {
return self::RemoveXss(self::QuotesRemover($_POST));
} else {
return self::QuotesRemover($_POST);
}
}
/**
* pobranie calej tablicy POST z wykorzystaniem xss removera
*
* @param boolean $xssremover
*/
static function GetAllGet($xssremover = true) {
if($xssremover == true) {
return self::RemoveXss(self::QuotesRemover($_GET));
} else {
return self::QuotesRemover($_GET);
}
}
/**
* pobiera get z wykorzystaniem xss remove'ra
*
* @param string|array $value
* @param bool $xssremover = true - czy wykorzystywac xssremovera
*
* @return string|array
*/
static function GetGet($value,$xssremover = true)
{
if(isset($_GET[$value]))
{
if($xssremover == true) {
return self::RemoveXss(self::QuotesRemover($_GET[$value]));
} else {
return self::QuotesRemover($_GET[$value]);
}
}
}
/**
* xss remover
*
* @param string|array $value
* @return string|array
*/
static function RemoveXss($value) {
if(is_array($value)) {
foreach($value as $k => $v) {
$value[$k] = self::RemoveXss($v);
}
return $value;
} else {
return Utils::RemoveXss($value);
}
}
static function SetPost($variable, $value) {
$_POST[$variable] = $value;
}
/**
* quotes remover
*
* @param string|array $value
* @return string|array
*/
static function QuotesRemover($value) {
if (!is_array($value)) {
$value = stripslashes($value);
} else {
$output = array();
foreach($value as $key=>$val) {
//if(!is_array($val)) {
//TODO: fixme
$output[$key]=self::QuotesRemover($val);
//}
}
$value = $output;
}
return $value;
}
}
?>

View File

@@ -0,0 +1,115 @@
<?php
/**
* wideohosting-api-war-client
* Copyright (C) 2008 Wirtualna Polska SA
*
* File: RestRequest.php
* Created: 2008-11-04
*/
/**
* Abstrakcyjna klasa reprezentuj±ca ¿±danie REST.
*
* @author WP
*/
abstract class RestRequest {
/**
* Bazowy URL, pod jakim jest widoczne API.
*/
private $baseUrl = "http://wpapi.wp.pl/api";
/**
* Konstruktor.
*/
public function __construct() {
}
/**
* Wysy³a request HTTP do API.
*
* @param $ch cURL handler
*/
private function sendRequest($ch) {
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size -4);
$body = substr($response, $header_size);
$status = $this->checkResponse($headers, $body);
curl_close($ch);
return $body;
}
private function buildResourceUrl($resource) {
return $this->baseUrl . $resource;
}
// POST
public function doPostCall($resource, $postArgs) {
$ch = curl_init($this->buildResourceUrl($resource));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies");
return $this->sendRequest($ch);
}
// GET
public function doGetCall($resource) {
$ch = curl_init($this->buildResourceUrl($resource));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies");
return $this->sendRequest($ch);
}
// DEL
public function doDelCall($resource) {
$ch = curl_init($this->buildResourceUrl($resource));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies");
return $this->sendRequest($ch);
}
// sprawdzenie statusu odpowiedzi
private function checkResponse($headers, $body) {
$status_code = array ();
preg_match('/\d\d\d/', $headers, $status_code);
switch ($status_code[0]) {
case 100:
case 200 :
case 201 :
case 202 :
break; //sukces
case 401:
throw new SecurityException('Raz');
case 403:
throw new SecurityException("Unauthorized");
break;
default :
throw new ApiException("Invocation error - code " + $status_code[0]);
}
echo "Response " + $status_code[0] . "\n";
return $status_code[0];
}
/**
* Metody wysy³aj±ce odpowiednie ¿±danie do API.
*/
public abstract function send();
public abstract function getStatus();
public abstract function authorize();
public abstract function delete();
}
?>

1324
core/class/Router.class.php Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

160
core/class/SQL.class.php Normal file
View File

@@ -0,0 +1,160 @@
<?php
class SQL {
/**
* Funkcja tworzy string gotowy do wstawienia w kwerendzie SELECT
* ma on posta<74> <TABELA>.<POLE> AS <KLASA>_<POLE>, ... <TABELA>.<POLE> AS <KLASA>_<POLE>
*
* Je<4A>eli klasa o podanej nazwie nie istnieje zwraca '*'
*
* @param string $name Nazwa klasy
* @return string
*/
public static function ToSelect($name,$queryFields = array(), $alias = null)
{
$return = '*';
if(class_exists($name))
{
$className = $name;
$stmt = '';
$list = '';
$tableName = '';
$prfx = '';
if(!empty($alias) && is_string($alias)) {
$tableName = $alias;
$prfx = $alias . '_';
} else {
$stmt = '$tableName = '. $className .'::$tableName;';
}
$stmt .= '$fields = '. $className .'::$fields;';
eval($stmt);
//Utils::ArrayDisplay($name);
//Utils::ArrayDisplay($queryFields);
if(count($queryFields) > 0)
{
foreach ($queryFields as $key => $var)
{
if(isset($fields[$var]) && $fields[$var]!="")
$list .= $tableName.'.'.$var.' AS '. $prfx.$className.'_'.$var.', ';
}
}
else
{
foreach ($fields as $key => $var)
{
if($key[0] == strtolower($key[0]))
$list .= $tableName.'.'.$key.' AS '. $prfx.$className.'_'.$key.', ';
}
}
$list = substr($list, 0, strlen($list) - 2);
$return = $list;
}
return $return;
}
/**
* Funkcja tworzy string gotowy do wstawienia w kwerendzie SELECT
* ma on posta<74> $prefix.<POLE> AS $prefix_<KLASA>_<POLE>, ... <TABELA>.<POLE> AS $prefix_<KLASA>_<POLE>
*
* Je<4A>eli klasa o podanej nazwie nie istnieje zwraca '*'
*
* @param string $name Nazwa klasy
* @return string
*/
public static function ToSelectPrefix($name, $prefix)
{
if(class_exists($name))
{
$className = $name;
$stmt = '$tableName = '. $className .'::$tableName;';
$stmt .= '$fields = '. $className .'::$fields;';
eval($stmt);
$list = "";
foreach ($fields as $key => $var) {
if($key[0] == strtolower($key[0]))
$list .= $prefix.'.'.$key.' AS '. $prefix . '_' . $className.'_'.$key.', ';
}
$list = substr($list, 0, strlen($list) - 2);
return $list;
}
else return '*';
}
public static function ToInsertFields($obj){
$array = $obj->GetFields();
$keys = array_keys($array);
$list = implode(', ', $keys);
return $list;
}
public static function ToInsertValues($obj){
$array = $obj->GetFields();
$db = Registry::Get('db');
$alist = array();
foreach ($array as $dbfield => $field) {
$func = 'Get'. $field;
if($obj->$func() !== "NULL") {
$alist[] .= '"' . $db->Escape( $obj->$func() ) . '" ';
} else {
$alist[] .= 'NULL ';
}
}
$list = implode(', ', $alist);
return $list;
}
public static function ToUpdateSet($obj){
$array = $obj->GetFields();
$alist = array();
$db = Registry::Get('db');
foreach ($array as $dbfield => $field) {
$func = 'Get'. $field;
if (strtolower($obj->$func()) == 'now()')
$alist[] = "`$dbfield` = NOW() " ;
else if ($obj->$func() === false)
{
$alist[] = '`' . $dbfield . '` = NULL';
} else if($obj->$func() !== null) {
// $alist[] = "`$dbfield` = '" . mysql_real_escape_string($obj->$func()). "'";
$alist[] = '`' . $dbfield . '` = \'' . $db->Escape( $obj->$func() ) . '\'';
}
}
$list = implode(', ', $alist);
return $list;
}
public static function ToDeleteSet($obj){
$array = $obj->GetFields();
$alist = array();
$db = Registry::Get('db');
foreach ($array as $dbfield => $field) {
$func = 'Get'. $field;
if ($obj->$func() !== null)
{
// $alist[] = "`$dbfield` = '" . mysql_real_escape_string($obj->$func()). "'";
$alist[] = '`' . $dbfield . '` = \'' . $db->Escape($obj->$func()) . '\'';
}
}
$list = implode('AND ', $alist);
return $list;
}
}
?>

View File

@@ -0,0 +1,107 @@
<?
/**
* $Id: SessionProxy.class.php 693 2008-06-25 12:13:38Z pawy $
*
* Copyright (c) 2002-2008 Formix www.formix.pl
* Ten plik <20>r<EFBFBD>d<EFBFBD>owy jest w<>asno<6E>ci<63> firmy Formix.
*
* Klasa po<70>rednik dost<73>pu do sesji
*/
class SessionProxy {
/**
* Zmiana do przechowywania danych w sesji php (wszystkie pozosta<74>e warto<74>ci bed<65> przechowywane w tablice w niej
*
*/
const SESSION_NAME = "FREEKAM";
/**
* Zapisanie wartosci do sesji
*
* @param EnumSessionValue $p_valueName nazwa pod ktora bedzie to przechowywane
* @param nieokre<72>lony $p_value wartosc zmiennej
*/
public static function SetValue($p_valueName, $p_value) {
//session_register(SessionProxy::SESSION_NAME);
$_SESSION[SessionProxy::SESSION_NAME][$p_valueName] = $p_value;
}
/**
* Pobranie wartosci z sesji
*
* @param EnumSessionValue $p_valueName wartosc zmiennej przechowywanej w sesji
* @return zgodne z typem (dowolnym) wpisanym do sesji lub NULL je<6A>li nie byla wpisana wczesniej
*/
public static function GetValue($p_valueName) {
//session_register(SessionProxy::SESSION_NAME);
if (isset($_SESSION[SessionProxy::SESSION_NAME][$p_valueName])) {
return $_SESSION[SessionProxy::SESSION_NAME][$p_valueName];
}
else {
return null;
}
}
/**
* Usuwa z sesji zmian<61> (wstawia NULL)
*
* @param EnumSessionValue $p_valueName nazwa zmiennej sesyjnej
*/
public static function ClearValue($p_valueName) {
SessionProxy::SetValue($p_valueName, null);
}
public static function ClearSession() {
$_SESSION[SessionProxy::SESSION_NAME] = array();
}
/**
* Jezeli przychodza zmianna ma wartosc to nadpisuje ta w sesji i ja zwraca
*
* @param enum $valueName identyfikator zmiennej w sesji
* @param all $value warto<74><6F>
* @return all warto<74><6F>
*/
public static function GetAndSetValue($valueName, $value) {
if ($value) {
SessionProxy::SetValue($valueName, $value);
}
return SessionProxy::GetValue($valueName);
}
/**
* Sprawdza czy istnieje zmienna
*
* @param string $p_valueName
* @return boolean
*/
public static function IsSetValue($p_valueName){
if(isset($_SESSION[SessionProxy::SESSION_NAME][$p_valueName])){
return true;
}
else{
return false;
}
}
}
/**
* Enumerator do przechowywania zmiennych ktore mozna wpisac do sesji
* Wartosci to nazwy zmiennej w tablicy sesyjnej
*
*/
class EnumSessionValue {
/**
* Definicja stalej admin
*
*/
const ADMIN_OBJECT = 'admin';
/**
* Definicja stalej user
*
*/
const USER_OBJECT = 'user';
/**
* Definicja stalej idType
*
*/
const IDTYPE = 'idType';
}
?>

View File

@@ -0,0 +1,190 @@
<?
/*
* Klasa posredniczaca w dostepie do smarty, obsluguje kontrole cacheowania
*/
class TemplateMaster extends Smarty {
//private $clearCache = false;
public function CacheControl($tpl, $param = '') {
return false;
}
/**
* Returns an array containing template variables
*
* @param string $name
* @param string $type
* @return array
*/
function &get_template_vars($name = null) {
if (!isset($name)) {
return $this->getTemplateVars();
} elseif ($this->getTemplateVars($name)) {
$_tmp = $this->getTemplateVars($name);
return $_tmp;
} else {
// var non-existant, return valid reference
$_tmp = null;
return $_tmp;
}
}
//
// public function CacheControl($tpl, $param='') {
//
// $this->force_compile = 0;
// if($this->caching!=2) {
// $this->cache_lifetime = 0;
// //$this->force_compile = true;
// // echo"aaa";
// return false;
// }
//
// // $param =
// // array ( 'cache_id' => [string],
// // 'compile_id'=> [string],
// // 'lifetime' => [integer],
// // 'write' => [boolean] );
// $_cache_file = null;
// $_auto_id = $this->_get_auto_id($param['cache_id'], 1);
// $_cache_file = $this->_get_auto_filename($this->cache_dir, $tpl, $_auto_id);
// if($this->template_exists($tpl)) {
// //$_cache_file = $this->_get_auto_filename($this->cache_dir, $tpl, $_auto_id);
// //$_compile_file = $this->_get_auto_filename($this->compile_dir, $tpl, $_auto_id);
//
// if(!$this->_is_compiled($tpl, $this->compile_dir) && is_file($_cache_file)) {
// $this->clear_cache($tpl, $param['cache_id'], $param['cache_id']);
// }
// }
//
// //$memcacheCheck = false;
// //if(Enviroment::CheckMemcache()) {
// // $memcacheCheck = MfMemcache::exists('cacheLock'.$param['cache_id']);
// //}
//
// $this->cache_lifetime = -1;
//
// // sprawdzam cache
// if (!$this->is_cached($tpl, $param['cache_id'])) {
// //echo"tu";
// return false;
//
// } elseif ((isset($param['methodRun']) && Registry::Get('methodRun') == true && (isset($param['write']) || $this->caching!=2 )) || (isset($param['write']) || $this->caching!=2 && !isset($param['methodRun']))) {
// MFLog::Debug("writing:".$tpl);
// //$this->clear_cache($tpl, $param['cache_id']);
// $this->clearCache = true;
//
// if(is_file($_cache_file)) {
// ///$futureTime = time();
// ///touch($_cache_file, $futureTime, $futureTime);
// //echo $futureTime."<br>";
// //$fh = fopen($_cache_file, 'w');
//
// $_contents = $this->_read_file($_cache_file);
// $_info_start = strpos($_contents, "\n") + 1;
// $_info_len = (int)substr($_contents, 0, $_info_start - 1);
// $_cache_info = unserialize(substr($_contents, $_info_start, $_info_len));
// $results = substr($_contents, $_info_start + $_info_len);
//
// $cacheInfo = $this->_cache_info;
// $cacheInfo['timestamp'] = time();
// //$cacheInfo['mexyk'] = time();
// //$cacheInfo['expires'] = '0';
//
// $sCacheInfo = serialize($cacheInfo);
// $header = strlen($sCacheInfo) . "\n" .$sCacheInfo;
//
// $fh = fopen($_cache_file, 'w');
//
// fwrite($fh, $header.$results);
// fclose($fh);
//
// }
// //if(Enviroment::CheckMemcache()) {
// // MfMemcache::set('cacheLock'.$param['cache_id'], true);
// //}
// // force overwrite cache file
// //$this->force_compile = true;
// //$this->cache_lifetime = 0;
// return true;
//
// } elseif (isset($param['lifetime'])) {
// //if(!Core::GetAppSafeMode() && $memcacheCheck == false) {
// if(!Core::GetAppSafeMode()) {
// // sprawdza czas cache
// MFLog::Debug('check:'.date("d H:i:s", $this->_cache_info['timestamp']));
// //return ($this->_cache_info['timestamp'] < time() - $param['lifetime']) ? false : true;
// //echo $this->_cache_info['timestamp'].':'.(time() - $param['lifetime'])."<br>";
// if($this->_cache_info['timestamp'] < time() - $param['lifetime']){
// //echo"regeneruj";
// return false;
// } else {
// return true;
// }
// } else {
// return true;
// }
//
// } else {
// return true;
// }
// }
//
// public function fetch($resource_name, $cache_id = null, $compile_id = null, $display = false) {
// //if(Enviroment::CheckMemcache()) {
// // MfMemcache::remove('cacheLock'.$cache_id);
// //}
//
// if($this->clearCache == true) {
// $_auto_id = $this->_get_auto_id($cache_id, 1);
// $_cache_file = $this->_get_auto_filename($this->cache_dir, $resource_name, $_auto_id);
//
// if(is_file($_cache_file)) {
//
// unlink($_cache_file);
//
// $this->force_compile = true;
// $this->is_cached($resource_name, $cache_id);
// $this->force_compile = false;
//
// }
// }
// $this->clearCache = false;
// return parent::fetch($resource_name, $cache_id, $compile_id, $display);
// }
//
//
// public function touchCacheFile($cacheFile) {
// if(is_file($cacheFile)) {
// ///$futureTime = time();
// ///touch($_cache_file, $futureTime, $futureTime);
// //echo $futureTime."<br>";
// //$fh = fopen($_cache_file, 'w');
//
// $_contents = $this->_read_file($cacheFile);
// $_info_start = strpos($_contents, "\n") + 1;
// $_info_len = (int)substr($_contents, 0, $_info_start - 1);
// $_cache_info = unserialize(substr($_contents, $_info_start, $_info_len));
// $results = substr($_contents, $_info_start + $_info_len);
//
// $cacheInfo = $_cache_info;
// $cacheInfo['timestamp'] = time();
// //$cacheInfo['mexyk'] = time();
// //$cacheInfo['expires'] = '0';
//
// $sCacheInfo = serialize($cacheInfo);
// $header = strlen($sCacheInfo) . "\n" .$sCacheInfo;
//
// $fh = fopen($cacheFile, 'w');
//
// fwrite($fh, $header.$results);
// fclose($fh);
//
// }
// }
}
?>

View File

@@ -0,0 +1,90 @@
<?php
/**
* Description of UserValidator.class
*
* Rozszerzenie Validatora dla specyficznych danych
*
* @author KoPi
*/
abstract class UserValidator {
/**
* funkcja sprawdzaja czy podane dane juz istnieja w tabeli uzytkownik
*
* @param string $login
*
* @return int $amout - ilosc powtarzajacych sie loginow
*/
public function CheckLoginRepeat($login)
{
$db = Registry::Get('db');
$sql = "SELECT count(login) FROM wp_preserve WHERE login=:01";
$stmt = $db->prepare($sql)
->bindParam("01", mysql_escape_string(strip_tags($login)) )
->execute();
$amout=$stmt->FetchRow();
return $amout[0];
}
/**
* funkcja sprawdzaja czy podane dane juz istnieja w tabeli uzytkownik
*
* @param string $login
*
* @return int $amout - ilosc powtarzajacych sie emaili
*/
public function CheckEmailRepeat($email)
{
$db = Registry::Get('db');
$sql = "SELECT count(email) FROM wp_preserve WHERE email=:01";
$stmt = $db->prepare($sql)
->bindParam("01", mysql_escape_string(strip_tags($email)) )
->execute();
$amout=$stmt->FetchRow();
return $amout[0];
}
public function CheckPassword($password,$hash)
{
// sprawdzanie czy haslo jest ok
$db = Registry::Get('db');
$sql="SELECT count(login) FROM wp_preserve WHERE hash=:01 AND passwd=:02";
$stmt = $db->prepare($sql)
->bindParam("01",mysql_escape_string(strip_tags($hash)) )
->bindParam("02",mysql_escape_string(strip_tags($password)) )
->execute();
$amout=$stmt->FetchRow();
return $amout[0];
}
public function ValidatePhotoForm(){
if ( $this->IsEmpty('name', 'Pole zdjêcia jest puste.'))
{
$this->IsNotEqualValue('error', 0, 'Wyst±pi³ b³±d serwera.');
if( $this->IsFile('tmp_name','Przes³anie pliku nie powio³o siê.'))
{
$this->IsGoodImageFormat('type','Format przesy³anego pliku nie jest poprawny.');
}
$this->IsWithinRange('size','Przesy³any plik jast za du¿y.',0,ALLOWED_FILE_SIZE);
}
return $this->GetErrorList();
}
}
?>

1529
core/class/Utils.class.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
<?
class UtilsUtf {
function decode_utf8($string)
{
$accented = array(
'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ă', 'Ą',
'Ç', 'Ć', 'Č', 'Œ',
'Ď', 'Đ',
'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ă', 'ą',
'ç', 'ć', 'č', 'œ',
'ď', 'đ',
'È', 'É', 'Ê', 'Ë', 'Ę', 'Ě',
'Ğ',
'Ì', 'Í', 'Î', 'Ï', 'İ',
'Ě', 'Ľ', 'Ł',
'è', 'é', 'ê', 'ë', 'ę', 'ě',
'ğ',
'ĂŹ', 'Ă­', 'ĂŽ', 'ĂŻ', 'Äą',
'ĺ', 'ľ', 'ł',
'Ñ', 'Ń', 'Ň',
'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ő',
'Ŕ', 'Ř',
'Ś', 'Ş', 'Š',
'ñ', 'ń', 'ň',
'ò', 'ó', 'ô', 'ö', 'ø', 'ő',
'ŕ', 'ř',
'ś', 'ş', 'š',
'Ţ', 'Ť',
'Ù', 'Ú', 'Û', 'Ų', 'Ü', 'Ů', 'Ű',
'Ý', 'ß',
'Ĺš', 'Ĺť', 'Ĺ˝',
'ĹŁ', 'ĹĽ',
'Ăš', 'Ăş', 'Ăť', 'Ĺł', 'Ăź', 'ĹŻ', 'Ĺą',
'Ă˝', 'Ăż',
'Ĺş', 'Ĺź', 'Ĺž',
'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р',
'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'р',
'Х', 'Т', 'У', 'Ф', 'м', 'Ќ', 'Ч', 'Ш', 'Њ', 'Ъ', 'Ѝ', 'Џ', 'Э', 'Ў', 'Я',
'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'
);
$replace = array(
'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'A', 'A',
'C', 'C', 'C', 'CE',
'D', 'D',
'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'a', 'a',
'c', 'c', 'c', 'ce',
'd', 'd',
'E', 'E', 'E', 'E', 'E', 'E',
'G',
'I', 'I', 'I', 'I', 'I',
'L', 'L', 'L',
'e', 'e', 'e', 'e', 'e', 'e',
'g',
'i', 'i', 'i', 'i', 'i',
'l', 'l', 'l',
'N', 'N', 'N',
'O', 'O', 'O', 'O', 'O', 'O', 'O',
'R', 'R',
'S', 'S', 'S',
'n', 'n', 'n',
'o', 'o', 'o', 'o', 'o', 'o',
'r', 'r',
's', 's', 's',
'T', 'T',
'U', 'U', 'U', 'U', 'U', 'U', 'U',
'Y', 'Y',
'Z', 'Z', 'Z',
't', 't',
'u', 'u', 'u', 'u', 'u', 'u', 'u',
'y', 'y',
'z', 'z', 'z',
'A', 'B', 'B', 'r', 'A', 'E', 'E', 'X', '3', 'N', 'N', 'K', 'N', 'M', 'H', 'O', 'N', 'P',
'a', 'b', 'b', 'r', 'a', 'e', 'e', 'x', '3', 'n', 'n', 'k', 'n', 'm', 'h', 'o', 'p',
'C', 'T', 'Y', 'O', 'X', 'U', 'u', 'W', 'W', 'b', 'b', 'b', 'E', 'O', 'R',
'c', 't', 'y', 'o', 'x', 'u', 'u', 'w', 'w', 'b', 'b', 'b', 'e', 'o', 'r'
);
return str_replace($accented, $replace, $string);
}
function returnInUtf($string) {
Utils::ArrayDisplay($string);
return str_replace('è', '%C3%A8', $string);
}
}
?>

View File

@@ -0,0 +1,820 @@
<?php
/**
*
* Klasa validatora
*
*/
class Validator extends UserValidator {
/**
* lista bledow
*
* @var array
*/
private $errors = array();
/**
* lista validatorow
*
* @var array
*/
private $validators = array();
/**
* validowane dane
*
* @var array
*/
private $values = array();
/**
* konstruktor klasy
* oczekuje danych w postaci array('nazwa_zmiennej'=>$wartosc, ...)
*
* @param array $data
*/
public function __construct($data) {
$this->ResetErrorList();
$data = $this->Remover($data);
$this->values = $data;
}
public function Remover($data) {
if (!is_array($data)) {
$data = rawurldecode($data);
// $data = Utils::url2pl($data);
} else {
$output = array();
foreach($data as $key=>$val) {
$output[$key]=self::Remover($val);
}
$data = $output;
}
return $data;
}
/**
* Dodaje parametry dla validatora
*
* @param string $field
* @param string $match
* @param string $msg
* @param array $data
*/
public function AddValidator($field, $match, $msg, $data = null) {
$this->validators[] = array('field'=>$field, 'match'=>$match, 'msg'=>$msg, 'data'=>$data);
}
/**
* Resetuje liste bledow
*
*/
public function ResetErrorList() {
$this->errors = array();
}
/**
* dodaje dowolny blad do dowolnego pola
*
* @param string $field
* @param string $msg
*/
public function AddError($field,$msg,$value = '') {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
}
/**
* Zwraca zadana wartosc
*
* @param string|array $field
* @return string
*/
private function GetValue($field) {
if(is_array($field)) {
if(isset($this -> values[$field['name']][$field['key']])) {
return $this -> values[$field['name']][$field['key']];
}
} else {
if(isset($this->values[$field])) {
return $this->values[$field];
}
}
}
public function IsBadLanguage($field,$msg,$alterField = null) {
$value = $this->GetValue($field);
if (RestrictedKeywordDAL::CheckBadLanguage($value)) {
$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
return false;
}
else {
return true;
}
}
/**
* sprawdza czy niepusty
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsEmpty($field, $msg, $alternativeField = null) {
$value = trim($this->GetValue($field));
if (empty($value)) {
$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
if($field == 'city') {
SessionProxy::SetValue('_city_limit_','');
}
return false;
}
else {
if($field == 'city') {
SessionProxy::SetValue('_city_limit_',html_entity_decode( $this->GetValue($field),ENT_NOQUOTES, 'UTF-8'));
}
return true;
}
}
/**
* musi byc pusty
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function OnlyEmpty($field, $msg, $alternativeField = null) {
$value = $this->GetValue($field);
if (trim($value) == "") {
if($field == 'city') {
SessionProxy::SetValue('_city_limit_',html_entity_decode( $this->GetValue($field),ENT_NOQUOTES, 'UTF-8'));
}
return false;
}
else {
$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
if($field == 'city') {
SessionProxy::SetValue('_city_limit_','');
}
return true;
}
}
/**
* Sprawdzenie czy wartosc istnieje w bazie
*
* @param <type> $field
* @param <type> $msg
*/
public function IsInDatabase($field, $msg, $classDAL, $db_field_name) {
$value = $this->GetValue($field);
eval('$result = ' . $classDAL . 'DAL::GetResult(array($db_field_name => "'.$value.'"), array(), null, null, true);');
if($result > 0) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
} else {
return true;
}
}
/**
* Sprawdzenie czy wartosc istnieje w bazie
*
* @param <type> $field
* @param <type> $msg
*/
public function NotInDatabase($field, $msg, $classDAL, $db_field_name) {
$value = $this->GetValue($field);
eval('$result = ' . $classDAL . 'DAL::GetResult(array($db_field_name => \'"'.$value.'"\'), array(), null, null, true);');
if($result == 0) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return true;
} else {
return false;
}
}
/**
* Metoda sprawdza czy dla danego wpisu isnieją powiązania zadanego typu w tabeli MfLink
*
* @param string $field - pole formularza
* @param string $alternativeField - alternatywne pole
* @param integer $srcId - id wpisu (artykuł, rapoty itp.)
* @param string $srcType
* @param string $destinationType
* @param string $msg
* @param string $classDAL
* @return bool
*/
public function IsInMfLink($field, $alternativeField, $srcId, $srcType, $destinationType, $msg) {
$value = $this->GetValue($field);
//$fields = array(
// 'mf_link.id_source' => $srcId,
// 'mf_link.source_type' => '"'.$srcType.'"',
// 'mf_link.destination_type' => '"'.$destinationType.'"'
//);
//$result = MfLinkDAL::GetResult($fields, array(), null, null, true);
//if($srcId == -1 && is_array($value)) $result = 1;
if(isset($value) && is_array($value)) {
$result = 1;
} else {
$result = 0;
}
if($result == 0) {
if(is_null($alternativeField)) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
} else {
$this->errors[] = array("field" => $alternativeField, "value" => $value, "msg" => $msg);
}
return false;
} else {
return true;
}
}
/**
* Sprawdzenie czy wartosci w bazie nie ma
*
* @param <type> $field
* @param <type> $msg
*/
public function IsntInDatabase($field, $msg, $classDAL, $db_field_name) {
$value = $this->GetValue($field);
eval('$result = ' . $classDAL . 'DAL::GetResult(array($db_field_name => $value), array(), null, null, true);');
if($result > 0) {
return true;
} else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
}
/**
* Sprawdzenie czy numer PWZ jest w bazie
*
* @param <type> $field
* @param <type> $msg
*/
public function IsNotInDatabase($field, $msg, $db_field_name, $profileId = 0) {
$value = $this->GetValue($field);
$result = PhysicianDAL::GetResult(array($db_field_name=> addslashes($value), 'id_nm_physician' => array('condition' => '!=', 'value' => $profileId)), array(), null, null, true);
if($result == 0) {
return true;
} else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
}
}
/**
* sprawdza czy zaznaczony
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsChecked($field, $msg, $fieldId) {
$value = $this->GetValue($field);
if (trim($value) != "on") {
if(is_null($fieldId)) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
}else {
$this->errors[] = array("field" => $fieldId, "value" => $value, "msg" => $msg);
}
return false;
}
else {
return true;
}
}
/**
* Sprawdza czy string
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsString($field, $msg) {
$value = $this->GetValue($field);
if(!is_string($value)) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
else {
return true;
}
}
/**
* Sprawdza czy liczba
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsNumber($field, $msg) {
$value = $this->GetValue($field);
if(!is_numeric($value)) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
else {
return true;
}
}
/**
* Sprawdza czy calkowite
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsInteger($field, $msg) {
$value = $this->GetValue($field);
if(!is_integer($value)) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
else {
return true;
}
}
/**
* Sprawdza czy zmiennoprzecinkowa
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsFloat($field, $msg) {
$value = $this->GetValue($field);
if(!is_float($value)) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
else {
return true;
}
}
/**
* Sprawdza czy literowe
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsAlpha($field, $msg) {
$value = $this->GetValue($field);
$pattern = "/^[a-zA-Z]+$/";
if(preg_match($pattern, $value)) {
return true;
}
else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
}
public function isDate($field,$msg, $alternativeField=null) {
$value = $this->GetValue($field);
$pattern = "/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/";
if (preg_match($pattern,$value))
return true;
else {
$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
return false;
}
}
public function isHour($field,$msg,$alternativeField=null) {
$value = $this->GetValue($field);
$pattern = "/([0-9]|[0-1][0-9]|[2][0-4]):([0-5][0-9])/";
if (preg_match($pattern,$value))
return true;
else {
$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
return false;
}
}
public function IsPrevDate($field, $msg) {
$value = $this->GetValue($field);
$date_prev = strtotime($value);
if($date_prev > time()) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
else
return true;
}
public function isGoodLogin($field,$msg) {
$value = $this->GetValue($field);
// echo mb_detect_encoding($value);
// if( mb_detect_encoding($value) == "UTF-8")
//$value = iconv("utf-8", "iso-8859-2", $value);
$len = "{" . strlen($value) . "}";
$pattern = "^[a-zA-Z0-9_<39><5F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E6A1A6><EFBFBD>Ư<EFBFBD><C6AF> \+\-]$len$";
//!@\$%\*\(\)\^\-
if(strlen($value)>=3 && strlen($value)<=15 && ereg($pattern,$value,$matches)) {
//var_dump($matches);
return true;
}
else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
}
public function isGoodPassword($field,$msg) {
$value = $this->GetValue($field);
if(strlen($value) >= 6)
return true;
else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
}
/**
* Sprawdza czy w przedziale
*
* @param string $field
* @param string $msg
* @param integer $min
* @param integer $max
* @return boolean
*/
public function IsWithinRange($field, $msg, $min, $max) {
$value = $this->GetValue($field);
if(!is_numeric($value) || $value < $min || $value > $max) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
else {
return true;
}
}
/**
* Sprawdza czy email
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsEmailAddress($field, $msg) {
$value = $this->GetValue($field);
$pattern = "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/";
if(preg_match($pattern, $value)) {
return true;
}
else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
}
/**
* Sprawdza czy oba pola sa takie sam
*
* @param string $field1
* @param string $field2
* @param string $msg
* @return boolean
*/
public function IsNotEqual($field1,$field2, $msg) {
$value1 = $this->GetValue($field1);
$value2 = $this->GetValue($field2);
if($value1 == $value2) {
return true;
}
else {
$this->errors[] = array("field" => $field2, "value" => "", "msg" => $msg);
return false;
}
}
/**
* Sprawdza czy oba pola sa takie sam
*
* @param string $field1
* @param string $field2
* @param string $msg
* @return boolean
*/
public function IsEqual($field1,$field2, $msg) {
$value1 = $this->GetValue($field1);
$value2 = $this->GetValue($field2);
if($value1 != $value2) {
return true;
}
else {
$this->errors[] = array("field" => $field2, "value" => "", "msg" => $msg);
return false;
}
}
public function IsEqualValue($field, $value, $msg) {
$value1 = $this->GetValue($field);
if($value1 != $value) {
return true;
}
else {
$this->errors[] = array("field" => $field, "value" => "", "msg" => $msg);
return false;
}
}
public function IsNotEqualValue($field, $value, $msg) {
$value1 = $this->GetValue($field);
//Utils::ArrayDisplay($value1.' == '. $value);
if($value1 == $value) {
return true;
}
else {
$this->errors[] = array("field" => $field, "value" => "", "msg" => $msg);
return false;
}
}
/**
* Zwraca liste bledow
*
* @return array
*/
public function GetErrorList() {
return $this->errors;
}
/**
* Zwraca liczbe bledow
*
* @return integer
*/
public function IsError() {
if (sizeof($this->errors) > 0) {
return sizeof($this->errors);
}
else {
return false;
}
}
public function CheckCaptcha($field,$msg) {
$value1 = $this->GetValue($field);
$value2 = Request::GetCookie(CAPTCHA_COOKIE_NAME, false);
//$value2 = $_SESSION[CAPTCHA_COOKIE_NAME];
//Utils::ArrayDisplay($value1);
//Utils::ArrayDisplay($value2);
if(md5(strtolower($value1) . CAPTCHA_SEED) == $value2)
return true;
else {
$this->errors[] = array("field" => 'captcha', "value" => $value1, "msg" => $msg);
return false;
}
}
public function IsFile($field,$msg) {
$value = $this->GetValue($field);
if(is_file($value)) {
return true;
}
else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
}
public function IsGoodImageFormat($field,$msg) {
$value = $this->GetValue($field);
switch ($value) {
default:
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
break;
case 'image/pjpeg':
break;
case 'image/gif':
break;
case 'image/jpeg':
break;
case 'image/png':
break;
case 'image/x-png':
break;
}
}
public function IsValidFeed($field, $msg) {
$value = $this->GetValue($field);
$value = str_replace('&lt;x&gt;','',$value);
if(empty($value)){
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
}else{
$feed = new FeedReader($value);
$feed->init();
$feed->handle_content_type();
if ($feed->error()){
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
} else {
return true;
}
}
}
/**
* Sprawdzenie czy numer specjalizacja jest w bazie
*
* @param <type> $field
* @param <type> $msg
*/
public function IsInDatabaseSpecialty($field, $msg, $db_field_name) {
$value = $this->GetValue($field);
if(is_array($value))foreach($value AS $k => $val) {
if(strlen($val) == 0) {
// $this->errors[] = array("field" => 'speciality_'.$k.'', "value" => $val, "msg" => 'To pole nie może być puste');
$this->errors[] = array("field" => $field.'['.$k.']', "value" => $val, "msg" => 'To pole nie może być puste');
// $this->errors[] = array("field" => $field.'_'.$k, "value" => $val, "msg" => 'To pole nie może być puste');
}else {
$result = SpecialtyDAL::GetResult(array($db_field_name=> addslashes($val)), array(), null, null, true);
if($result > 0) {
return true;
} else {
// $this->errors[] = array("field" => 'speciality_'.$k.'', "value" => $val, "msg" => $msg);
$this->errors[] = array("field" => $field.'['.$k.']', "value" => $val, "msg" => $msg);
// $this->errors[] = array("field" => $field.'_'.$k, "value" => $val, "msg" => $msg);
}
}
}
}
/**
* Sprawdzenie czy numer specjalizacja jest w bazie
*
* @param <type> $field
* @param <type> $msg
*/
public function IsInDatabaseArticleCategory($field, $msg, $id) {
$val = $this->values['name'];
$result = MfArticleCategoryDescriptionDAL::GetResult(array('name'=> addslashes($val)), array(), null, null, true);
if($result > 0 && $val != '') {
if($id == -1) {
$this->errors[] = array("field" => $field, "value" => $val, "msg" => $msg);
return count($result);
}
} else {
return false;
}
}
public function IsNotProvince($field,$msg,$db_field_name = null) {
$value = $this->GetValue($field);
$sql = 'SELECT COUNT(*) AS count FROM nmd_province WHERE name LIKE "'.$value.'"';
$result = Registry::Get('db')->prepare($sql)->execute()->FetchAllAssoc();
if(intval($result[0]['count']) == 0) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
}
}
public function IsNotCity($field,$msg,$db_field_name = null) {
$value = $this->GetValue($field);
$sql = 'SELECT COUNT(*) AS count FROM nmd_city WHERE name LIKE "'.$value.'"';
$result = Registry::Get('db')->prepare($sql)->execute()->FetchAllAssoc();
if(intval($result[0]['count']) == 0) {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
}
}
public function IsArray($field, $msg, $fieldId = null) {
$value = $this->GetValue($field);
if(is_array($value) && !empty($value)) {
return true;
}
else {
if(is_null($fieldId)) {
$this->errors[] = array("field" => $field."[0]", "value" => $value, "msg" => $msg);
$this->errors[] = array("field" => $field."[1]", "value" => $value, "msg" => $msg);
$this->errors[] = array("field" => $field."[2]", "value" => $value, "msg" => $msg);
}else {
$this->errors[] = array("field" => $fieldId, "value" => $value, "msg" => $msg);
}
return false;
}
}
/**
* Waliduje dane przy pomocy wprowadzonych validatorow
*
*/
public function Validate() {
foreach($this->validators as $validator) {
if(isset($validator['field']) && isset($validator['match']) && isset($validator['msg'])) {
if($validator['match'] == 'empty') {
$this->IsEmpty($validator['field'], $validator['msg']);
} else if ($validator['match'] == 'string') {
$this->IsString($validator['field'], $validator['msg']);
} else if ($validator['match'] == 'number') {
$this->IsNumber($validator['field'], $validator['msg']);
} else if ($validator['match'] == 'integer') {
$this->IsInteger($validator['field'], $validator['msg']);
} else if ($validator['match'] == 'float') {
$this->IsFloat($validator['field'], $validator['msg']);
} else if ($validator['match'] == 'alpha') {
$this->IsAlpha($validator['field'], $validator['msg']);
} else if ($validator['match'] == 'range') {
$this->IsWithinRange($validator['field'], $validator['msg'], $validator['data']['min'], $validator['data']['max']);
} else if ($validator['match'] == 'email') {
$this->IsEmail($validator['field'], $validator['msg']);
}
}
}
}
public function CheckDimensions($file, $width, $height) {
//Utils::ArrayDisplay($file);
$dimensions = getimagesize($file['tmp_name']);
$img_width = $dimensions[0];
$img_height = $dimensions[1];
if($img_width != $width || $img_height != $height) {
$this->errors[] = array("field" => $field, "value" => $val, "msg" => $msg);
return false;
} else {
return true;
}
}
/**
* Sprawdza czy email
*
* @param string $field
* @param string $msg
* @return boolean
*/
public function IsPostalCode($field, $msg) {
$value = $this->GetValue($field);
$pattern = "/^[0-9]{2}[-][0-9]{3}$/";
if(preg_match($pattern, $value)) {
return true;
}
else {
$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
return false;
}
}
public function setValues($data) {
$this->values = $data;
}
}
?>

View File

@@ -0,0 +1,141 @@
<?php
/**
* XML2Array: A class to convert XML to array in PHP
* It returns the array which can be converted back to XML using the Array2XML script
* It takes an XML string or a DOMDocument object as an input.
*
* See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
*
* Author : Lalit Patel
* Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array
* License: Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
* Version: 0.1 (07 Dec 2011)
* Version: 0.2 (04 Mar 2012)
* Fixed typo 'DomDocument' to 'DOMDocument'
*
* Usage:
* $array = XML2Array::createArray($xml);
*/
class XML2Array {
private static $xml = null;
private static $encoding = 'UTF-8';
/**
* Initialize the root XML node [optional]
* @param $version
* @param $encoding
* @param $format_output
*/
public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
self::$xml = new DOMDocument($version, $encoding);
self::$xml->formatOutput = $format_output;
self::$encoding = $encoding;
}
/**
* Convert an XML to Array
* @param string $node_name - name of the root node to be converted
* @param array $arr - aray to be converterd
* @return DOMDocument
*/
public static function &createArray($input_xml) {
$xml = self::getXMLRoot();
if(is_string($input_xml)) {
$parsed = $xml->loadXML($input_xml);
if(!$parsed) {
throw new Exception('[XML2Array] Error parsing the XML string.');
}
} else {
if(get_class($input_xml) != 'DOMDocument') {
throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.');
}
$xml = self::$xml = $input_xml;
}
$array[$xml->documentElement->tagName] = self::convert($xml->documentElement);
self::$xml = null; // clear the xml node in the class for 2nd time use.
return $array;
}
/**
* Convert an Array to XML
* @param mixed $node - XML as a string or as an object of DOMDocument
* @return mixed
*/
private static function &convert($node) {
$output = array();
switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
$output['@cdata'] = trim($node->textContent);
break;
case XML_TEXT_NODE:
$output = trim($node->textContent);
break;
case XML_ELEMENT_NODE:
// for each child node, call the covert function recursively
for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
$child = $node->childNodes->item($i);
$v = self::convert($child);
if(isset($child->tagName)) {
$t = $child->tagName;
// assume more nodes of same kind are coming
if(!isset($output[$t])) {
$output[$t] = array();
}
$output[$t][] = $v;
} else {
//check if it is not an empty text node
if($v !== '') {
$output = $v;
}
}
}
if(is_array($output)) {
// if only one node of its kind, assign it directly instead if array($value);
foreach ($output as $t => $v) {
if(is_array($v) && count($v)==1) {
$output[$t] = $v[0];
}
}
if(empty($output)) {
//for empty nodes
$output = '';
}
}
// loop through the attributes and collect them
if($node->attributes->length) {
$a = array();
foreach($node->attributes as $attrName => $attrNode) {
$a[$attrName] = (string) $attrNode->value;
}
// if its an leaf node, store the value in @value instead of directly storing it.
if(!is_array($output)) {
$output = array('@value' => $output);
}
$output['@attributes'] = $a;
}
break;
}
return $output;
}
/*
* Get the root XML node, if there isn't one, create it.
*/
private static function getXMLRoot(){
if(empty(self::$xml)) {
self::init();
}
return self::$xml;
}
}
?>

View File

@@ -0,0 +1,6 @@
[db]
prodUser = testaem2
prodPass = aiKahxui6H
prodDb = testaem2
prodHost = mysql8.ceti.pl

View File

@@ -0,0 +1,16 @@
<?php
// ** Ustawienia MySQL-a - możesz uzyskać je od administratora Twojego serwera ** //
/** Nazwa bazy danych, której używać ma WordPress */
define('prodDb', 'zurawikn_aem');
/** Nazwa użytkownika bazy danych MySQL */
define('prodUser', 'zurawikn_aem');
/** Hasło użytkownika bazy danych MySQL */
define('prodPass', 'G]@0NeuvRokQ');
/** Nazwa hosta serwera MySQL */
define('prodHost', 'localhost');
?>

View File

@@ -0,0 +1,26 @@
<?php
$panelMenu['layout'] = array(
//'User' => array('User' => 'Index'),
// 'Boxy' => array('HomeSite' => 'Index'),
//'Menu' => array('HomeSite' => 'Links'),
// 'Slider-Baner' => array('HomeSite' => 'Baner'),
// 'Loga sponsorzy' => array('HomeSite' => 'Logo', 'type' => 1),
// 'Loga media' => array('HomeSite' => 'Logo', 'type' => 2),
'Treść Home' => array('HomeSite' => 'ArticleBox'),
'Słowniki' => array('Dictionary' => 'Index')
);
$panelMenu['admin'] =array(
//'User' => array('User' => 'Index'),
'Zmienne serwisu' => array('Setup' => 'Index'),
//'Kategorie produktów' => array('ProductCategory' => 'Index')
);
define('ARRAY_PANEL_MENU', $panelMenu);
?>

View File

@@ -0,0 +1,45 @@
<?php
define('PROJECT_NAME', 'CMS');
define('BREAD_CRUMB_DELIMITER', '/');
define('CONTENT_PER_PAGE', '10');
define('COMMENTS_PER_PAGE', '10');
define('COMMENTS_PER_PAGE_MOST', '10');
define('APPLICATION_FILE_TYPE', '');
define('SMARTY_CACHING_METHOD', '0');
define('URL_DELIMITER', '/');
define('ERROR_REDIRECT', false);
define('DBCACHE_ENABLE', false);
define('QUERYCACHE_ENABLE', false);
define('ADMIN_PANEL',true);
define('SMARTY_INTERNAL_CACHING', false);
/** ORDER TYPES **/
define ('ORDER_ASC', 'ASC');
define ('ORDER_DESC', 'DESC');
define ('ROUTER_SORT_LABEL', 'sortuj');
define ('ROUTER_DIR_LABEL', 'kierunek');
define ('ROUTER_PAGE_LABEL', 'page');
define('DEFAULT_SORT_FIELD', 'domyslne');
define('DEFAULT_SORT_DIR', 'asc');
define('PAGE_NEXT_LABEL', 'Następna »');
define('PAGE_PREV_LABEL', '« Poprzednia');
/** KOMENTARZE **/
define('COMMENT_INDENT', 10);
//==Param=URL=STRONA======
define('STRONA_APPLICATION_FILE_TYPE', '');
define('STRONA_URL_DELIMITER', '/');
//------------------------
?>

View File

@@ -0,0 +1,30 @@
<?php
error_reporting(E_ALL);
//URL BEZ PREFIKSU http:// ORAZ BEZ KONCOWEGU UKOSNIKA
define ('APP_URL', 'zurawik.pl/Admin');
define ('APP_STATIC_URL', 'zurawik.pl/Static');
define ('APP_SITE_URL', 'zurawik.pl');
//OD TEGO MIEJSA NIC NIE ZMIENIAMY!!
define ('DS', DIRECTORY_SEPARATOR);
define ('PATH_CONFIG', pathinfo(__FILE__, PATHINFO_DIRNAME ) . DS);
define ('PATH_CORE', PATH_CONFIG . '..' . DS . '..' . DS);
define ('PATH_MAIN_APP', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS . 'Admin' . DS);
define ('PATH_STATIC_CONTENT', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS . 'Static' . DS);
define ('PATH_SMARTY_COMPILE', PATH_MAIN_APP . 'temp' . DS . 'compile' . DS );
define ('PATH_SMARTY_CACHE', PATH_MAIN_APP . 'temp' . DS . 'cache' . DS);
define ('PATH_MODEL_TMP', PATH_MAIN_APP . 'temp' . DS . 'model' . DS );
define ('PATH_SITE_CACHE', PATH_CORE . 'Strona' . DS . 'temp' . DS . 'cache' . DS);
define ('PATH_SMARTY_TEMPLATE', PATH_MAIN_APP . 'template' . DS);
define ('PATH_SMARTY_PLUGINS', PATH_CORE . 'plugins' . DS . 'Smarty' . DS);
define ('DBCACHE_PATH', PATH_MAIN_APP . 'temp' . DS . 'dbcache' . DS);
define ('URL_MAIN', 'https://' . APP_URL);
define ('URL_STATIC_CONTENT', 'https://' . APP_STATIC_URL);
define ('URL_SITE_MAIN', 'https://' . APP_SITE_URL);
define ('LOG4PHP_DIR', PATH_CORE . 'lib' . DS . 'log4php' . DS . 'src' . DS . 'php' . DS);
define ('LOG4PHP_CONFIGURATION', PATH_CORE . 'config' . DS . 'Log4PHPConfig.xml');
require_once(LOG4PHP_DIR . 'Logger.php');
?>

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?><!--
@author Dawid Kloch <dawid@formix.pl>
@version $Revision: 1.2 $
-->
<log4php:configuration xmlns:log4php="http://www.vxr.it/log4php/"
threshold="all" debug="false">
<!-- Definition file log -->
<appender name="daily01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="./logs/pasztet_%s.log" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<!-- <layout class="LoggerLayoutSimple"></layout> -->
</appender>
<!--
<appender name="dailyWarn01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="../logs/modelki_warn_%s.log" />
<layout class="LoggerLayoutSimple"></layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
-->
<!-- Definition send mail -->
<appender name="sendMailEvent" class="LoggerAppenderMailEvent">
<param name="from" value="ModelkiLogger" />
<param name="subject" value="modelki.wp.pl Log4PHP Report" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="fatal" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMail" class="LoggerAppenderMail">
<param name="from" value="ModelkiLogger" />
<param name="subject"
value="modelki.wp.pl Log4PHP Report (sendMail)" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="Mail report" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="error" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition html info -->
<appender name="htmlTable" class="LoggerAppenderEcho">
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="LoggerAppenderEcho" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Root section -->
<root>
<level value="debug" />
<appender_ref ref="daily01" />
<appender_ref ref="sendMailEvent" />
<appender_ref ref="sendMail" />
<!-- <appender_ref ref="dailyWarn01" /> -->
<!-- <appender_ref ref="htmlTable" /> -->
</root>
</log4php:configuration>

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?><!--
@author Dawid Kloch <dawid@formix.pl>
@version $Revision: 1.2 $
-->
<log4php:configuration xmlns:log4php="http://www.vxr.it/log4php/"
threshold="all" debug="false">
<!-- Definition file log -->
<appender name="daily01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="./logs/pasztet_%s.log" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<!-- <layout class="LoggerLayoutSimple"></layout> -->
</appender>
<!--
<appender name="dailyWarn01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="../logs/modelki_warn_%s.log" />
<layout class="LoggerLayoutSimple"></layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
-->
<!-- Definition send mail -->
<appender name="sendMailEvent" class="LoggerAppenderMailEvent">
<param name="from" value="ModelkiLogger" />
<param name="subject" value="modelki.wp.pl Log4PHP Report" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="fatal" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMail" class="LoggerAppenderMail">
<param name="from" value="ModelkiLogger" />
<param name="subject"
value="modelki.wp.pl Log4PHP Report (sendMail)" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="Mail report" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="error" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition html info -->
<appender name="htmlTable" class="LoggerAppenderEcho">
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="LoggerAppenderEcho" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Root section -->
<root>
<level value="debug" />
<appender_ref ref="daily01" />
<appender_ref ref="sendMailEvent" />
<appender_ref ref="sendMail" />
<!-- <appender_ref ref="dailyWarn01" /> -->
<!-- <appender_ref ref="htmlTable" /> -->
</root>
</log4php:configuration>

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?><!--
@author Dawid Kloch <dawid@formix.pl>
@version $Revision: 1.2 $
-->
<log4php:configuration xmlns:log4php="http://www.vxr.it/log4php/"
threshold="all" debug="false">
<!-- Definition file log -->
<appender name="daily01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="../logs/pasztet_%s.log" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<!-- <layout class="LoggerLayoutSimple"></layout> -->
</appender>
<!--
<appender name="dailyWarn01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="../logs/modelki_warn_%s.log" />
<layout class="LoggerLayoutSimple"></layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
-->
<!-- Definition send mail -->
<appender name="sendMailEvent" class="LoggerAppenderMailEvent">
<param name="from" value="ModelkiLogger" />
<param name="subject" value="modelki.wp.pl Log4PHP Report" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="fatal" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMail" class="LoggerAppenderMail">
<param name="from" value="ModelkiLogger" />
<param name="subject"
value="modelki.wp.pl Log4PHP Report (sendMail)" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="Mail report" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="error" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition html info -->
<appender name="htmlTable" class="LoggerAppenderEcho">
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="LoggerAppenderEcho" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Root section -->
<root>
<level value="debug" />
<appender_ref ref="daily01" />
<appender_ref ref="sendMailEvent" />
<appender_ref ref="sendMail" />
<!-- <appender_ref ref="dailyWarn01" /> -->
<!-- <appender_ref ref="htmlTable" /> -->
</root>
</log4php:configuration>

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?><!--
@author Dawid Kloch <dawid@formix.pl>
@version $Revision: 1.2 $
-->
<log4php:configuration xmlns:log4php="http://www.vxr.it/log4php/"
threshold="all" debug="false">
<!-- Definition file log -->
<appender name="daily01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="../logs/pasztet_%s.log" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<!-- <layout class="LoggerLayoutSimple"></layout> -->
</appender>
<!--
<appender name="dailyWarn01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="../logs/modelki_warn_%s.log" />
<layout class="LoggerLayoutSimple"></layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
-->
<!-- Definition send mail -->
<appender name="sendMailEvent" class="LoggerAppenderMailEvent">
<param name="from" value="ModelkiLogger" />
<param name="subject" value="modelki.wp.pl Log4PHP Report" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="fatal" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMail" class="LoggerAppenderMail">
<param name="from" value="ModelkiLogger" />
<param name="subject"
value="modelki.wp.pl Log4PHP Report (sendMail)" />
<param name="to" value="dawid@formix.pl" />
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="Mail report" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="error" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition html info -->
<appender name="htmlTable" class="LoggerAppenderEcho">
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="LoggerAppenderEcho" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Root section -->
<root>
<level value="debug" />
<appender_ref ref="daily01" />
<appender_ref ref="sendMailEvent" />
<appender_ref ref="sendMail" />
<!-- <appender_ref ref="dailyWarn01" /> -->
<!-- <appender_ref ref="htmlTable" /> -->
</root>
</log4php:configuration>

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?><!--
@author Dawid Kloch <dawid@kloch.pl>
@version $Revision: 1.2 $
-->
<log4php:configuration xmlns:log4php="http://www.vxr.it/log4php/"
threshold="all" debug="false">
<!-- Definition file log -->
<appender name="daily01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="./logs/CMS_%s.log" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<!-- <layout class="LoggerLayoutSimple"></layout> -->
</appender>
<appender name="dailyWarn01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="./logs/CMS_warn_%s.log" />
<layout class="LoggerLayoutSimple"></layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMailEvent" class="LoggerAppenderMailEvent">
<param name="from" value="maciek@kloch.pl" />
<param name="subject" value="CMS Log4PHP Report" />
<param name="to" value="maciek@kloch.pl" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="fatal" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMail" class="LoggerAppenderMail">
<param name="from" value="maciek@kloch.pl" />
<param name="subject"
value="CMS Log4PHP Report (sendMail)" />
<param name="to" value="maciek@kloch.pl" />
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="Mail report" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="error" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition html info -->
<appender name="htmlTable" class="LoggerAppenderEcho">
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="LoggerAppenderEcho" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Root section -->
<root>
<level value="debug" />
<appender_ref ref="daily01" />
<appender_ref ref="sendMailEvent" />
<appender_ref ref="sendMail" />
<!-- <appender_ref ref="dailyWarn01" /> -->
<!-- <appender_ref ref="htmlTable" /> -->
</root>
</log4php:configuration>

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?><!--
@author Dawid Kloch <dawid@kloch.pl>
@version $Revision: 1.2 $
-->
<log4php:configuration xmlns:log4php="http://www.vxr.it/log4php/"
threshold="all" debug="false">
<!-- Definition file log -->
<appender name="daily01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="./logs/CMS_%s.log" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<!-- <layout class="LoggerLayoutSimple"></layout> -->
</appender>
<appender name="dailyWarn01" class="LoggerAppenderDailyFile">
<param name="datePattern" value="Y-m-d" />
<param name="file" value="./logs/CMS_warn_%s.log" />
<layout class="LoggerLayoutSimple"></layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMailEvent" class="LoggerAppenderMailEvent">
<param name="from" value="maciek@kloch.pl" />
<param name="subject" value="CMS Log4PHP Report" />
<param name="to" value="maciek@kloch.pl" />
<layout class="LoggerLayoutTTCC">
<param name="threadPrinting" value="true" />
<param name="categoryPrefixing" value="true" />
<param name="contextPrinting" value="true" />
<param name="microSecondsPrinting" value="false" />
<param name="dateFormat" value="%Y-%m-%d %H:%M:%S" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="fatal" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition send mail -->
<appender name="sendMail" class="LoggerAppenderMail">
<param name="from" value="maciek@kloch.pl" />
<param name="subject"
value="CMS Log4PHP Report (sendMail)" />
<param name="to" value="maciek@kloch.pl" />
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="Mail report" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="error" />
<param name="LevelMax" value="fatal" />
</filter>
</appender>
<!-- Definition html info -->
<appender name="htmlTable" class="LoggerAppenderEcho">
<layout class="LoggerLayoutHtml">
<param name="locationInfo" value="true" />
<param name="title" value="LoggerAppenderEcho" />
</layout>
<filter class="LoggerLevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
</filter>
</appender>
<!-- Root section -->
<root>
<level value="debug" />
<appender_ref ref="daily01" />
<appender_ref ref="sendMailEvent" />
<appender_ref ref="sendMail" />
<!-- <appender_ref ref="dailyWarn01" /> -->
<!-- <appender_ref ref="htmlTable" /> -->
</root>
</log4php:configuration>

View File

@@ -0,0 +1,6 @@
[db]
prodUser = testaem
prodPass = aith2Heing
prodDb = testaem
prodHost = mysql8.ceti.pl

View File

@@ -0,0 +1,55 @@
<?php
define('ALLOWED_FILE_SIZE', '1100000');
define('CAPTCHA_SEED', 'qwerty12345');
define('CAPTCHA_COOKIE_NAME', 'k3nd3u');
define('CONTENT_PER_PAGE', '10');
define('COMMENTS_PER_PAGE', '10');
define('COMMENTS_PER_PAGE_MOST', '10');
define('APPLICATION_FILE_TYPE', '');
define('SMARTY_CACHING_METHOD', '0');
define('URL_DELIMITER', '/');
define('ADMIN_EMAIL', 'maciek@kloch.pl');
define('SERVER_MAIL_FROM', 'maciek@kloch.pl');
define('ERROR_REDIRECT', false);
define('DBCACHE_ENABLE', false);
define('QUERYCACHE_ENABLE', false);
define('WP_REKID', 7990);
define('DEVELOPER_MODE', true);
define('SMARTY_INTERNAL_CACHING', false);
define('CONTENT_MAX_DISP_LEN', 200);
/** ORDER TYPES **/
define ('ORDER_ASC', 'ASC');
define ('ORDER_DESC', 'DESC');
define ('ROUTER_SORT_LABEL', 'sortuj');
define ('ROUTER_DIR_LABEL', 'kierunek');
define ('ROUTER_PAGE_LABEL', 'page');
define('DEFAULT_SORT_FIELD', 'domyslne');
define('DEFAULT_SORT_DIR', 'asc');
define('PAGE_NEXT_LABEL', 'Następna »');
define('PAGE_PREV_LABEL', '« Poprzednia');
define('MIN_TAG_LENGTH', 3);
define('FEED_CACHE_ENABLED', true);
define('ADMIN_PANEL',false);
define('HEAD_TITLE', 'ParioPack');
define('HEAD_KEYWORDS', '');
define('HEAD_DESCRIPTION', '');
define('STATISTIC', '');
?>

View File

@@ -0,0 +1,36 @@
<?php
error_reporting(E_ALL);
//URL BEZ PREFIKSU http:// ORAZ BEZ KONCOWEGU UKOSNIKA
define ('APP_URL', 'test.aem.pl/pario2/pack');
define ('APP_STATIC_URL', 'test.aem.pl/pario2/Static');
//OD TEGO MIEJSA NIC NIE ZMIENIAMY!!
define ('DS', DIRECTORY_SEPARATOR);
define ('PATH_CONFIG', pathinfo(__FILE__, PATHINFO_DIRNAME ) . DS);
define ('PATH_CORE', PATH_CONFIG . '..' . DS . '..' . DS);
define ('PATH_MAIN_APP', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS);
define ('PATH_STATIC_CONTENT', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS . 'Static' . DS);
define ('PATH_SMARTY_COMPILE', PATH_MAIN_APP . 'temp' . DS . 'compile' . DS . 'pack' );
define ('PATH_SMARTY_CACHE', PATH_MAIN_APP . 'temp' . DS . 'cache' . DS);
define ('PATH_SMARTY_TEMPLATE', PATH_MAIN_APP . 'template' . DS);
define ('PATH_SMARTY_PLUGINS', PATH_CORE . 'plugins' . DS . 'Smarty' . DS);
define ('DBCACHE_PATH', PATH_MAIN_APP . 'temp' . DS . 'dbcache' . DS);
define ('PATH_USER_SESSION', PATH_MAIN_APP . 'temp' . DS . 'session' . DS);
define ('URL_MAIN', 'http://' . APP_URL);
define ('URL_SITE_MAIN', URL_MAIN);
define ('FATAL_ERROR_URL' , 'http://' . APP_URL);
define ('URL_STATIC_CONTENT', 'http://' . APP_STATIC_URL);
define ('LOG4PHP_DIR', PATH_CORE . 'lib' . DS . 'log4php' . DS . 'src' . DS . 'php' . DS);
define ('LOG4PHP_CONFIGURATION', PATH_CORE . 'config' . DS . 'Log4PHPConfig.xml');
require_once(LOG4PHP_DIR . 'Logger.php');
?>

View File

@@ -0,0 +1,6 @@
[db]
prodUser = root
prodPass =
prodDb = magalie
prodHost = localhost

View File

@@ -0,0 +1,97 @@
<?php
define('ALLOWED_FILE_SIZE', '1100000');
define('CAPTCHA_SEED', 'qwerty12345');
define('CAPTCHA_COOKIE_NAME', 'k3nd3u');
define('CONTENT_PER_PAGE', '2');
define('APPLICATION_FILE_TYPE', '.html');
define('SMARTY_CACHING_METHOD', '0');
define('SMARTY_INTERNAL_CACHING', false);
define('URL_DELIMITER', '/');
define('ADMIN_EMAIL', 'dawid@formix.pl');
define('SERVER_MAIL_FROM', 'modelki@serwis.wp.pl');
define('ERROR_REDIRECT', false);
define('DBCACHE_ENABLE', false);
define('QUERYCACHE_ENABLE', false);
/** ORDER TYPES **/
define ('ORDER_ASC', 'ASC');
define ('ORDER_DESC', 'DESC');
/** **/
/** KLUB AKTYWNEGO PASZTETA **/
define ('FAILURE_SHOW_LATEST_SHORT', 3);
define ('FAILURE_SHOW_LATEST', 5);
define ('FAILURE_SHOW_WIN', 5);
define ('FAILURE_MOST_ACTIVE', 5);
define ('FAILURE_BOOK_SHOW', 2);
/** end KLUB AKTYWNEGO PASZTETA **/
/** PAGER CONFIG **/
define ('PAG_DISP', 2);
/** end PAGER CONFIG **/
/** POKOJ KRZYWONOGA **/
/** dowcipy **/
define ('ROOM_TYPE_JOKE', 1); // dowcip
define ('ROOM_TYPE_ANEC', 2); // anegdota
define ('ROOM_JOKE_LATEST_SHOW_SHORT', 3);
define ('ROOM_JOKE_LATEST_SHOW', 5);
define ('ROOM_JOKE_LIST_SHOW', 10);
/** sondy **/
define ('PROBE_MAX_Q_NO', 6); // maksymalna liczba odpowiedzi w sondzie
define ('PROBE_MIN_Q_NO', 2); // minimalna liczba odpowiedzi w sondzie
define ('ROOM_PROBE_LATEST_SHOW_SHORT', 3);
define ('ROOM_PROBE_LATEST_SHOW', 5);
define ('ROOM_PROBE_LIST_SHOW', 10);
/** end POKOJ KRZYWONOGA **/
/** FORMATOWANIE DATY I CZASU **/
define('DATE_DEFAULT_FORMAT', '%a, %d %b %Y, %H:%M');
define('TIME_DEFAULT_FORMAT', '%H:%M');
define('DATE_SHORT_FORMAT', "%d-%m-%Y") ;
/** end FORMATOWANIE DATY I CZASU **/
/** PRZYZNAWANIE NAGR<47>D **/
define('MIN_RATING_COUNT_FOR_AWARD', 1);
/** end PRZYZNAWANIE NAGR<47>D **/
/** file upload **/
define ('ST_TYPE_LOCAL', 1);
define ('ST_TYPE_SERVER', 2);
define ('STORAGE_TYPE', ST_TYPE_SERVER);
define('ANSWER_STATUS_OK', 200);
define('ANSWER_STATUS_CREATED', 201);
/** WP API **/
define('WP_API_LOGIN', 'max15');
define('WP_API_PASSWORD', '872GtwyJ29U');
//define('WP_API_LOGIN', 'turystyka');
//define('WP_API_PASSWORD', 'aIVsj3kYh32j');
define('WP_API_URL', 'http://wpapi.wp.pl/api');
define('WP_API_URL_GET', 'http://get-2.wpapi.wp.pl/?');
/** end WP API **/
?>

View File

@@ -0,0 +1,35 @@
<?php
error_reporting(E_ALL);
//URL BEZ PREFIKSU http:// ORAZ BEZ KONCOWEGU UKOSNIKA
define ('APP_URL', 'localhost/formix_old_projects/magalie/dev/src/Server');
define ('APP_STATIC_URL', 'localhost/formix_old_projects/magalie/dev/src/Static');
define ('APP_ADMIN_URL', 'localhost/formix_old_projects/magalie/dev/src/Admin');
define ('APP_SITE_URL', 'localhost/formix_old_projects/magalie/dev/src/Strona');
//OD TEGO MIEJSA NIC NIE ZMIENIAMY!!
define ('DS', DIRECTORY_SEPARATOR);
define ('PATH_CONFIG', pathinfo(__FILE__, PATHINFO_DIRNAME ) . DS);
define ('PATH_CORE', dirname(dirname(PATH_CONFIG)) . DS);
define ('PATH_MAIN', dirname(dirname(dirname(PATH_CONFIG))) . DS . 'Server' . DS);
define ('PATH_MAIN_APP', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS . 'Strona' . DS);
define ('PATH_STATIC_CONTENT', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS . 'Static' . DS);
define ('PATH_MODEL_TMP', PATH_MAIN_APP . 'temp' . DS . 'model' . DS );
define ('PATH_SMARTY_COMPILE', PATH_MAIN_APP . 'temp' . DS . 'compile' . DS );
define ('PATH_SMARTY_CACHE', PATH_MAIN_APP . 'temp' . DS . 'cache' . DS);
define ('PATH_SMARTY_TEMPLATE', PATH_MAIN_APP . 'template' . DS);
define ('PATH_SMARTY_PLUGINS', PATH_CORE . 'plugins' . DS . 'Smarty' . DS);
define ('DBCACHE_PATH', PATH_MAIN_APP . 'temp' . DS . 'dbcache' . DS);
define ('PATH_USER_SESSION', PATH_MAIN_APP . 'temp' . DS . 'session' . DS);
define ('URL_MAIN', 'http://' . APP_URL);
define ('URL_SITE_MAIN', 'http://' . APP_SITE_URL);
define ('URL_ADMIN_MAIN', 'http://' . APP_ADMIN_URL);
define ('URL_STATIC_CONTENT', 'http://' . APP_STATIC_URL);
define ('LOG4PHP_DIR', PATH_CORE . DS . 'lib' . DS . 'log4php' . DS . 'src' . DS . 'log4php' . DS);
define ('LOG4PHP_CONFIGURATION', PATH_CORE . DS . 'config' . DS . 'Log4PHPConfig.xml');
require_once(LOG4PHP_DIR . 'LoggerManager.php');
define('FEED_CACHE_DIR', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS . 'FeedCache' . DS);
?>

View File

@@ -0,0 +1,6 @@
[db]
prodUser = testaem2
prodPass = aiKahxui6H
prodDb = testaem2
prodHost = mysql8.ceti.pl

View File

@@ -0,0 +1,16 @@
<?php
// ** Ustawienia MySQL-a - możesz uzyskać je od administratora Twojego serwera ** //
/** Nazwa bazy danych, której używać ma WordPress */
define('prodDb', '01244953_zurawik');
/** Nazwa użytkownika bazy danych MySQL */
define('prodUser', '01244953_zurawik');
/** Hasło użytkownika bazy danych MySQL */
define('prodPass', 'Df61Xz21');
/** Nazwa hosta serwera MySQL */
define('prodHost', 'mysql8');
?>

View File

@@ -0,0 +1,55 @@
<?php
define('ALLOWED_FILE_SIZE', '1100000');
define('CAPTCHA_SEED', 'qwerty12345');
define('CAPTCHA_COOKIE_NAME', 'k3nd3u');
define('CONTENT_PER_PAGE', '10');
define('COMMENTS_PER_PAGE', '10');
define('COMMENTS_PER_PAGE_MOST', '10');
define('APPLICATION_FILE_TYPE', '');
define('SMARTY_CACHING_METHOD', '0');
define('URL_DELIMITER', '/');
define('ADMIN_EMAIL', 'maciek@kloch.pl');
define('SERVER_MAIL_FROM', 'maciek@kloch.pl');
define('ERROR_REDIRECT', false);
define('DBCACHE_ENABLE', false);
define('QUERYCACHE_ENABLE', false);
define('WP_REKID', 7990);
define('DEVELOPER_MODE', true);
define('SMARTY_INTERNAL_CACHING', false);
define('CONTENT_MAX_DISP_LEN', 200);
/** ORDER TYPES **/
define ('ORDER_ASC', 'ASC');
define ('ORDER_DESC', 'DESC');
define ('ROUTER_SORT_LABEL', 'sortuj');
define ('ROUTER_DIR_LABEL', 'kierunek');
define ('ROUTER_PAGE_LABEL', 'page');
define('DEFAULT_SORT_FIELD', 'domyslne');
define('DEFAULT_SORT_DIR', 'asc');
define('PAGE_NEXT_LABEL', 'Następna »');
define('PAGE_PREV_LABEL', '« Poprzednia');
define('MIN_TAG_LENGTH', 3);
define('FEED_CACHE_ENABLED', true);
define('ADMIN_PANEL',false);
define('HEAD_TITLE', 'HEAD_TITLE');
define('HEAD_KEYWORDS', '');
define('HEAD_DESCRIPTION', '');
define('STATISTIC', '');
?>

View File

@@ -0,0 +1,36 @@
<?php
error_reporting(E_ALL);
//URL BEZ PREFIKSU http:// ORAZ BEZ KONCOWEGU UKOSNIKA
define ('APP_URL', 'zurawik.pl');
define ('APP_STATIC_URL', 'zurawik.pl/Static');
//OD TEGO MIEJSA NIC NIE ZMIENIAMY!!
define ('DS', DIRECTORY_SEPARATOR);
define ('PATH_CONFIG', pathinfo(__FILE__, PATHINFO_DIRNAME ) . DS);
define ('PATH_CORE', PATH_CONFIG . '..' . DS . '..' . DS);
define ('PATH_MAIN_APP', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS);
define ('PATH_STATIC_CONTENT', PATH_CONFIG . '..' . DS . '..' . DS . '..' . DS . 'Static' . DS);
define ('PATH_SMARTY_COMPILE', PATH_MAIN_APP . 'temp' . DS . 'compile' . DS );
define ('PATH_SMARTY_CACHE', PATH_MAIN_APP . 'temp' . DS . 'cache' . DS);
define ('PATH_SMARTY_TEMPLATE', PATH_MAIN_APP . 'template' . DS);
define ('PATH_SMARTY_PLUGINS', PATH_CORE . 'plugins' . DS . 'Smarty' . DS);
define ('DBCACHE_PATH', PATH_MAIN_APP . 'temp' . DS . 'dbcache' . DS);
define ('PATH_USER_SESSION', PATH_MAIN_APP . 'temp' . DS . 'session' . DS);
define ('URL_MAIN', 'https://' . APP_URL);
define ('URL_SITE_MAIN', URL_MAIN);
define ('FATAL_ERROR_URL' , 'https://' . APP_URL);
define ('URL_STATIC_CONTENT', 'https://' . APP_STATIC_URL);
define ('LOG4PHP_DIR', PATH_CORE . 'lib' . DS . 'log4php' . DS . 'src' . DS . 'php' . DS);
define ('LOG4PHP_CONFIGURATION', PATH_CORE . 'config' . DS . 'Log4PHPConfig.xml');
require_once(LOG4PHP_DIR . 'Logger.php');
?>

View File

@@ -0,0 +1,14 @@
<?
/**
* $Id: class.config.php 395 2008-05-28 19:41:06Z dakl $
* Tu zbieramy definicje wszystkich klas mozliwych do zaladowania z katalogu class jadra
*
*/
class CoreClassCollection {
const SESSION='SessionProxy';
const REQUEST='Request';
}
?>

325
core/core.php Normal file
View File

@@ -0,0 +1,325 @@
<?
include_once('class/Exception.class.php');
include_once('class/Config.class.php');
/**
*
* Klasa jadra aplikacji
*
*/
class Core {
/**
* Dopuszczalne typy stron..
*
* @var array
*/
private static $site = array('Strona', 'Admin', 'Dev');
public static $template = 'index.tpl';
public static $appSafeMode = false;
/**
* Konstruktor klasy
*
* @param PageType $site Typ strony
*/
public function __construct() {
}
/**
* Inicjator aplikacji
*
* @param integer $site
*/
public static function Init($site) {
include('class/DB.class.php');
include('class/Registry.class.php');
self::RequireOnce('class/DbSqlLite.class.php');
//print_r($site);
self::LoadConfig($site);
include('ErrorHandler.php');
try {
$db = new DBProd();
$dbTemp = new DBTemp();
} catch (MysqlException $e) {
//Utils::ArrayDisplay($e, __FILE__.' - '.__LINE__);
MFLog::Fatal("Line: " . $e->getLine() . " Message: " . $e->getMessage() . " Referer: " . getenv('HTTP_REFERER'));
}
//Utils::ArrayDisplay($db, __FILE__.' - '.__LINE__);
Registry::Set('db', $db);
Registry::Set('dbTemp', $dbTemp);
Config::Set('site', $site);
Registry::Set('smartyTemplate', self::$template);
$title = array();
Registry::Set('title', $title);
self::PageConfig();
}
public static function SetAppSafeMode() {
MFLog::Error('Switching into the SafeMod.');
if (Config::Get('ERROR_REDIRECT') == true) {
self::$appSafeMode = true;
}
}
public static function GetAppSafeMode() {
return self::$appSafeMode;
}
/**
* Parametry konfiguracyjne strony zmieniane przez autora lub administratora
*
*/
public static function PageConfig() {
try {
// zaczytuje do rejestru dane z tabeli Setup
$config = SetupDAL::GetAllVariables();
$rConfig = array();
foreach ($config as $key => $value) {
//Utils::ArrayDisplay($config);
$rConfig[$value['variable']] = $value['value'];
}
Config::SetDbConfig($rConfig);
} catch (MysqlException $e) {
self::SetAppSafeMode();
}
/*
$captchaStatus = true;
$moderateStatus = false;
Registry::Set('captchaStatus', $captchaStatus);
Registry::Set('moderateStatus', $moderateStatus);
*/
// ustawienia local dla czasu
setlocale(LC_TIME, 'pl_PL', 'pl', 'Polish_Poland.28592');
}
/**
* Ladowanie plikow konfiguracyjnych
*
* @param PageType $site Typ strony
*/
public static function LoadConfig($site) {
include_once('config/' . $site . '/path.config.php');
include_once('config/' . $site . '/param.config.php');
include_once('config/' . $site . '/db.config.php');
if ($site == 'Admin') {
include_once('config/' . $site . '/panel.config.php');
}
//-cONDIF INI DO WYYWALENIA!!
//Config::LoadIniConfig(Config::Get('PATH_CORE') . '/config/' . $site . '/db.config.ini', true);
}
/**
* Ladowanie i konfiguracja Smarty
*
*/
public static function LoadSmarty() {
require_once('lib/Smarty3/Smarty.class.php');
require_once('lib/SmartyValidate/libs/SmartyValidate.class.php');
$smarty = new Smarty();
$smarty->setErrorReporting(E_ALL ^E_DEPRECATED);
$smarty = new TemplateMaster();
//
$smarty->template_dir = Config::Get('PATH_SMARTY_TEMPLATE');
$smarty->compile_dir = Config::Get('PATH_SMARTY_COMPILE');
$smarty->cache_dir = Config::Get('PATH_SMARTY_CACHE');
$smarty->addPluginsDir(Config::Get('PATH_SMARTY_PLUGINS'));
$smarty->config_dir = Config::Get('PATH_CONFIG');
$smarty->cache_lifetime = 60;
//Utils::ArrayDisplay($smarty);
if(Config::Get('SMARTY_INTERNAL_CACHING') == true) {
$smarty->caching = Config::Get('SMARTY_CACHING_METHOD');
} else {
$smarty->caching = 0;
}
//$smarty->error_reporting = 0;
$smarty->assign('urlStatic', Config::Get('URL_STATIC_CONTENT'));
//$smarty->assign('commentIndent', COMMENT_INDENT);
$smarty->assign('dynamicContent', null);
$smarty->assign("pageStyle", 'style.css');
$smarty->assign('urlMain', Config::Get('URL_MAIN'));
$smarty->assign('pageDescription', null);
MFLog::Warn(serialize($smarty));
// //Utils::ArrayDisplay($smarty);
//$smarty->cache
//$smarty->testInstall();
Registry::Set('smarty', $smarty);
}
/**
* Wyswietla szablon Smarty
*
* @return Wgenerowana strona
*/
public static function SmartyDisplay() {
$smarty = Registry::Get('smarty');
return $smarty->display(self::$template);
}
/**
* Laduje pliki z klasami
*
* @param $name Nazwa pozadanej klasy
*/
public static function LoadClass($name) {
//echo $name." <br>";
if (file_exists(Config::Get('PATH_CORE') . '/class/' . $name . '.class.php')) {
self::RequireOnce(Config::Get('PATH_CORE') . '/class/' . $name . '.class.php');
} else if (file_exists(Config::Get('PATH_MAIN_APP') .'module/' . $name . '.mod.php')) {
self::RequireOnce(Config::Get('PATH_MAIN_APP').'module/' . $name . '.mod.php');
} else if (file_exists(Config::Get('PATH_CORE') . '/model/' . $name . '.class.php')) {
self::RequireOnce(Config::Get('PATH_CORE') . '/model/' . $name . '.class.php');
} else if (file_exists(Config::Get('PATH_CORE') . '/lib/' . $name . '.class.php')) {
self::RequireOnce(Config::Get('PATH_CORE') . '/lib/' . $name . '.class.php');
} else if (file_exists(PATH_CORE . '/model/' . strtolower(str_replace('DAL', '', $name)) . '/' . $name . '.class.php')) {
include(PATH_CORE . '/model/' . strtolower(str_replace('DAL', '', $name)) . '/' . $name . '.class.php');
} else {
//echo '/lib/' . $name . '.class.php'."<br>";
preg_match_all('/[A-Z]/', $name, $matches);
if (isset($matches[0][1])) {
$firstChar = substr($name, 0, 1);
$fullpathArray = explode($matches[0][1], substr($name, 1), 2);
$fullpathFile = PATH_CORE . '/model/' . strtolower($firstChar) . $fullpathArray[0] . '/' . $matches[0][1] . $fullpathArray[1] . '.class.php';
if (file_exists($fullpathFile)) {
include($fullpathFile);
}
}
$path = str_replace('_', '/', $name);
// $filePath = array_shift($filePath);
//
// if(is_array($filePath)) {
// $path = implode('/', $filePath);
// } else {
// $path = $filePath;
// }
// $name = str_replace($path.'_', '', $name);
if (file_exists(Config::Get('PATH_CORE') . '/' . $path . '.class.php')) {
self::RequireOnce(Config::Get('PATH_CORE') . '/' . $path . '.class.php');
} else if (file_exists(Config::Get('PATH_CORE') . '/class/' . $path . '.class.php')) {
self::RequireOnce(Config::Get('PATH_CORE') . '/class/' . $path . '.class.php');
} else if (file_exists(Config::Get('PATH_CORE') . '/model/' . $path . '.class.php')) {
self::RequireOnce(Config::Get('PATH_CORE') . '/model/' . $path . '.class.php');
} else if (file_exists(Config::Get('PATH_CORE') . '/lib/' . $path . '.class.php')) {
self::RequireOnce(Config::Get('PATH_CORE') . '/lib/' . $path . '.class.php');
}
}
}
/**
* Zamyka aplikacje
*
*/
public static function Garbage() {
$db = Registry::Get('db');
$db->__destruct();
}
public static function RequireOnce($file) {
//print_r($file);
require_once($file);
}
public static function LoadPlugin($plugin) {
self::RequireOnce('plugins/' . $plugin . '.php');
}
}
/**
* Klasa wyboru typu aplikacji
*
*/
class PageType {
/**
* Część użytkowa
*
*/
const STRONA = 'Strona';
/**
* Część użytkowa
*
*/
const Package = 'Package';
/**
* Część użytkowa
*
*/
//const Lubricant = 'Lubricant';
/**
* Część administracyjna
*/
//const Company = 'Company';
/**
* Część administracyjna
*/
const ADMIN = 'Admin';
/**
* Część serwerowa
*/
const SERVER = 'Server';
}
/**
* Bloka dynamiczny jako funkcja do smarty
*
* @param unknown_type $param
* @param unknown_type $content
* @param unknown_type $smarty
* @return unknown
*/
function SmartyBlockDynamic($param, $content, &$smarty) {
return $content;
}
/**
* Zwraca biezacy url
*
* @return unknown
*/
function SelfUrl() {
$s = (empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on")) ? "s" : "";
$protocol = StrLeft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/") . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":" . $_SERVER["SERVER_PORT"]);
return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
}
/**
* Funkcja pomocnicza do SelfUrl()
*
* @param unknown_type $s1
* @param unknown_type $s2
* @return unknown
*/
function StrLeft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
?>

242
core/lib/MimeType.class.php Normal file
View File

@@ -0,0 +1,242 @@
<?php
/**
*
* Klasa sprawdzająca na różne sposoby MimeType pliku.
*
*
* @date 8.03.2009
* @author Krystian Kuczek
*/
class MimeType {
const BY_FINFO = 0;
const BY_MIME_MAGIC = 1;
const BY_EXTENSION = 2;
const DEFAULT_BY = self::BY_EXTENSION;
const MAGIC_FILE = './mime.magic';
public static function GetFileMimeType($file) {
if (is_array($file)) {
$arr = true;
$fileTmp = $file['tmp_name'];
} else {
$arr = false;
}
switch(self::DEFAULT_BY) {
case self::BY_FINFO:
return self::GetMimeByFInfo($fileTmp);
case self::BY_MIME_MAGIC:
return self::GetMimeByMimeMagic($fileTmp);
case self::BY_EXTENSION:
if ($arr) {
return self::GetMimeByExtension($file['name']);
}
return self::GetMimeByExtension($file['name']);
}
}
public static function GetMimeByExtension($file) {
$exp = explode(".", $file);
$ext = $exp[sizeof($exp) - 1];
$mimeArray = self::ExtToMimeArray();
if (isset($mimeArray[$ext])) {
return $mimeArray[strtolower($ext)];
} else {
return "application/octet-stream";
}
}
public static function GetMimeByMimeMagic($file) {
return mime_content_type($file);
}
public static function GetMimeByFInfo($file) {
$res = finfo_open(FILEINFO_MIME, MAGIC_FILE);
$ret = $res->file($file);
finfo_close($file);
return $ret;
}
public function GetFileExtByMimeType($file) {
$mime = self::GetFileMimeType($file);
$mimeArray = self::MimeToExtArray();
}
public static function IsImage($file) {
$mime = self::GetFileMimeType($file);
switch ($mime) {
case "image/bmp":
case "image/gif":
case "image/jpeg":
case "image/png":
case "image/tiff":
return true;
default:
return false;
}
}
public static function IsMovie($file) {
$mime = self::GetFileMimeType($file);
switch ($mime) {
case "video/x-flv";
case "video/mpeg";
return true;
default:
return false;
}
}
private static function MimeToExtArray() {
return array(
"application/andrew-inset" => "ez",
"application/mac-binhex40" => "hqx",
"application/mac-compactpro" => "cpt",
"application/msword" => "doc",
"application/oda" => "oda",
"application/pdf" => "pdf",
"application/postscript" => "ps",
"application/smil" => "smil",
"application/vnd.wap.wbxml" => "wbxml",
"application/vnd.wap.wmlc" => "wmlc",
"application/vnd.wap.wmlscriptc" => "wmlsc",
"application/x-bcpio" => "bcpio",
"application/x-cdlink" => "vcd",
"application/x-chess-pgn" => "pgn",
"application/x-cpio" => "cpio",
"application/x-csh" => "csh",
"application/x-director" => "dir",
"application/x-dvi" => "dvi",
"application/x-futuresplash" => "spl",
"application/x-gtar" => "gtar",
"application/x-hdf" => "hdf",
"application/x-javascript" => "js",
"application/x-koan" => "skp",
"application/x-latex" => "latex",
"application/x-netcdf" => "nc",
"application/x-sh" => "sh",
"application/x-shar" => "shar",
"application/x-shockwave-flash" => "swf",
"application/x-stuffit" => "sit",
"application/x-sv4cpio" => "sv4cpio",
"application/x-sv4crc" => "sv4crc",
"application/x-tar" => "tar",
"application/x-tcl" => "tcl",
"application/x-tex" => "tex",
"application/x-texinfo" => "texinfo",
"application/x-troff" => "roff",
"application/x-troff-man" => "man",
"application/x-troff-me" => "me",
"application/x-troff-ms" => "ms",
"application/x-ustar" => "ustar",
"application/x-wais-source" => "src",
"application/xhtml+xml" => "xhtml",
"application/zip" => "zip",
"audio/basic" => "au",
"audio/midi" => "midi",
"audio/mpeg" => "mp3",
"audio/x-aiff" => "aiff",
"image/tiff" => "tif",
"audio/x-mpegurl" => "m3u",
"audio/x-pn-realaudio" => "ram",
"audio/x-pn-realaudio-plugin" => "rpm",
"audio/x-realaudio" => "ra",
"audio/x-wav" => "wav",
"chemical/x-pdb" => "pdb",
"chemical/x-xyz" => "xyz",
"image/bmp" => "bmp",
"image/gif" => "gif",
"image/ief" => "ief",
"image/jpeg" => "jpg",
"image/png" => "png",
"image/tiff" => "tiff",
"image/vnd.djvu" => "djvu",
"image/vnd.djvu" => "djv",
"image/vnd.wap.wbmp" => "wbmp",
"image/x-cmu-raster" => "ras",
"image/x-portable-anymap" => "pnm",
"image/x-portable-bitmap" => "pbm",
"image/x-portable-graymap" => "pgm",
"image/x-portable-pixmap" => "ppm",
"image/x-rgb" => "rgb",
"image/x-xbitmap" => "xbm",
"image/x-xpixmap" => "xpm",
"image/x-windowdump" => "xwd",
"model/iges" => "iges",
"model/mesh" => "mesh",
"model/vrml" => "vrml",
"text/css" => "css",
"text/html" => "html",
"text/plain" => "txt",
"text/richtext" => "rtx",
"text/rtf" => "rtf",
"text/sgml" => "sgml",
"text/tab-seperated-values" => "tsv",
"text/vnd.wap.wml" => "wml",
"text/vnd.wap.wmlscript" => "wmls",
"text/x-setext" => "etx",
"text/xml" => "xml",
"video/mpeg" => "mpg",
"video/x-flv" => "flv",
"video/quicktime" => "qt",
"video/vnd.mpegurl" => "mxu",
"video/x-msvideo" => "avi",
"video/x-sgi-movie" => "movie",
"x-conference-xcooltalk" => "ice"
);
}
public static function ExtToMimeArray() {
$mimeTypes = array_flip(self::MimeToExtArray());
$mimeTypes["jpeg"] = "image/jpeg";
$mimeTypes["jpe"] = "image/jpeg";
$mimeTypes["mov"] = "video/quicktime";
$mimeTypes["mpeg"] = "video/mpeg";
$mimeTypes["mpe"] = "video/mpeg";
$mimeTypes["xsl"] = "text/xml";
$mimeTypes["sgm"] = "text/sgml";
$mimeTypes["asc"] = "text/plain";
$mimeTypes["wrl"] = "model/vrml";
$mimeTypes["igs"] = "model/iges";
$mimeTypes["msh"] = "model/mesh";
$mimeTypes["silo"] = "model/mesh";
$mimeTypes["htm"] = "text/html";
$mimeTypes["snd"] = "audio/basic";
$mimeTypes["kar"] = "audio/midi";
$mimeTypes["mpga"] = "audio/mpeg";
$mimeTypes["mp2"] = "audio/mpeg";
$mimeTypes["aif"] = "audio/x-aiff";
$mimeTypes["aifc"] = "audio/x-aiff";
$mimeTypes["rm"] = "audio/x-pn-realaudio";
$mimeTypes["ai"] = "application/postscript";
$mimeTypes["eps"] = "application/postscript";
$mimeTypes["smi"] = "application/smil";
$mimeTypes["dcr"] = "application/x-director";
$mimeTypes["dxr"] = "application/x-director";
$mimeTypes["skd"] = "application/x-koan";
$mimeTypes["skt"] = "application/x-koan";
$mimeTypes["skm"] = "application/x-koan";
$mimeTypes["cdf"] = "application/x-netcdf";
$mimeTypes["texi"] = "application/x-texinfo";
$mimeTypes["t"] = "application/x-troff";
$mimeTypes["tr"] = "application/x-troff";
$mimeTypes["xht"] = "application/xhtml+xml";
$mimeTypes["mid"] = "audio/midi";
return $mimeTypes;
}
}
?>

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.20
* @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);
}
/**#@-*/
}
?>

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.20
* @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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

157
core/lib/Smarty/debug.tpl Normal file
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}

157
core/lib/Smarty/debug_1.tpl Normal file
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,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,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,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,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 = PATH_SMARTY_PLUGINS;
//Utils::ArrayDisplay($_ini_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,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,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,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,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,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,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: */
?>

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: */
?>

View File

@@ -0,0 +1,71 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Replace cached inserts with the actual results
*
* @param string $results
* @return string
*/
function smarty_core_process_cached_inserts($params, &$smarty)
{
preg_match_all('!'.$smarty->_smarty_md5.'{insert_cache (.*)}'.$smarty->_smarty_md5.'!Uis',
$params['results'], $match);
list($cached_inserts, $insert_args) = $match;
for ($i = 0, $for_max = count($cached_inserts); $i < $for_max; $i++) {
if ($smarty->debugging) {
$_params = array();
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
$debug_start_time = smarty_core_get_microtime($_params, $smarty);
}
$args = unserialize($insert_args[$i]);
$name = $args['name'];
if (isset($args['script'])) {
$_params = array('resource_name' => $smarty->_dequote($args['script']));
require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php');
if(!smarty_core_get_php_resource($_params, $smarty)) {
return false;
}
$resource_type = $_params['resource_type'];
$php_resource = $_params['php_resource'];
if ($resource_type == 'file') {
$smarty->_include($php_resource, true);
} else {
$smarty->_eval($php_resource);
}
}
$function_name = $smarty->_plugins['insert'][$name][0];
if (empty($args['assign'])) {
$replace = $function_name($args, $smarty);
} else {
$smarty->assign($args['assign'], $function_name($args, $smarty));
$replace = '';
}
$params['results'] = substr_replace($params['results'], $replace, strpos($params['results'], $cached_inserts[$i]), strlen($cached_inserts[$i]));
if ($smarty->debugging) {
$_params = array();
require_once(SMARTY_CORE_DIR . 'core.get_microtime.php');
$smarty->_smarty_debug_info[] = array('type' => 'insert',
'filename' => 'insert_'.$name,
'depth' => $smarty->_inclusion_depth,
'exec_time' => smarty_core_get_microtime($_params, $smarty) - $debug_start_time);
}
}
return $params['results'];
}
/* vim: set expandtab: */
?>

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