first commit

This commit is contained in:
2026-04-24 15:32:21 +02:00
commit 20d40fead4
5046 changed files with 641038 additions and 0 deletions

View File

@@ -0,0 +1,81 @@
<?php
/**
* $Id: Config.class.php 395 2008-05-28 19:41:06Z pawy $
* 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,753 @@
<?
/**
* $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);
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($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']);
$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);
}
?>

View File

@@ -0,0 +1,716 @@
<?
/**
* $Id: DB.class.php 982 2008-07-31 15:25:34Z dakl $
* Interfejs polaczenia z baza v2.2
*
*/
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;
}
// echo $this->dbh->host_info . "\n";
// $this->dbh = new mysqli($this->dbHost, $this->user, $this->pass);
// //$this->dbh = mysqli_connect($this->dbHost, $this->user, $this->pass);
// $this->dbh = new PDO('mysql:host='.$this->dbHost.';dbname='.$this->dbName.';charset='.$this->characterset, $this->user, $this->pass);
//
// if(empty($this->dbh)) {
// throw new MysqlException('Cannot connect to database!');
// }
}
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) {
// if(Enviroment::CheckMagicQuotes()) {
// $return = mysqli_real_escape_string($string);
// } else {
// $return = $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;
//Utils::ArrayDisplay( abs((int)$deltaTime));
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');
$this->dbHost = $db['prodHost'];
$this->dbName = $db['prodDb'];
$this->user = $db['prodUser'];
$this->pass = $db['prodPass'];
}
public function GetDbh() {
if (empty($this->dbh)) {
//$this->Connect(__METHOD__);
}
return $this->dbh;
}
}
?>

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,77 @@
<?php
/*
* Singleton slownika
*/
class Dictionary {
public static $rowSet = array();
public static $lang;
public static $allLangs = array();
public static function Init($lang) {
if (!in_array($lang, Router::$arrayLang)) {
throw new LangException('Incorrect language.');
}
self::$rowSet = MfDictionaryDAL::GetAllVariables($lang, 0);
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);
}
//Utils::ArrayDisplay(self::$allLangs);
}
public static function Translate($keyword) {
self::CheckAndAdd($keyword);
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) {
// $lang = 'pl';
$lang = Router::$curLang;
if (!key_exists($keyword, self::$rowSet)) {
//Utils::ArrayDisplay(self::$rowSet);
$isVariables = MfDictionaryDAL::IsVariables($keyword, $lang);
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);
//Utils::ArrayDisplay($keyword);
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,621 @@
<?
/**
* 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() {
if(is_file($this->directory.'/'.str_replace('_', '/', ucfirst($this->controller)).'.php')) {
Core::RequireOnce($this->directory.'/'.str_replace('_', '/', ucfirst($this->controller)).'.php');
Core::RequireOnce($this->directory.'/SharedController.php');
MFLog::Debug('Loading controller: '.$this->controller);
} else {
Core::RequireOnce($this->directory.'/'.ucfirst($this->defaultController).'.php');
Core::RequireOnce($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() {
if(is_file($this->directory.'/'.$this->config['module'].'/'.str_replace($this->config['module'].'_', '', ucfirst($this->controller)).'.php')) {
Core::RequireOnce($this->directory.'/'.$this->config['module'].'/'.str_replace($this->config['module'].'_', '', ucfirst($this->controller)).'.php');
Core::RequireOnce($this->directory.'/SharedController.php');
MFLog::Debug('Loading module: '.$this->config['module'].': '.$this->controller);
} else {
Core::RequireOnce($this->directory.'/'.ucfirst($this->defaultController).'.php');
Core::RequireOnce($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['param']['urlParam']);
$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() {
$headers = Registry::Get('headers');
$t = $headers['title'];
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(count($t)>1) {
$title = implode($this->titleDelimiter, $t);
} else if (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');
$smarty->assign('controller', strtolower(str_replace('Controller', '', $this->controller)));
$smarty->assign('method', strtolower($this->method));
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);
}
}
$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 {
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();
//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()) {
//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));
//}
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;
}
}
?>

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);
}
?>

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);
}
}
?>

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,453 @@
<?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()) {
$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);
//--------------------------------------------------------------------------
//===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($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());
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', '');
}
//=====Uruchamianie==ActionSet=====================================
$actionSetTemplate = '';
$config = $router->GetConfig();
$arrayConfig = unserialize($config);
$actionSet = $arrayConfig['actionSet'];
if (is_array($actionSet)) {
foreach ($actionSet as $action) {
$arrayAction = explode(',', $action);
$this->RunModuleController($arrayAction[0], $arrayAction[1], $param);
//Utils::ArrayDisplay('template :'.$arrayAction[1]);
$actionSetTemplate .= $this->smarty->get_template_vars(strtolower($arrayAction[1]));
//Utils::ArrayDisplay($this->smarty->get_template_vars($arrayAction[1]));
}
}
//Utils::ArrayDisplay($actionSetTemplate);
$this->smarty->assign('actionSetTemplate', $actionSetTemplate);
//-----------------------------------------------------------------
} 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'));
$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':
$this->GetRedirectInfo();
$this->AddScript('../../Admin/plugins/ckeditor/ckeditor.js');
$this->smarty->assign('projectName', PROJECT_NAME);
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('jQuery/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->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,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 @@
<?
/**
* $Id: Registry.class.php 395 2008-05-28 19:41:06Z dakl $
* 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 (get_magic_quotes_gpc()) {
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();
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,159 @@
<?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 = null, $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);
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();
}
}
?>

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 = null, $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;
}
}
?>