From 232aa1924c8c0f10d87b210b46c9f061af5c844c Mon Sep 17 00:00:00 2001 From: Antonio Gallo Date: Sun, 17 Oct 2010 13:29:57 +0000 Subject: added files --- h-source/Library/Array/Validate/Base.php | 241 ++++++ h-source/Library/Array/Validate/Soft.php | 85 ++ h-source/Library/Array/Validate/Strong.php | 180 ++++ h-source/Library/Array/Validate/index.html | 1 + h-source/Library/Array/index.html | 1 + h-source/Library/ArrayExt.php | 63 ++ h-source/Library/Bootstrap.php | 14 + h-source/Library/BoxParser.php | 69 ++ h-source/Library/Call.php | 321 ++++++++ h-source/Library/Controller.php | 291 +++++++ h-source/Library/Db/Mysql.php | 394 +++++++++ h-source/Library/Db/Mysqli.php | 400 +++++++++ h-source/Library/Db/index.html | 1 + h-source/Library/Email.php | 229 ++++++ h-source/Library/ErrorReporting.php | 25 + h-source/Library/Factory/Db.php | 52 ++ h-source/Library/Factory/index.html | 1 + h-source/Library/Files/Log.php | 97 +++ h-source/Library/Files/Upload.php | 451 ++++++++++ h-source/Library/Files/index.html | 1 + h-source/Library/Form/Checkbox.php | 41 + h-source/Library/Form/Entry.php | 45 + h-source/Library/Form/Form.php | 116 +++ h-source/Library/Form/Hidden.php | 23 + h-source/Library/Form/Html.php | 23 + h-source/Library/Form/InputText.php | 30 + h-source/Library/Form/Password.php | 30 + h-source/Library/Form/Radio.php | 30 + h-source/Library/Form/Select.php | 30 + h-source/Library/Form/Textarea.php | 30 + h-source/Library/Form/index.html | 1 + h-source/Library/Functions.php | 279 +++++++ h-source/Library/HeaderObj.php | 28 + h-source/Library/Helper/Array.php | 11 + h-source/Library/Helper/Html.php | 14 + h-source/Library/Helper/List.php | 278 +++++++ h-source/Library/Helper/Menu.php | 75 ++ h-source/Library/Helper/Pages.php | 108 +++ h-source/Library/Helper/Popup.php | 87 ++ h-source/Library/Helper/index.html | 1 + h-source/Library/Hooks.php | 21 + h-source/Library/Html/Form.php | 168 ++++ h-source/Library/Html/index.html | 1 + h-source/Library/Image/Gd/Captcha.php | 85 ++ h-source/Library/Image/Gd/Thumbnail.php | 151 ++++ h-source/Library/Image/Gd/index.html | 1 + h-source/Library/Image/index.html | 1 + h-source/Library/Lang/Eng/DbCondStrings.php | 17 + h-source/Library/Lang/Eng/ModelStrings.php | 19 + h-source/Library/Lang/Eng/UploadStrings.php | 27 + h-source/Library/Lang/Eng/ValCondStrings.php | 76 ++ h-source/Library/Lang/Eng/index.html | 1 + h-source/Library/Lang/ResultStrings.php | 25 + h-source/Library/Lang/index.html | 1 + h-source/Library/ModAbstract.php | 25 + h-source/Library/Model/Base.php | 1140 ++++++++++++++++++++++++++ h-source/Library/Model/Map.php | 439 ++++++++++ h-source/Library/Model/Tree.php | 287 +++++++ h-source/Library/Model/index.html | 1 + h-source/Library/Params.php | 37 + h-source/Library/Popup.php | 15 + h-source/Library/Request.php | 39 + h-source/Library/Scaffold.php | 272 ++++++ h-source/Library/Strings/Functions.php | 30 + h-source/Library/Theme.php | 79 ++ h-source/Library/Url.php | 36 + h-source/Library/Users/CheckAdmin.php | 369 +++++++++ h-source/Library/Users/index.html | 1 + h-source/Library/index.html | 1 + 69 files changed, 7562 insertions(+) create mode 100644 h-source/Library/Array/Validate/Base.php create mode 100644 h-source/Library/Array/Validate/Soft.php create mode 100644 h-source/Library/Array/Validate/Strong.php create mode 100644 h-source/Library/Array/Validate/index.html create mode 100644 h-source/Library/Array/index.html create mode 100755 h-source/Library/ArrayExt.php create mode 100755 h-source/Library/Bootstrap.php create mode 100644 h-source/Library/BoxParser.php create mode 100755 h-source/Library/Call.php create mode 100755 h-source/Library/Controller.php create mode 100755 h-source/Library/Db/Mysql.php create mode 100644 h-source/Library/Db/Mysqli.php create mode 100644 h-source/Library/Db/index.html create mode 100644 h-source/Library/Email.php create mode 100644 h-source/Library/ErrorReporting.php create mode 100755 h-source/Library/Factory/Db.php create mode 100644 h-source/Library/Factory/index.html create mode 100644 h-source/Library/Files/Log.php create mode 100755 h-source/Library/Files/Upload.php create mode 100644 h-source/Library/Files/index.html create mode 100755 h-source/Library/Form/Checkbox.php create mode 100755 h-source/Library/Form/Entry.php create mode 100755 h-source/Library/Form/Form.php create mode 100755 h-source/Library/Form/Hidden.php create mode 100644 h-source/Library/Form/Html.php create mode 100755 h-source/Library/Form/InputText.php create mode 100644 h-source/Library/Form/Password.php create mode 100755 h-source/Library/Form/Radio.php create mode 100755 h-source/Library/Form/Select.php create mode 100755 h-source/Library/Form/Textarea.php create mode 100644 h-source/Library/Form/index.html create mode 100755 h-source/Library/Functions.php create mode 100644 h-source/Library/HeaderObj.php create mode 100755 h-source/Library/Helper/Array.php create mode 100755 h-source/Library/Helper/Html.php create mode 100755 h-source/Library/Helper/List.php create mode 100755 h-source/Library/Helper/Menu.php create mode 100755 h-source/Library/Helper/Pages.php create mode 100755 h-source/Library/Helper/Popup.php create mode 100644 h-source/Library/Helper/index.html create mode 100644 h-source/Library/Hooks.php create mode 100644 h-source/Library/Html/Form.php create mode 100644 h-source/Library/Html/index.html create mode 100644 h-source/Library/Image/Gd/Captcha.php create mode 100644 h-source/Library/Image/Gd/Thumbnail.php create mode 100644 h-source/Library/Image/Gd/index.html create mode 100644 h-source/Library/Image/index.html create mode 100644 h-source/Library/Lang/Eng/DbCondStrings.php create mode 100644 h-source/Library/Lang/Eng/ModelStrings.php create mode 100644 h-source/Library/Lang/Eng/UploadStrings.php create mode 100644 h-source/Library/Lang/Eng/ValCondStrings.php create mode 100644 h-source/Library/Lang/Eng/index.html create mode 100644 h-source/Library/Lang/ResultStrings.php create mode 100644 h-source/Library/Lang/index.html create mode 100644 h-source/Library/ModAbstract.php create mode 100755 h-source/Library/Model/Base.php create mode 100755 h-source/Library/Model/Map.php create mode 100755 h-source/Library/Model/Tree.php create mode 100644 h-source/Library/Model/index.html create mode 100644 h-source/Library/Params.php create mode 100755 h-source/Library/Popup.php create mode 100644 h-source/Library/Request.php create mode 100755 h-source/Library/Scaffold.php create mode 100644 h-source/Library/Strings/Functions.php create mode 100755 h-source/Library/Theme.php create mode 100755 h-source/Library/Url.php create mode 100755 h-source/Library/Users/CheckAdmin.php create mode 100644 h-source/Library/Users/index.html create mode 100644 h-source/Library/index.html (limited to 'h-source/Library') diff --git a/h-source/Library/Array/Validate/Base.php b/h-source/Library/Array/Validate/Base.php new file mode 100644 index 0000000..3366097 --- /dev/null +++ b/h-source/Library/Array/Validate/Base.php @@ -0,0 +1,241 @@ +_lang = $lang; + $stringClass = 'Lang_'.$this->_lang.'_ValCondStrings'; + if (!class_exists($stringClass)) + { + $stringClass = 'Lang_Eng_ValCondStrings'; + } + $this->_resultString = new $stringClass(); + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are not '' and are equal (===) to each other + public function checkEqual($associativeArray,$keyString) + { + $errorString = null; + $keyArray = explode(',',$keyString); + $numb = 0; + + //set the first value to null + $firstValue = null; + + foreach ($keyArray as $key) + { + if (array_key_exists($key,$associativeArray)) + { + $firstValue = $associativeArray[$key]; + break; + } + } + + if (isset($firstValue)) + { + for ($i = 0; $i < count($keyArray); $i++) + { + if (array_key_exists($keyArray[$i],$associativeArray)) + { + if (strcmp($associativeArray[$keyArray[$i]],$firstValue) !== 0) + { + $numb++; + $errorString = $this->_resultString->getNotEqualResultString($keyString); + } + } + } + } + + $this->errorString = $errorString; + return $numb === 0 ? true : false; + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are alphabetic values + //$strength: hard or soft. If $strength is set equal to soft than non check is made upon array values equalt to '' or null + public function checkAlpha($associativeArray,$keyString,$strength = 'strong') + { + return $this->checkGeneric($associativeArray,$keyString,$strength,'ctype_alpha','getNotAlphabeticResultString'); + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are alphanumeric values + //$strength: hard or soft. If $strength is set equal to soft than non check is made upon array values equalt to '' or null + public function checkAlphaNum($associativeArray,$keyString,$strength = 'strong') + { + return $this->checkGeneric($associativeArray,$keyString,$strength,'ctype_alnum','getNotAlphanumericResultString'); + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are decimal digits + //$strength: hard or soft. If $strength is set equal to soft than non check is made upon array values equalt to '' or null + public function checkDigit($associativeArray,$keyString,$strength = 'strong') + { + return $this->checkGeneric($associativeArray,$keyString,$strength,'ctype_digit','getNotDecimalDigitResultString'); + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) have mail format + //$strength: hard or soft. If $strength is set equal to soft than non check is made upon array values equalt to '' or null + public function checkMail($associativeArray,$keyString,$strength = 'strong') + { + return $this->checkGeneric($associativeArray,$keyString,$strength,'checkMail','getNotMailFormatResultString'); + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) is a number (integer or number). It makes use of the is_numeric PHP built-in function + //$strength: hard or soft. If $strength is set equal to soft than non check is made upon array values equalt to '' or null + public function checkNumeric($associativeArray,$keyString,$strength = 'strong') + { + return $this->checkGeneric($associativeArray,$keyString,$strength,'is_numeric','getNotNumericResultString'); + } + + + //apply a generic check function + //$strength: hard or soft. If $strength is set equal to soft than non check is made upon array values equalt to '' or null + //$func: the function to apply + //$strFunc: the method of the object $this->_resultString to apply + private function checkGeneric($associativeArray,$keyString,$strength,$func,$strFunc) + { + + $errorString = null; + $keyArray = explode(',',$keyString); + $numb = 0; + + for ($i = 0; $i < count($keyArray); $i++) + { + if (array_key_exists($keyArray[$i],$associativeArray)) + { + if (strcmp($associativeArray[$keyArray[$i]],'') !== 0 or $strength === 'strong') + { + if (!call_user_func($func,$associativeArray[$keyArray[$i]])) + { + $numb++; + $errorString .= call_user_func(array($this->_resultString,$strFunc),$keyArray[$i]); + } + } + } + } + + $this->errorString = $errorString; + return $numb === 0 ? true : false; + + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) have a number of chars smaller than $maxLenght + public function checkLength($associativeArray,$keyString,$maxLength = 10) + { + $errorString = null; + $keyArray = explode(',',$keyString); + $numb = 0; + for ($i = 0; $i < count($keyArray); $i++) + { + if (array_key_exists($keyArray[$i],$associativeArray)) + { + if (eg_strlen($associativeArray[$keyArray[$i]]) > $maxLength) + { + $numb++; + $errorString .= $this->_resultString->getLengthExceedsResultString($keyArray[$i],$maxLength); + } + } + } + $this->errorString = $errorString; + return $numb === 0 ? true : false; + + } + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are different from the values indicated in the argument $strings (a comma-separated list of words) + public function checkIsNotStrings($associativeArray,$keyString,$strings = '') + { + $errorString = null; + $keyArray = explode(',',$keyString); + $numb = 0; + //get the array from the comma-separated list of strings + $stringsArray = explode(',',$strings); + for ($i = 0; $i < count($keyArray); $i++) + { + if (array_key_exists($keyArray[$i],$associativeArray)) + { + foreach ($stringsArray as $string) + { + if (strcmp($associativeArray[$keyArray[$i]],$string) === 0) + { + $numb++; + $errorString .= $this->_resultString->getIsForbiddenStringResultString($keyArray[$i],$strings); + } + } + } + } + $this->errorString = $errorString; + return $numb === 0 ? true : false; + } + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are one of the values indicated in the argument $strings (a comma-separated list of words) + //$strength: hard or soft. If $strength is set equal to soft than non check is made upon array values equalt to '' or null + public function checkIsStrings($associativeArray,$keyString,$strings = '',$strength = 'strong') + { + $errorString = null; + $keyArray = explode(',',$keyString); + $numb = 0; + //get the array from the comma-separated list of strings + $stringsArray = explode(',',$strings); + for ($i = 0; $i < count($keyArray); $i++) + { + if (array_key_exists($keyArray[$i],$associativeArray)) + { + if (strcmp($associativeArray[$keyArray[$i]],'') !== 0 or $strength === 'strong') + { + if (!in_array($associativeArray[$keyArray[$i]],$stringsArray)) + { + $numb++; + $errorString .= $this->_resultString->getIsNotStringResultString($keyArray[$i],$strings); + } + } + } + } + $this->errorString = $errorString; + return $numb === 0 ? true : false; + } + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) match the regular expression $regExp + public function checkMatch($associativeArray,$keyString,$regExp = '/./',$strength = 'strong') + { + $errorString = null; + $keyArray = explode(',',$keyString); + $numb = 0; + for ($i = 0; $i < count($keyArray); $i++) + { + if (array_key_exists($keyArray[$i],$associativeArray)) + { + if (strcmp($associativeArray[$keyArray[$i]],'') !== 0 or $strength === 'strong') + { + if (!preg_match($regExp,$associativeArray[$keyArray[$i]])) + { + $numb++; + $errorString .= $this->_resultString->getDoesntMatchResultString($keyArray[$i],$regExp); + } + } + } + } + $this->errorString = $errorString; + return $numb === 0 ? true : false; + } + +} \ No newline at end of file diff --git a/h-source/Library/Array/Validate/Soft.php b/h-source/Library/Array/Validate/Soft.php new file mode 100644 index 0000000..95e208d --- /dev/null +++ b/h-source/Library/Array/Validate/Soft.php @@ -0,0 +1,85 @@ +_resultString->getNotDefinedResultString($keyArray[$i]); + $numb++; + } + } + else + { + $errorString .= $this->_resultString->getNotDefinedResultString($keyArray[$i]); + $numb++; + } + } + $this->errorString = $errorString; + $this->errorNumb = $numb; + return $numb === 0 ? true : false; + } + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are not '' and are equal (===) to each other + public function checkEqual($associativeArray,$keyString) + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkEqual($associativeArray,$keyString); + + } else { + return false; + } + } + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are alphabetic values + public function checkAlpha($associativeArray,$keyString) + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkAlpha($associativeArray,$keyString,'strong'); + + } else { + return false; + } + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are alphanumeric values + public function checkAlphaNum($associativeArray,$keyString) + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkAlphaNum($associativeArray,$keyString,'strong'); + + } else { + return false; + } + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are decimal digits + public function checkDigit($associativeArray,$keyString) + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkDigit($associativeArray,$keyString,'strong'); + + } else { + return false; + } + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) have mail format + public function checkMail($associativeArray,$keyString) + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkMail($associativeArray,$keyString,'strong'); + + } else { + return false; + } + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) is a number (integer or number). It makes use of the is_numeric PHP built-in function + public function checkNumeric($associativeArray,$keyString) + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkNumeric($associativeArray,$keyString,'strong'); + + } else { + return false; + } + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) have a number of chars smaller than $maxLenght + public function checkLength($associativeArray,$keyString,$maxLength = 10) + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkLength($associativeArray,$keyString,$maxLength); + + } else { + return false; + } + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are different from the values indicated in the argument $strings (a comma-separated list of words) + public function checkIsNotStrings($associativeArray,$keyString,$strings = '') + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkIsNotStrings($associativeArray,$keyString,$strings); + + } else { + return false; + } + } + + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) are one of the values indicated in the argument $strings (a comma-separated list of words) + public function checkIsStrings($associativeArray,$keyString,$strings = '') + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkIsStrings($associativeArray,$keyString,$strings,'strong'); + + } else { + return false; + } + } + + //verify that the values of the associative array ($associativeArray) indicated by the key string ($keyString) match the regular expression $regExp + public function checkMatch($associativeArray,$keyString,$regExp = '/./') + { + if ($this->checkNotEmpty($associativeArray,$keyString)) + { + + return parent::checkMatch($associativeArray,$keyString,$regExp,'strong'); + + } else { + return false; + } + } +} \ No newline at end of file diff --git a/h-source/Library/Array/Validate/index.html b/h-source/Library/Array/Validate/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Array/Validate/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Array/index.html b/h-source/Library/Array/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Array/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/ArrayExt.php b/h-source/Library/ArrayExt.php new file mode 100755 index 0000000..93eca91 --- /dev/null +++ b/h-source/Library/ArrayExt.php @@ -0,0 +1,63 @@ +subset($associativeArray,$complementaryKeyString,$func); + } + +} diff --git a/h-source/Library/Bootstrap.php b/h-source/Library/Bootstrap.php new file mode 100755 index 0000000..796b22f --- /dev/null +++ b/h-source/Library/Bootstrap.php @@ -0,0 +1,14 @@ +module name tag defines the name of the object that has to be instantiate and saved in the +//$modules property (that is an array referencing different module objects) array(moduleObj1,moduleObj2, ...) +//if the module class corresponding ot the module name tag does not exists, than no module is created and the next module name is checked +class BoxParser { + + public $modules = array(); //array referencing different module classes --> array(moduleObj1,moduleObj2, ...) See files inside the Application/Modules folder + + //$simpleXMLText: it has to be an XML text + //$type; it can be string or file. + public function __construct($simpleXMLText, $type = 'string') + { + if ($type === 'string') + { + if (@simplexml_load_string($simpleXMLText)) + { + $simpleXmlObj = simplexml_load_string($simpleXMLText); + $this->populate($simpleXmlObj); + } + } + else if ($type === 'file') + { + if (@simplexml_load_file($simpleXMLText)) + { + $simpleXmlObj = simplexml_load_file($simpleXMLText); + $this->populate($simpleXmlObj); + } + } + } + + //inistantiate the module objects and save them in the $this->modules property array + private function populate($simpleXmlObj) + { + foreach ($simpleXmlObj as $mod) + { + $className = 'Mod'.ucwords((string)$mod->type); + if (class_exists($className)) + { + if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Modules' . DS . $className . '.php')) + { + $newModule = new $className($mod); + if ($newModule instanceof ModAbstract) + { + $this->modules[] = $newModule; + } + } + } + } + } + + //create the HTML of the modules + public function render() + { + $HTML = null; + foreach ($this->modules as $module) + { + $HTML .= $module->render(); + } + return $HTML; + } + +} \ No newline at end of file diff --git a/h-source/Library/Call.php b/h-source/Library/Call.php new file mode 100755 index 0000000..d80f1d4 --- /dev/null +++ b/h-source/Library/Call.php @@ -0,0 +1,321 @@ + $value) + { + if (strlen($value) > MAX_POST_LENGTH) die('the length of some of the $_POST values is too large'); + } + } +} + +function checkRequestUriLength() +{ + if (MAX_REQUEST_URI_LENGTH !== 0) + { + if (strlen($_SERVER['REQUEST_URI']) > MAX_REQUEST_URI_LENGTH) die('the length of the REQUEST_URI is too large'); + } +} + +function checkRegisterGlobals() +{ + if (ini_get('register_globals')) die('register globals is on: easyGiant works only with register globals off'); +} + +function callHook() +{ + + if (MOD_REWRITE_MODULE === true) + { + $url = isset($_GET['url']) ? $_GET['url'] : DEFAULT_CONTROLLER . '/' . DEFAULT_ACTION; + } + else + { + $url = (strcmp(getQueryString(),"") !== 0) ? getQueryString() : DEFAULT_CONTROLLER . '/' . DEFAULT_ACTION; + } + + //rewrite the URL +// if (Route::$rewrite === 'yes') +// { +// $url = rewrite($url); +// } + +// echo $url; + + $urlArray = array(); + $urlArray = explode("/",$url); + + $controller = DEFAULT_CONTROLLER; + $action = DEFAULT_ACTION; + + if (isset($urlArray[0])) + { + $controller = (strcmp($urlArray[0],'') !== 0) ? strtolower(trim($urlArray[0])) : DEFAULT_CONTROLLER; + } + + array_shift($urlArray); + + if (isset($urlArray[0])) + { + $action = (strcmp($urlArray[0],'') !== 0) ? strtolower(trim($urlArray[0])) : DEFAULT_ACTION; + } + + //set ERROR_CONTROLLER and ERROR_ACTION + $errorController = ERROR_CONTROLLER !== false ? ERROR_CONTROLLER : DEFAULT_CONTROLLER; + $errorAction = ERROR_ACTION !== false ? ERROR_ACTION : DEFAULT_ACTION; + + /* + VERIFY THE ACTION NAME + */ + if (method_exists('Controller', $action) or !ctype_alnum($action) or (strcmp($action,'') === 0)) + { + $controller = $errorController; + $action = $errorAction; + $urlArray = array(); + } + + /* + VERIFY THE CONTROLLER NAME + */ + if (!ctype_alnum($controller) or (strcmp($controller,'') === 0)) + { + $controller = $errorController; + $action = $errorAction; + $urlArray = array(); + } + + //check that the controller class belongs to the application/controllers folder + //otherwise set the controller to the default controller + if (!file_exists(ROOT.DS.APPLICATION_PATH.DS.'Controllers'.DS.ucwords($controller).'Controller.php')) + { + $controller = $errorController; + $action = $errorAction; + $urlArray = array(); + } + + //set the controller class to DEFAULT_CONTROLLER if it doesn't exists + if (!class_exists(ucwords($controller).'Controller')) + { + $controller = $errorController; + $action = $errorAction; + $urlArray = array(); + } + + //set the action to DEFAULT_ACTION if it doesn't exists + if (!method_exists(ucwords($controller).'Controller', $action)) + { + $controller = $errorController; + $action = $errorAction; + $urlArray = array(); + } + + /* + CHECK COUPLES CONTROLLER,ACTION + */ + if (!in_array('all',Route::$allowed)) + { + $couple = "$controller,$action"; + if (!in_array($couple,Route::$allowed)) + { + $controller = $errorController; + $action = $errorAction; + $urlArray = array(); + } + } + + array_shift($urlArray); + $queryString = $urlArray; + //set the name of the application + $application = $controller; + $controller = ucwords($controller); + $model = $controller; + $controller .= 'Controller'; + $model .= 'Model'; + + //include the file containing the set of actions to carry out before the initialization of the controller class + Hooks::load(ROOT . DS . APPLICATION_PATH . DS . 'Hooks' . DS . 'BeforeInitialization.php'); + + if (class_exists($controller)) + { + $dispatch = new $controller($model,$application,$queryString); + + //pass the action to the controller object + $dispatch->action = $action; + $dispatch->currPage = $dispatch->baseUrl.'/'.$dispatch->controller.'/'.$dispatch->action; + + //require the file containing the set of actions to carry out after the initialization of the controller class + Hooks::load(ROOT . DS . APPLICATION_PATH . DS . 'Hooks' . DS . 'AfterInitialization.php'); + + $templateFlag= true; + + if (method_exists($controller, $action)) + { + //pass the action to the theme object + $dispatch->theme->action = $action; + $dispatch->theme->currPage = $dispatch->baseUrl.'/'.$dispatch->controller.'/'.$dispatch->action; + + call_user_func_array(array($dispatch,$action),$queryString); + } + else + { + $templateFlag= false; + } + + if ($templateFlag) + { + $dispatch->theme->render(); + } + + } + else + { + echo "

the '$controller' controller is not present!

"; + } + +} + + +// //rewrite the URL +// function rewrite($url) +// { +// foreach (Route::$map as $key => $address) +// { +// if (preg_match('/^'.$key.'/',$url)) +// { +// return preg_replace('/^'.$key.'/',$address,$url); +// } +// } +// return ERROR_CONTROLLER.'/'.ERROR_ACTION; +// } + +function getQueryString() +{ + + if (strstr($_SERVER['REQUEST_URI'],'index.php/')) + { + return Params::$mbStringLoaded === true ? mb_substr(mb_strstr($_SERVER['REQUEST_URI'],'index.php/'),10) : substr(strstr($_SERVER['REQUEST_URI'],'index.php/'),10); + } + + return ''; +} + +function __autoload($className) +{ + + $backupName = $className; + + if (strstr($className,'_')) + { + $parts = explode('_',$className); + $className = implode(DS,$parts); + } + + if (file_exists(ROOT . DS . 'Library' . DS . $className . '.php')) + { + require_once(ROOT . DS . 'Library' . DS . $className . '.php'); + } + else if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Controllers' . DS . $backupName . '.php')) + { + require_once(ROOT . DS . APPLICATION_PATH . DS . 'Controllers' . DS . $backupName . '.php'); + } + else if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Models' . DS . $backupName . '.php')) + { + require_once(ROOT . DS . APPLICATION_PATH . DS . 'Models' . DS . $backupName . '.php'); + } + else if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Modules' . DS . $backupName . '.php')) + { + require_once(ROOT . DS . APPLICATION_PATH . DS . 'Modules' . DS . $backupName . '.php'); + } + else if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Strings' . DS . $className . '.php')) + { + require_once(ROOT . DS . APPLICATION_PATH . DS . 'Strings' . DS . $className . '.php'); + } + +} + +try { + + //check the length of the $_POST values + checkPostLength(); + + //check the length of the REQUEST_URI + checkRequestUriLength(); + + //connect to the database + Factory_Db::getInstance(DATABASE_TYPE,array(HOST,USER,PWD,DB)); + + //set htmlentities charset + switch (DEFAULT_CHARSET) + { + case 'SJIS': + Params::$htmlentititiesCharset = 'Shift_JIS'; + break; + } + + $allowedCharsets = array('UTF-8','ISO-8859-1','EUC-JP','SJIS'); + if (!in_array(DEFAULT_CHARSET,$allowedCharsets)) die('charset not-allowed'); + + //check if the mbstring extension is loaded + if (extension_loaded('mbstring')) + { + //set the internal encoding + mb_internal_encoding(DEFAULT_CHARSET); + Params::$mbStringLoaded = true; + } + + //load the files defined inside Config/Autoload.php + foreach (Autoload::$files as $file) + { + $ext = strtolower(end(explode('.', $file))); + $path = ROOT . DS . APPLICATION_PATH . DS . 'Include' . DS . $file; + if (file_exists($path) and $ext === 'php') + { + require_once($path); + } + } + + //include the file containing the set of actions to carry out before the check of the super global array + Hooks::load(ROOT . DS . APPLICATION_PATH . DS . 'Hooks' . DS . 'BeforeChecks.php'); + + //sanitize super global arrays + sanitizeSuperGlobal(); + + //report errors + ErrorReporting(); + + //verify that register globals is not active + checkRegisterGlobals(); + + //call the main hook + callHook(); + + //disconnect to the database + Factory_Db::disconnect(DATABASE_TYPE); + +} catch (Exception $e) { + + echo '
Message: '.$e->getMessage().'
'; + +} \ No newline at end of file diff --git a/h-source/Library/Controller.php b/h-source/Library/Controller.php new file mode 100755 index 0000000..9ceaa5f --- /dev/null +++ b/h-source/Library/Controller.php @@ -0,0 +1,291 @@ +viewArgs) + + public $theme; + public $baseUrl = null; //the base url of the website: http://domainname + public $baseUrlSrc = null; //the base url of the website (http://domainname) if MOD_REWRITE_MODULE has been set to false + + public $headerObj; //reference to headerObj class + +// protected $_users; //object to manage access + + protected $scaffold = null; //the reference to the scaffold object + + function __construct($model, $controller, $queryString = array()) { + + $this->controller = $controller; + $this->modelName = $model; + $this->_queryString = $queryString; + + $this->theme = new Theme($controller); + $this->baseUrl = $this->theme->baseUrl; + $this->baseUrlSrc = $this->theme->baseUrlSrc; + + $this->headerObj = new HeaderObj(DOMAIN_NAME); + $this->request = new Request(); + } + + //redirect to $path after the time $time + final public function redirect($path,$time = 0,$string = null) + { + $this->headerObj->redirect($path,$time,$string); + } + + //set the $_data structure of the theme + final public function set($value) + { + $this->theme->set($value); + } + + //append values to the $_data structure of the theme + final public function append($value) + { + $this->theme->append($value); + } + + //load a view file + final public function load($viewFile,$option = 'none') { + $this->theme->load($viewFile,$option); + } + + //clean the array containing the view files to load + final public function clean() { + $this->theme->clean(); + } + + //load an helper class + final function helper($helperName) { + $args = func_get_args(); + array_shift($args); + $name = 'Helper_'.$helperName; + if (class_exists($name)) + { + $this->h[$helperName] = new $name(); + + if ($this->h[$helperName] instanceof Helper_Html) { + $this->h[$helperName]->viewArgs = $this->viewArgs; + $this->h[$helperName]->viewStatus = $this->viewStatus; + } + + if (method_exists($this->h[$helperName], 'build')) { + call_user_func_array(array($this->h[$helperName],'build'),$args); + } + } + + } + + //load a model class + //$name: the name of the model class + final public function model($name = null) { + $modelName = isset($name) ? $name : $this->modelName; + if (class_exists($modelName)) { + $this->m[$modelName] = new $modelName(); + } else { + throw new Exception('Error in '.__METHOD__.': class "'.$modelName.'" has not been defined'); + } + } + + //load a controller + //$controllerName: the name of the controller class to load + final public function controller($controller) + { + if (class_exists($controller)) { + $model = str_replace('Controller',null,$controller).'Model'; + $application = strtolower(str_replace('Controller',null,$controller)); + $this->c[$controller] = new $controller($model,$application,array()); + $this->c[$controller]->theme = $this->theme; + } + } + + //load a users_checkAdmin class + //$sessonType: the type of session. It can be 'admin' (in the case of the access of an admin user) or 'registered' (in the case of the access of a registerd user) + final public function session($sessionType = 'admin') { + $sessionTypeArray = array('admin','registered'); + if (!in_array($sessionType,$sessionTypeArray)) { + throw new Exception('Error in '.__METHOD__.': the session type can be \'admin\' or \'registered\' only'); + } + //admin session + if ($sessionType === 'admin') { + $params = array( + 'users_controller' => ADMIN_USERS_CONTROLLER, + 'users_login_action' => ADMIN_USERS_LOGIN_ACTION, + 'panel_controller' => ADMIN_PANEL_CONTROLLER, + 'panel_main_action' => ADMIN_PANEL_MAIN_ACTION, + 'cookie_name' => ADMIN_COOKIE_NAME, + 'sessionsTable' => ADMIN_SESSIONS_TABLE, + 'usersTable' => ADMIN_USERS_TABLE, + 'groupsTable' => ADMIN_GROUPS_TABLE, + 'manyToManyTable' => ADMIN_MANYTOMANY_TABLE, + 'accessesTable' => ADMIN_ACCESSES_TABLE, + 'session_expire' => ADMIN_SESSION_EXPIRE, + 'cookie_path' => ADMIN_COOKIE_PATH, + 'database_type' => DATABASE_TYPE, + 'hijacking_check' => ADMIN_HIJACKING_CHECK, + 'on_hijacking_event' => ADMIN_ON_HIJACKING_EVENT, + 'hijacking_action' => ADMIN_HIJACKING_ACTION, + 'time_after_failure' => ADMIN_TIME_AFTER_FAILURE, + 'password_hash' => PASSWORD_HASH, + 'cookie_domain' => ADMIN_COOKIE_DOMAIN, + 'cookie_secure' => ADMIN_COOKIE_SECURE + ); + $this->s['admin'] = new Users_CheckAdmin($params); + } + //registered session + if ($sessionType === 'registered') { + $params = array( + 'users_controller' => REG_USERS_CONTROLLER, + 'users_login_action' => REG_USERS_LOGIN_ACTION, + 'panel_controller' => REG_PANEL_CONTROLLER, + 'panel_main_action' => REG_PANEL_MAIN_ACTION, + 'cookie_name' => REG_COOKIE_NAME, + 'sessionsTable' => REG_SESSIONS_TABLE, + 'usersTable' => REG_USERS_TABLE, + 'groupsTable' => REG_GROUPS_TABLE, + 'manyToManyTable' => REG_MANYTOMANY_TABLE, + 'accessesTable' => REG_ACCESSES_TABLE, + 'session_expire' => REG_SESSION_EXPIRE, + 'cookie_path' => REG_COOKIE_PATH, + 'database_type' => DATABASE_TYPE, + 'hijacking_check' => REG_HIJACKING_CHECK, + 'on_hijacking_event' => REG_ON_HIJACKING_EVENT, + 'hijacking_action' => REG_HIJACKING_ACTION, + 'time_after_failure' => REG_TIME_AFTER_FAILURE, + 'password_hash' => PASSWORD_HASH, + 'cookie_domain' => REG_COOKIE_DOMAIN, + 'cookie_secure' => REG_COOKIE_SECURE + ); + $this->s['registered'] = new Users_CheckAdmin($params); + } + } + + //method to set $this->argKeys. Chenge the string in the array! + final public function setArgKeys($argKeys) { +// $this->argKeys = explode(',',$argKeys); + $this->argKeys = array_keys($argKeys); + $this->argDefault = array_values($argKeys); + } + + //shift the $this->_queryString array a number of times equal to the number indicated by the $number variable and build the $this->viewArgs array and the $this->viewStatus string (additional url) + final public function shift($number = 0) { + + //save the query string array + $oldQueryString = $this->_queryString; + + for ($i = 0; $i < $number; $i++) + { + array_shift($this->_queryString); + } + $this->callInArgKeysFunc(); + for ($i = 0; $i < count($this->argKeys); $i++) + { + if (!isset($this->_queryString[$i])) { + $this->viewArgs[$this->argKeys[$i]] = isset($this->argDefault[$i]) ? $this->argDefault[$i] : null; + continue; + } + $this->viewArgs[$this->argKeys[$i]] = $this->_queryString[$i]; + } + $this->viewStatus = Url::createUrl(array_values($this->viewArgs)); + $this->updateHelpers(); + + //update the theme + $this->theme->viewStatus = $this->viewStatus; + $this->theme->viewArgs = $this->viewArgs; + + //restore the query string array + $this->_queryString = $oldQueryString; + } + + //call the functions defined in $this->argKeys after the colon (ex- 'page:forceInt' => apply the forceInt() function upon the $page arg) + final public function callInArgKeysFunc() { + for ($i = 0; $i < count($this->argKeys); $i++) { + if (strstr($this->argKeys[$i],':')) { + $temp = explode(':',$this->argKeys[$i]); + //exception + if (!in_array($temp[1],explode(',',params::$allowedSanitizeFunc))) { + throw new Exception('"'.$temp[1]. '" function not allowed in $this->argKeys'); + } + $this->argKeys[$i] = $temp[0]; + if (!isset($this->_queryString[$i])) { + continue; + } + $this->_queryString[$i] = call_user_func($temp[1],$this->_queryString[$i]); + } + } + } + + //function to update all the Helper that are instance of the HtmlHelper class. This function update the $viesArgs and $viewStatus properties. This function is called by the shift method. + final public function updateHelpers() { + foreach ($this->h as $Helper) { + if ($Helper instanceof Helper_Html) { + $Helper->viewArgs = $this->viewArgs; + $Helper->viewStatus = $this->viewStatus; + } + } + } + + //create the viewStatus property + final public function buildStatus() + { + $this->viewStatus = Url::createUrl(array_values($this->viewArgs)); + //update the theme + $this->theme->viewStatus = $this->viewStatus; + $this->theme->viewArgs = $this->viewArgs; + } + + //method to instanciate the scaffold + final public function loadScaffold($type,$params = null) { + + $typeArray = array('main','form'); + if (!in_array($type,$typeArray)) { + throw new Exception("the type '$type' is not allowed in ".__METHOD__); + } + $this->scaffold = new Scaffold($type,$this->controller,$this->m[$this->modelName],$this->viewArgs,$params); + + $this->helper('Menu',$this->controller,$this->scaffold->params['panelController']); + $this->scaffold->mainMenu = $this->h['Menu']; + + $this->m[$this->modelName]->popupBuild(); + $popupArray = $this->m[$this->modelName]->popupArray; + + if ($type === 'main') { + + $here = $this->controller.'/'.$this->scaffold->params['mainAction']; + $this->helper('Pages',$here,$this->scaffold->params['pageVariable']); + $this->helper('List',$this->m[$this->modelName]->identifierName); + + + $this->helper('Popup',$here,$popupArray,$this->scaffold->params['popupType'],$this->scaffold->params['pageVariable']); + + $this->scaffold->pageList = $this->h['Pages']; + $this->scaffold->itemList = $this->h['List']; + $this->scaffold->popupMenu = $this->h['Popup']; + } + } + +} \ No newline at end of file diff --git a/h-source/Library/Db/Mysql.php b/h-source/Library/Db/Mysql.php new file mode 100755 index 0000000..8b96f44 --- /dev/null +++ b/h-source/Library/Db/Mysql.php @@ -0,0 +1,394 @@ + 'utf8', + 'ISO-8859-1' => 'latin1', + 'EUC-JP' => 'ujis', + 'SJIS' => 'sjis' + ); + + private function __construct($host,$user,$pwd,$db_name) + { + + $this->dblink = mysql_connect($host,$user,$pwd); + + if ($this->dblink === FALSE) { + die ("Connection error. Verify parameters in config.php"); + } + + $db2 = mysql_select_db($db_name, $this->dblink) + or die ("Database selection error. Verify parameters in config.php"); + + $charset = array_key_exists(DEFAULT_CHARSET,$this->charsetTranslationTable) ? $this->charsetTranslationTable[DEFAULT_CHARSET] : 'utf8'; + + if (!@mysql_set_charset($charset,$this->dblink)) $this->charsetError = false; + + $this->charset = mysql_client_encoding(); + } + + public static function getInstance($host = null, $user = null, $pwd = null, $db_name = null) + { + if (!isset(self::$instance)) { + $className = __CLASS__; + self::$instance = new $className($host,$user,$pwd,$db_name); + } + + return self::$instance; + } + + + //close the connection + public function disconnect() + { + mysql_close($this->dblink); + } + + //the text of the error message from previous MySQL operation + public function getError() + { + return mysql_error($this->dblink); + } + + //the numerical value of the error message from previous MySQL operation + public function getErrno() + { + return mysql_errno($this->dblink); + } + + public function createSelectQuery($table,$fields='*',$where=null,$group_by=null,$order_by=null,$limit=null,$on=null,$using=null) + { + if (isset($where)) + { + $where='WHERE '.$where; + } + if (isset($using)) + { + $using ='USING ('.$using.')'; + $on = null; + } + if (isset($on) and !isset($using)) + { + $on='ON '.$on; + } + if (isset($order_by)) { + $order_by='ORDER BY '.$order_by; + } + if (isset($group_by)) { + $group_by='GROUP BY '.$group_by; + } + if (isset($limit)) { + $limit='LIMIT '.$limit; + } + + $query="SELECT $fields FROM $table $on $using $where $group_by $order_by $limit;"; + return $query; + } + + public function get_num_rows($table,$where=null,$group_by=null,$on=null,$using=null) { + + $query = $this->createSelectQuery($table,'*',$where,$group_by,null,null,$on,$using); + + $this->query=$query; + + $ris = mysql_query($query); + if ($ris) { + $num_rows = mysql_num_rows($ris); + return $num_rows; + } else { + return false; + } + } + + //get the maximum value of the field $field of the table $table having the $where conditions + public function getMath($func,$table,$field,$where=null,$group_by = null, $on=null,$using=null) + { + $query = $this->createSelectQuery($table,"$func($field) AS m",$where,$group_by,null,null,$on,$using); + + $this->query = $query; + $result = mysql_query($query); + if ($result) + { + $row = mysql_fetch_array($result); + return $row['m']; + } + else + { + return false; + } + } + + //get the maximum value of the field $field of the table $table having the $where conditions + public function getMax($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('MAX',$table,$field,$where,$group_by,$on,$using); + } + + //get the minimum value of the field $field of the table $table having the $where conditions + public function getMin($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('MIN',$table,$field,$where,$group_by,$on,$using); + } + + //get the sum of the fields + public function getSum($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('SUM',$table,$field,$where,$group_by,$on,$using); + } + + //get the average of the fields + public function getAvg($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('AVG',$table,$field,$where,$group_by,$on,$using); + } + + public function select($table,$fields='*',$where=null,$group_by=null,$order_by=null,$limit=null,$on=null,$using=null) + { + $query = $this->createSelectQuery($table,$fields,$where,$group_by,$order_by,$limit,$on,$using); + + $this->query = $query; + $result = mysql_query($query); + return $this->getData($result); + } + + +// public function select($table,$fields='*',$where=null,$group_by=null,$order_by=null,$limit=null) { +// $query = $this->selectQuery($table,$fields,$where,$group_by,$order_by,$limit); +// return $this->getData($query); +// } + + + //obtain an associative array containing the result values (keys:tableName_fieldsName) + //$par = 'single/multi' single table,multi table + public function getData($result) + { + $data = array(); //data from the query + $temp = array(); //temporary array (values of a single record) +// $result = mysql_query($query); + if ($result) + { + $fieldsNumber = mysql_num_fields($result); + while ($row = mysql_fetch_array($result)) + { + for ($i = 0;$i < $fieldsNumber;$i++) + { + $tableName = mysql_field_table($result, $i); + if (strcmp($tableName,'') === 0) $tableName = Params::$aggregateKey; + $fieldName = mysql_field_name($result, $i); + $temp[$tableName][$fieldName] = $row[$i]; + } + array_push($data,$temp); + } + return $data; + } + else + { + return false; + } + } + + //return an array containing all the types of the fields (indicated in $fields) of a table (indicated in $table) + public function getTypes($table, $fields) + { + $query = "DESCRIBE $table;"; + $result = mysql_query($query); + $temp = array(); + while ($row = mysql_fetch_assoc($result)) { + $temp[$row['Field']] = reset(explode('(',$row['Type'])); + } + + $types = array(); + $fields = explode(',',$fields); + for ($i = 0; $i < count($fields); $i++) + { + if (!array_key_exists($fields[$i],$temp)) return false; + $types[] = $temp[$fields[$i]]; + } + + return $types; + } + + public function insert($table,$fields,$values) { + + #$table is a string + #$fields has to be a string with comma as separator: name1,name2,... + #$values has to be an array + $values = array_values($values); + if (strcmp($fields,'') !== 0) + { + //get the type of the fields + $types = $this->getTypes($table,$fields); + if (!$types) return false; + + for($i = 0; $i < count($values); $i++) + { + if (!in_array($types[$i],$this->fieldsType)) + { + $values[$i] = '"'.$values[$i].'"'; + } + else + { + if (strcmp($values[$i],'') === 0) $values[$i] = '"'.$values[$i].'"'; + } + } + + $values = implode(',',$values); + $query="INSERT INTO $table ($fields) VALUES ($values);"; + $this->query = $query; + $ris = mysql_query($query); + + #check the result + if ($ris) { + return true; + } else { + return false; + } + + } else { + return false; + } + } + + // Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). + public function lastId() + { + return mysql_insert_id(); + } + + public function update($table,$fields,$values,$where) { + + #$table and $where are two strings + #$fields has to be a string with comma as separator: name1,name2,... + #$values has to be an array + $values = array_values($values); +// if (isset($where)) { + $where='WHERE '.$where; +// } + #get the array from the $fields string + if (strcmp($fields,'') !== 0) + { + //get the type of the fields + $types = $this->getTypes($table,$fields); + if (!$types) return false; + + $fields=explode(',',$fields); + $str=array(); + + for ($i=0;$ifieldsType)) + { + $values[$i] = '"'.$values[$i].'"'; + } + else + { + if (strcmp($values[$i],'') === 0) $values[$i] = '"'.$values[$i].'"'; + } + $str[$i]= $fields[$i].'='.$values[$i]; + } + + #set the string name1=value1,name2=... + $str=implode(',',$str); + $query="UPDATE $table SET $str $where;"; + $this->query=$query; + $ris = mysql_query($query); + + #check the result + if ($ris) { + return true; + } else { + return false; + } + } else { + return false; + } + + } + + + public function del($table,$where) { + + #$table and $where are two strings +// if (isset($where)) { + $where='WHERE '.$where; +// } + $query="DELETE FROM $table $where;"; + $this->query=$query; + $ris = mysql_query($query); + #check the result + + if ($ris) { + return true; + } else { + return false; + } + + } + + // function to check if exist the record having the field $id_name=$id_value + public function recordExists($table,$fieldName,$fieldValue,$where = null,$groupBy=null,$on=null,$using=null) + { + if (isset($where)) + { + $where=' AND '.$where; + } + + $fieldValue = '"'.$fieldValue.'"'; + + $num=$this->get_num_rows($table,$fieldName.'='.$fieldValue.$where,$groupBy,$on,$using); + $res=($num>0) ? true : false; + return $res; + + } + + + //send a generic query to the database + //$query: the query to be sent + public function query($query) + { + $this->query = $query; + $result = mysql_query($query); + if ($result === false) + { + return false; + } + else if ($result === true) + { + return true; + } + else if (@get_resource_type($result)) + { + return $this->getData($result); + } + } + + // Prevent users to clone the instance + public function __clone() + { + throw new Exception('error in '. __METHOD__.': clone is not allowed'); + } + +} \ No newline at end of file diff --git a/h-source/Library/Db/Mysqli.php b/h-source/Library/Db/Mysqli.php new file mode 100644 index 0000000..4e4c528 --- /dev/null +++ b/h-source/Library/Db/Mysqli.php @@ -0,0 +1,400 @@ + 'utf8', + 'ISO-8859-1' => 'latin1', + 'EUC-JP' => 'ujis', + 'SJIS' => 'sjis' + ); + + /** + + *connect to the database + *'host','user','password','db_name' + + */ + + private function __construct($host,$user,$pwd,$db_name) + { + + $this->db = new mysqli($host,$user,$pwd,$db_name); + + if (mysqli_connect_error()) + { + die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); + } + + $charset = array_key_exists(DEFAULT_CHARSET,$this->charsetTranslationTable) ? $this->charsetTranslationTable[DEFAULT_CHARSET] : 'utf8'; + + if (!@$this->db->set_charset($charset)) $this->charsetError = false; + + $this->charset = $this->db->character_set_name(); + + } + + //return the $this->db property + public function getDb() + { + return $this->db; + } + + public static function getInstance($host = null, $user = null, $pwd = null, $db_name = null) + { + if (!isset(self::$instance)) { + $className = __CLASS__; + self::$instance = new $className($host,$user,$pwd,$db_name); + } + + return self::$instance; + } + + + //close the connection + public function disconnect() + { + $this->db->close(); + } + + //the text of the error message from previous MySQL operation + public function getError() + { + return $this->db->error; + } + + //the numerical value of the error message from previous MySQL operation + public function getErrno() + { + return $this->db->errno; + } + + public function createSelectQuery($table,$fields='*',$where=null,$group_by=null,$order_by=null,$limit=null,$on=null,$using=null) + { + if (isset($where)) + { + $where='WHERE '.$where; + } + if (isset($using)) + { + $using ='USING ('.$using.')'; + $on = null; + } + if (isset($on) and !isset($using)) + { + $on='ON '.$on; + } + if (isset($order_by)) { + $order_by='ORDER BY '.$order_by; + } + if (isset($group_by)) { + $group_by='GROUP BY '.$group_by; + } + if (isset($limit)) { + $limit='LIMIT '.$limit; + } + + $query="SELECT $fields FROM $table $on $using $where $group_by $order_by $limit;"; + return $query; + } + + public function get_num_rows($table,$where=null,$group_by=null,$on=null,$using=null) { + + $query = $this->createSelectQuery($table,'*',$where,$group_by,null,null,$on,$using); + + $this->query = $query; + $ris = $this->db->query($query); + if ($ris) { + $num_rows = $ris->num_rows; + $ris->close(); + return $num_rows; + } else { + return false; + } + } + + public function getMath($func,$table,$field,$where=null,$group_by = null, $on=null,$using=null) + { + $query = $this->createSelectQuery($table,"$func($field) AS m",$where,$group_by,null,null,$on,$using); + + $this->query = $query; + $result = $this->db->query($query); + if ($result) + { + $row = $result->fetch_array(); + $result->close(); + return $row['m']; + } + else + { + return false; + } + } + + //get the maximum value of the field $field of the table $table having the $where conditions + public function getMax($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('MAX',$table,$field,$where,$group_by,$on,$using); + } + + //get the minimum value of the field $field of the table $table having the $where conditions + public function getMin($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('MIN',$table,$field,$where,$group_by,$on,$using); + } + + //get the sum of the fields + public function getSum($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('SUM',$table,$field,$where,$group_by,$on,$using); + } + + //get the average of the fields + public function getAvg($table,$field,$where=null,$group_by = null,$on=null,$using=null) + { + return $this->getMath('AVG',$table,$field,$where,$group_by,$on,$using); + } + + public function select($table,$fields='*',$where=null,$group_by=null,$order_by=null,$limit=null,$on=null,$using=null) + { + $query = $this->createSelectQuery($table,$fields,$where,$group_by,$order_by,$limit,$on,$using); + + $this->query = $query; + $result = $this->db->query($query); + return $this->getData($result); + } + + +// public function select($table,$fields='*',$where=null,$group_by=null,$order_by=null,$limit=null) { +// $query = $this->selectQuery($table,$fields,$where,$group_by,$order_by,$limit); +// return $this->getData($query); +// } + + + //obtain an associative array containing the result values (keys:tableName_fieldsName) + //$par = 'single/multi' single table,multi table + public function getData($result) { + $data = array(); //data from the query + $temp = array(); //temporary array (values of a single record) +// $result = $this->db->query($query); + if ($result) { + $fieldsNumber = $result->field_count; + while ($row = $result->fetch_array()) { + for ($i = 0;$i < $fieldsNumber;$i++) { + $finfo = $result->fetch_field_direct($i); + $tableName = $finfo->table; + if (strcmp($tableName,'') === 0) $tableName = Params::$aggregateKey; + $fieldName = $finfo->name; + $temp[$tableName][$fieldName] = $row[$i]; + } + array_push($data,$temp); + } + $result->close(); + return $data; + } else { + return false; + } + } + + //return an array containing all the types of the fields (indicated in $fields) of a table (indicated in $table) + public function getTypes($table, $fields) + { + $query = "DESCRIBE $table;"; + $result = $this->db->query($query); + $temp = array(); + while ($row = $result->fetch_assoc()) { + $temp[$row['Field']] = reset(explode('(',$row['Type'])); + } + $result->close(); + + $types = array(); + $fields = explode(',',$fields); + for ($i = 0; $i < count($fields); $i++) + { + if (!array_key_exists($fields[$i],$temp)) return false; + $types[] = $temp[$fields[$i]]; + } + + return $types; + } + + public function insert($table,$fields,$values) { + + #$table is a string + #$fields has to be a string with comma as separator: name1,name2,... + #$values has to be an array + $values = array_values($values); + if (strcmp($fields,'') !== 0) + { + //get the type of the fields + $types = $this->getTypes($table,$fields); + if (!$types) return false; + + for($i = 0; $i < count($values); $i++) + { + if (!in_array($types[$i],$this->fieldsType)) + { + $values[$i] = '"'.$values[$i].'"'; + } + else + { + if (strcmp($values[$i],'') === 0) $values[$i] = '"'.$values[$i].'"'; + } + } + + $values = implode(',',$values); + $query="INSERT INTO $table ($fields) VALUES ($values);"; + $this->query=$query; + + $ris = $this->db->query($query); + + #check the result + if ($ris) { + return true; + } else { + return false; + } + + } else { + return false; + } + } + + // Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). + public function lastId() + { + return $this->db->insert_id; + } + + public function update($table,$fields,$values,$where) { + + #$table and $where are two strings + #$fields has to be a string with comma as separator: name1,name2,... + #$values has to be an array + $values = array_values($values); +// if (isset($where)) { + $where='WHERE '.$where; +// } + #get the array from the $fields string + if (strcmp($fields,'') !== 0) + { + //get the type of the fields + $types = $this->getTypes($table,$fields); + if (!$types) return false; + + $fields = explode(',',$fields); + $str = array(); + + for ($i=0;$ifieldsType)) + { + $values[$i] = '"'.$values[$i].'"'; + } + else + { + if (strcmp($values[$i],'') === 0) $values[$i] = '"'.$values[$i].'"'; + } + $str[$i]= $fields[$i].'='.$values[$i]; + } + + #set the string name1=value1,name2=... + $str=implode(',',$str); + $query="UPDATE $table SET $str $where;"; + $this->query=$query; + $ris = $this->db->query($query); + + #check the result + if ($ris) { + return true; + } else { + return false; + } + } else { + return false; + } + + } + + + public function del($table,$where) { + + #$table and $where are two strings +// if (isset($where)) { + $where='WHERE '.$where; +// } + $query="DELETE FROM $table $where;"; + $this->query=$query; + $ris = $this->db->query($query); + #check the result + + if ($ris) { + return true; + } else { + return false; + } + + } + + + //function to check if exist the record having the field $id_name=$id_value + public function recordExists($table,$fieldName,$fieldValue,$where = null,$groupBy=null,$on=null,$using=null) + { + if (isset($where)) + { + $where=' AND '.$where; + } + + $fieldValue = '"'.$fieldValue.'"'; + + $num = $this->get_num_rows($table,$fieldName.'='.$fieldValue.$where,$groupBy,$on,$using); + $res=($num>0) ? true : false; + return $res; + + } + + + //send a generic query to the database + //$query: the query to be sent + public function query($query) + { + $this->query = $query; + $result = $this->db->query($query); + if ($result === true) + { + return true; + } + else if ($result === false) + { + return false; + } + else if ($result instanceof MySQLi_Result) + { + return $this->getData($result); + } + } + + // Prevent users to clone the instance + public function __clone() + { + throw new Exception('error in '. __METHOD__.': clone is not allowed'); + } + +} \ No newline at end of file diff --git a/h-source/Library/Db/index.html b/h-source/Library/Db/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Db/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Email.php b/h-source/Library/Email.php new file mode 100644 index 0000000..c948098 --- /dev/null +++ b/h-source/Library/Email.php @@ -0,0 +1,229 @@ +_check = $bool; + } + + //set the sentTo addresses array + //$addresses: array of e-mail addresses or a string + public function sendTo($addresses) + { + $this->_sendTo = explode(',',$addresses); + } + + //set the subject + public function subject($subject) + { + $this->_subject = $subject; + } + + //set the cc addresses array + //$addresses: array of e-mail addresses or a string + public function cc($addresses) + { + $this->_cc = explode(',',$addresses); + } + + //set the bcc addresses array + //$addresses: array of e-mail addresses or a string + public function bcc($addresses) + { + $this->_bcc = explode(',',$addresses); + } + + //set the address of the sender + public function from($address) + { + $this->_from = $address; + } + + //set the charset + public function charset($charset) + { + $this->_charset = $charset; + } + + //set the Content-Transfer-Encoding + public function ctencoding($ctencoding) + { + $this->_ctencoding = $ctencoding; + } + + //set the text body + public function body($body) + { + $this->_body = $body; + } + + //set the address regular expression + public function addressRegExp($regExp) + { + $this->_addressRegExp = $regExp; + } + + //check if the mail address is valid + public function isValidAddress($address) + { + + if( preg_match( '/^[^<>]*<(.+)>$/', $address, $matches ) ) + { + $address = $matches[1]; + } + + if (isset($this->_addressRegExp)) + { + if (preg_match($this->_addressRegExp,$address)) + { + return true; + } + else + { + return false; + } + } + else + { + if (checkMail($address)) return true; + } + + return false; + + } + + //check the addresses inside the $addresses array + public function checkAddresses($addresses) + { + foreach ($addresses as $address) + { + if(!$this->isValidAddress($address)) return false; + } + return true; + } + + //build the mail + public function buildMail() + { + + if (empty($this->_sendTo)) + { + $this->errorsArray[] = 'no address specified'; + return false; + } + + if ($this->_check) + { + if (!$this->checkAddresses($this->_sendTo)) + { + $this->errorsArray[] = 'errors in the sendTo address validation'; + return false; + } + + if (!empty($this->_cc)) + { + if (!$this->checkAddresses($this->_cc)) + { + $this->errorsArray[] = 'errors in the cc address validation'; + return false; + } + } + + if (!empty($this->_bcc)) + { + if (!$this->checkAddresses($this->_bcc)) + { + $this->errorsArray[] = 'errors in the bcc address validation'; + return false; + } + } + + if (isset($this->_from)) + { + if (!$this->checkAddresses(array($this->_from))) + { + $this->errorsArray[] = 'errors in the from address validation'; + return false; + } + } + } + + if (strcmp($this->_subject,'') === 0) + { + $this->errorsArray[] = 'no subject specified'; + return false; + } + + $headers = null; + if (isset($this->_from)) $headers .= "From: ".$this->_from."\r\n"; + $headers .= "MIME-Version: 1.0\r\n"; + $headers .= "Content-Type: text/plain; charset=\"".$this->_charset."\"\r\n"; + $headers .= "Content-Transfer-Encoding: ".$this->_ctencoding."\r\n"; + if (!empty($this->_cc)) $headers .= "CC: ".implode(',',$this->_cc)."\r\n"; + if (!empty($this->_bcc)) $headers .= "Bcc: ".implode(',',$this->_bcc)."\r\n"; + + $this->_headers = $headers; + + return true; + + } + + public function send() + { + if (!$this->buildMail()) return false; + + $to = implode(',',$this->_sendTo); + + if (!@mail($to,$this->_subject,$this->_body,$this->_headers)) + { + $this->errorsArray[] = 'error in the send process'; + return false; + } + + return true; + } + +} \ No newline at end of file diff --git a/h-source/Library/ErrorReporting.php b/h-source/Library/ErrorReporting.php new file mode 100644 index 0000000..bc541bc --- /dev/null +++ b/h-source/Library/ErrorReporting.php @@ -0,0 +1,25 @@ +disconnect(); + break; + case 'Mysqli': + $mysqli = Db_Mysqli::getInstance(); + $mysqli->disconnect(); + break; + case 'None': + return null; + break; + } + } + +} diff --git a/h-source/Library/Factory/index.html b/h-source/Library/Factory/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Factory/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Files/Log.php b/h-source/Library/Files/Log.php new file mode 100644 index 0000000..895c26d --- /dev/null +++ b/h-source/Library/Files/Log.php @@ -0,0 +1,97 @@ +splFile = new SplFileObject($path,'a+'); + //change the permission of the file + @chmod($path,self::$logPermission); + } + + // The singleton method + // $instanceName: name of the key of self::$instance. It is also the name of the log file to open + public static function getInstance($instanceName) + { + if (!isset(self::$instance[$instanceName])) { + $className = __CLASS__; + self::$instance[$instanceName] = new $className($instanceName); + } + + return self::$instance[$instanceName]; + } + + //write the string $string at the end of the file + public function writeString($string,$format = 'Y-m-d H:i:s') + { + $date = date($format); + $this->splFile->fwrite("[$date]\t".$string."\n"); + } + + //get the date string of the line $line + public function getDateString($line) + { + if (preg_match('/^[\[]{1}([a-zA-Z0-9:\-\s])*[\]]{1}/',$line,$match)) + { + $match[0] = str_replace('[',null,$match[0]); + $match[0] = str_replace(']',null,$match[0]); + return $match[0]; + } + else + { + return false; + } + } + + //delete all the lines older than a number of days equal to $days + public function clearBefore($days = 30) + { + $tempArray = array(); + $newTime = time() - (int)$days * 24 * 3600; + foreach ($this->splFile as $line) + { + $lineTime = strtotime($this->getDateString($line)); + if ($lineTime !== false and $lineTime > $newTime) + { + $tempArray[] = $line; + } + } + $this->splFile->ftruncate(0); + foreach ($tempArray as $row) + { + $this->splFile->fwrite($row); + } + } + + // Prevent users to clone the instance + public function __clone() + { + throw new Exception('error in '. __METHOD__.': clone is not allowed'); + } + +} \ No newline at end of file diff --git a/h-source/Library/Files/Upload.php b/h-source/Library/Files/Upload.php new file mode 100755 index 0000000..47289fd --- /dev/null +++ b/h-source/Library/Files/Upload.php @@ -0,0 +1,451 @@ +directory. The path starts from the $base folder + private $files = array(); //files inside the current directory + private $relFiles = array(); //files inside $this->directory. The path starts from the $base directory + private $params; //class parameters + private $pattern = null; //the pattern for the preg_match function + + protected $_resultString; //reference to the class uploadStrings containing all the result strings + + public $fileName = null; //the name of the last file that has been uploaded + public $notice = null; //the result string of the operation + + public function __construct($base,$params = null, $directory = null) { + + $this->base = $this->addTrailingSlash($base); + + //set the match pattern + $tmp = str_replace(self::DS,'\\'.self::DS,$this->base); + $this->pattern = "/^(".$tmp.")/"; + + $defaultParams = array( + 'filesPermission'=>0777, + 'delFolderAction'=>'delFolderAction', + 'delFileAction'=>'delFileAction', + 'createFolderAction'=>'createFolderAction', + 'uploadFileAction'=>'uploadFileAction', + 'maxFileSize' => 3000000, + 'language' => 'eng', + 'allowedExtensions'=>'jpg,jpeg,png,gif,txt', + 'fileUploadKey' => 'userfile' + ); + + //set the $this->scaffold->params array + if (is_array($params)) + { + foreach ($params as $key => $value) + { + $defaultParams[$key] = $value; + } + } + $this->params = $defaultParams; + + //instantiate the $_resultString object + $stringClass = 'Lang_'.$this->params['language'].'_UploadStrings'; + if (!class_exists($stringClass)) + { + $stringClass = 'Lang_Eng_UploadStrings'; + } + $this->_resultString = new $stringClass(); + + $this->setDirectory($directory); + + } + + //obtain the current directory + public function setDirectory($directory = null) + { + $relDir = (strcmp($directory,"") !== 0) ? $this->addTrailingSlash($directory) : null; + $absDir = $this->addTrailingSlash($this->base.$directory); + + if (is_dir($absDir)) + { + if ($this->isValidFolder($absDir)) + { + $this->directory = $relDir; + return true; + } + else + { + $this->notice = $this->_resultString->getString('not-child'); + } + } + else + { + $this->directory = null; + $this->notice = $this->_resultString->getString('not-dir'); + } + return false; + } + + //check if $folder is a folder and is subfolder of $this->base + protected function isValidFolder($folder) + { + if (is_dir($folder)) + { + $folder = $this->addTrailingSlash(realpath($folder)); + if ($this->isMatching($folder)) return true; + } + return false; + } + + protected function isMatching($path) + { + if (preg_match($this->pattern,$path)) + { + if (strstr($path,'..')) return false; + return true; + } + return false; + } + + public function getDirectory() { + return $this->directory; + } + + public function getBase() + { + return $this->base; + } + + public function getSubDir() { + return $this->subDir; + } + + public function getRelSubDir() + { + return $this->relSubDir; + } + + public function getFiles() { + return $this->files; + } + + public function getRelFiles() + { + return $this->relFiles; + } + + public function getParentDir() { + return $this->parentDir; + } + + //add the trailing slash to the string + protected function addTrailingSlash($string) + { + $finalChar = $string[strlen($string) - 1]; + if (strcmp($finalChar,self::DS) !== 0) + { + return $string.self::DS; + } + return $string; + } + + protected function urlDeep($dir) { #funzione per creare l'indirizzo completo della cartella all'interno della quale voglio entrare + #$dir:cartella all'interno della quale voglio entrare + return $this->base.$this->directory.$dir.self::DS; + } + + public function listFiles() { #creo la lista di file e cartelle all'interno della directory corrente + $items = scandir($this->base.$this->directory); + foreach( $items as $this_file ) { + if( strcmp($this_file,".") !== 0 && strcmp($this_file,"..") !== 0 ) { + if (is_dir($this->urlDeep($this_file))) { + $this->subDir[] = $this_file; + $this->relSubDir[] = $this->directory.$this_file; + } else { + $this->files[] = $this_file; + $this->relFiles[] = $this->directory.$this_file; + } + } + } + //get the parent dir + $this->parentDir(); + } + + //get the extension of the file + protected function getFileExtension($file) + { + return strtolower(end(explode('.', $file))); + } + + protected function parentDir() { #individuo la cartella madre + + $folders = explode(self::DS,$this->directory); + array_pop($folders); + array_pop($folders); + $parent = implode(self::DS,$folders); + $parent = (strcmp($parent,"") !== 0) ? $this->addTrailingSlash($parent) : null; + + if ($this->isValidFolder($this->base.$parent)) + { + $this->parentDir = $parent; + } + else + { + $this->parentDir = null; + } + } + + //create the $name subfolder of the $this->directory folder + public function createFolder($name) { #funzione per creare una cartella nella directory corrente + $name = basename($name); + if (strcmp(trim($name),'') !== 0) + { + if (is_writable($this->base.$this->directory)) + { + $path = $this->base.$this->directory.$name; + + if ($this->isMatching($path)) + { + if (!file_exists($path)) + { + if (@mkdir($path,$this->params['filesPermission'])) + { + @chmod($path, $this->params['filesPermission']); + $this->notice = $this->_resultString->getString('executed'); + return true; + } + else + { + $this->notice = $this->_resultString->getString('error'); + } + } + else + { + $this->notice = $this->_resultString->getString('dir-exists'); + } + } + else + { + $this->notice = $this->_resultString->getString('not-child'); + } + } + else + { + $this->notice = $this->_resultString->getString('not-writable'); + } + } + else + { + $this->notice = $this->_resultString->getString('no-folder-specified'); + } + return false; + } + + //check if the $name folder is empty or not + protected function isEmpty($name) + { + $items = scandir($name); + foreach( $items as $this_file ) { + if( strcmp($this_file,".") !== 0 && strcmp($this_file,"..") !== 0 ) { + return false; + } + } + return true; + } + + public function removeFile($name) + { + $name = basename($name); + if (strcmp(trim($name),'') !== 0) + { + $path = $this->base.$this->directory.$name; + if ($this->isMatching($path)) + { + if ($this->removeAbsFile($path)) return true; + } + else + { + $this->notice = $this->_resultString->getString('not-child'); + } + } + else + { + $this->notice = $this->_resultString->getString('no-file-specified'); + } + return false; + } + + //remove the $name file + protected function removeAbsFile($name) + { + if (strcmp(trim($name),'') !== 0) + { + if (is_writable($name)) + { + if (@unlink($name)) + { + $this->notice = $this->_resultString->getString('executed'); + return true; + } + else + { + $this->notice = $this->_resultString->getString('error'); + } + } + else + { + $this->notice = $this->_resultString->getString('not-writable-file'); + } + } + else + { + $this->notice = $this->_resultString->getString('no-file-specified'); + } + return false; + } + + public function removeFolder($name) + { + $name = basename($name); + if (strcmp(trim($name),'') !== 0) + { + $dir = $this->base.$this->directory.$name; + if ($this->isMatching($dir)) + { + if ($this->removeAbsFolder($dir)) return true; + } + else + { + $this->notice = $this->_resultString->getString('not-child'); + } + } + else + { + $this->notice = $this->_resultString->getString('no-folder-specified'); + } + return false; + } + + //remove the $name folder + protected function removeAbsFolder($name) { + if (strcmp(trim($name),'') !== 0) { + if (is_writable($name)) + { + if ($this->isEmpty($name)) + { + if (@rmdir($name)) + { + $this->notice = $this->_resultString->getString('executed'); + return true; + } + else + { + $this->notice = $this->_resultString->getString('error'); + } + } + else + { + $this->notice = $this->_resultString->getString('not-empty'); + } + } + else + { + $this->notice = $this->_resultString->getString('not-writable'); + } + } + else + { + $this->notice = $this->_resultString->getString('no-folder-specified'); + } + return false; + } + + //upload a file in the current directory + //$fileName: name of the file + public function uploadFile($fileName = null) { + $userfile = $this->params['fileUploadKey']; + $ext = $this->getFileExtension($_FILES[$userfile]["name"]); + $fileName = isset($fileName) ? $fileName.".$ext" : basename($_FILES[$userfile]["name"]); + + $this->fileName = $fileName; + + if(strcmp(trim($_FILES[$userfile]["name"]),"") !== 0) + { + if(@is_uploaded_file($_FILES[$userfile]["tmp_name"])) { + if ($_FILES[$userfile]["size"] <= $this->params['maxFileSize']) + { + //check the extension of the file + $AllowedExtensionsArray = explode(',',$this->params['allowedExtensions']); + + if (in_array($ext,$AllowedExtensionsArray)) + { + //check if the file doesn't exists + if (!file_exists($this->base.$this->directory.$fileName)) + { + if (@move_uploaded_file($_FILES[$userfile]["tmp_name"],$this->base.$this->directory.$fileName)) + { + @chmod($this->base.$this->directory.$fileName, $this->params['filesPermission']); + $this->notice = $this->_resultString->getString('executed'); + return true; + } + else + { + $this->notice = $this->_resultString->getString('error'); + } + } + else + { + $this->notice = $this->_resultString->getString('file-exists'); + } + } + else + { + $this->notice = $this->_resultString->getString('not-allowed-ext'); + } + } + else + { + $this->notice = $this->_resultString->getString('size-over'); + } + } + else + { + $this->notice = $this->_resultString->getString('no-upload-file'); + } + } + else + { + $this->notice = $this->_resultString->getString('no-upload-file'); + } + return false; + } + + //update the folder tree + public function updateTree() { + + if (isset($_POST[$this->params['delFolderAction']])) { + $this->removeFolder($_POST[$this->params['delFolderAction']]); + } + + if (isset($_POST[$this->params['delFileAction']])) { + $this->removeFile($_POST[$this->params['delFileAction']]); + } + + if (isset($_POST[$this->params['createFolderAction']])) { + $this->createFolder($_POST['folderName']); + } + + if (isset($_POST[$this->params['uploadFileAction']])) { + $this->uploadFile(); + } + + } +} \ No newline at end of file diff --git a/h-source/Library/Files/index.html b/h-source/Library/Files/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Files/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Form/Checkbox.php b/h-source/Library/Form/Checkbox.php new file mode 100755 index 0000000..5df1917 --- /dev/null +++ b/h-source/Library/Form/Checkbox.php @@ -0,0 +1,41 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $wrap = $this->getWrapElements(); + $returnString = "
\n\t"; + $returnString .= $wrap[0]; + $returnString .= $this->getLabelTag(); + $returnString .= $wrap[1]; + $returnString .= Html_Form::checkbox($this->entryName, $value, $this->options, $this->className,$this->idName); + $returnString .= $wrap[2]; + $returnString .="
\n"; + return $returnString; + } + +} diff --git a/h-source/Library/Form/Entry.php b/h-source/Library/Form/Entry.php new file mode 100755 index 0000000..725235a --- /dev/null +++ b/h-source/Library/Form/Entry.php @@ -0,0 +1,45 @@ + entry or a radio button). Associative array or comma-divided list. + public $defaultValue = ''; + public $wrap = array(); + public $type = null; //the type of the entry + + //create the label of each entry of the form + public function getLabelTag() + { + $labelTagClass = isset($this->labelClass) ? $this->labelClass : 'entryLabel'; + return isset($this->labelString) ? "\n\t" : null; + } + + //get the class of the entry + public function getEntryClass() + { + return isset($this->entryClass) ? $this->entryClass : 'formEntry'; + } + + public function getWrapElements() + { + $wrap[0] = isset($this->wrap[0]) ? $this->wrap[0] : null; + $wrap[1] = isset($this->wrap[1]) ? $this->wrap[1] : null; + $wrap[2] = isset($this->wrap[2]) ? $this->wrap[2] : null; + return $wrap; + } + + abstract public function render($value = null); + +} diff --git a/h-source/Library/Form/Form.php b/h-source/Library/Form/Form.php new file mode 100755 index 0000000..00e27d4 --- /dev/null +++ b/h-source/Library/Form/Form.php @@ -0,0 +1,116 @@ +'value') + public $method = 'POST'; //the transmission method: POST/GET + + public function __construct($action,$submit = array('generalAction'=>'save'),$method = 'POST') + { + $this->action = $action; //action of the form: controller/action + $this->submit = $submit; + $this->method = $method; + } + + //method to manage the $this->entry associative array + //entryType: the type of the object to be initialized, $entryName: the name of the entry + //$options: the list of options (if the entry is a \n\n"; + } + $htmlForm .= "\n"; + return $htmlForm; + } + +} diff --git a/h-source/Library/Form/Hidden.php b/h-source/Library/Form/Hidden.php new file mode 100755 index 0000000..fb81b30 --- /dev/null +++ b/h-source/Library/Form/Hidden.php @@ -0,0 +1,23 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $returnString = Html_Form::hidden($this->entryName, $value); + return $returnString; + } + +} diff --git a/h-source/Library/Form/Html.php b/h-source/Library/Form/Html.php new file mode 100644 index 0000000..dce91c6 --- /dev/null +++ b/h-source/Library/Form/Html.php @@ -0,0 +1,23 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $returnString = "
\n\t$value\n
\n"; + return $returnString; + } + +} diff --git a/h-source/Library/Form/InputText.php b/h-source/Library/Form/InputText.php new file mode 100755 index 0000000..fb98336 --- /dev/null +++ b/h-source/Library/Form/InputText.php @@ -0,0 +1,30 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $wrap = $this->getWrapElements(); + $returnString = "
\n\t"; + $returnString .= $wrap[0]; + $returnString .= $this->getLabelTag(); + $returnString .= $wrap[1]; + $returnString .= Html_Form::input($this->entryName, $value, $this->className, $this->idName); + $returnString .= $wrap[2]; + $returnString .="
\n"; + return $returnString; + } + +} diff --git a/h-source/Library/Form/Password.php b/h-source/Library/Form/Password.php new file mode 100644 index 0000000..76bc735 --- /dev/null +++ b/h-source/Library/Form/Password.php @@ -0,0 +1,30 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $wrap = $this->getWrapElements(); + $returnString = "
\n\t"; + $returnString .= $wrap[0]; + $returnString .= $this->getLabelTag(); + $returnString .= $wrap[1]; + $returnString .= Html_Form::password($this->entryName, null, $this->className); + $returnString .= $wrap[2]; + $returnString .="
\n"; + return $returnString; + } + +} diff --git a/h-source/Library/Form/Radio.php b/h-source/Library/Form/Radio.php new file mode 100755 index 0000000..fb20677 --- /dev/null +++ b/h-source/Library/Form/Radio.php @@ -0,0 +1,30 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $wrap = $this->getWrapElements(); + $returnString = "
\n\t"; + $returnString .= $wrap[0]; + $returnString .= $this->getLabelTag(); + $returnString .= $wrap[1]; + $returnString .= Html_Form::radio($this->entryName,$value,$this->options,$this->className, 'after', $this->idName); + $returnString .= $wrap[2]; + $returnString .="
\n"; + return $returnString; + } + +} diff --git a/h-source/Library/Form/Select.php b/h-source/Library/Form/Select.php new file mode 100755 index 0000000..558fd57 --- /dev/null +++ b/h-source/Library/Form/Select.php @@ -0,0 +1,30 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $wrap = $this->getWrapElements(); + $returnString = "
\n\t"; + $returnString .= $wrap[0]; + $returnString .= $this->getLabelTag(); + $returnString .= $wrap[1]; + $returnString .= Html_Form::select($this->entryName,$value,$this->options,$this->className, $this->idName); + $returnString .= $wrap[2]; + $returnString .="
\n"; + return $returnString; + } + +} diff --git a/h-source/Library/Form/Textarea.php b/h-source/Library/Form/Textarea.php new file mode 100755 index 0000000..d81cc84 --- /dev/null +++ b/h-source/Library/Form/Textarea.php @@ -0,0 +1,30 @@ +entryName = $entryName; + } + + public function render($value = null) + { + $wrap = $this->getWrapElements(); + $returnString = "
\n\t"; + $returnString .= $wrap[0]; + $returnString .= $this->getLabelTag(); + $returnString .= $wrap[1]; + $returnString .= Html_Form::textarea($this->entryName, $value, $this->className, $this->idName); + $returnString .= $wrap[2]; + $returnString .="
\n"; + return $returnString; + } + +} diff --git a/h-source/Library/Form/index.html b/h-source/Library/Form/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Form/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Functions.php b/h-source/Library/Functions.php new file mode 100755 index 0000000..414770f --- /dev/null +++ b/h-source/Library/Functions.php @@ -0,0 +1,279 @@ +getDb(); + $stringa = $db->real_escape_string($stringa); + return $stringa; + } + + return $stringa; +} + +function sanitizeAll($stringa) { + + $stringa=sanitizeHtml($stringa); + $stringa=sanitizeDb($stringa); + return $stringa; + +} + +function sanitizeHtml($stringa) { + + $charset = Params::$htmlentititiesCharset; + $stringa=htmlentities($stringa,ENT_QUOTES,$charset); + return $stringa; + +} + +//check if only alphabetic + optional characters are present in the string $string. Set $string to $altString if other characters are found +//$optChar: allowed characters divided by '|' Ex: '+|-|;' +function sanitizeCustom($string,$optChar,$altString = 'EasyGiant') +{ + + $optChar = html_entity_decode($optChar,ENT_QUOTES); + $optCharArray = explode('|',$optChar); + $temp = $string; + foreach($optCharArray as $char) + { + $temp = str_replace($char,null,$temp); + } + if (ctype_alnum($temp)) + { + return $string; + } + else + { + return $altString; + } +} + + + + +/* +SANITIZE DEEP +*/ + +function stripslashesDeep($value) { + if(get_magic_quotes_gpc()) {#if stripslashes + return array_map('stripslashes', $value); + } + return $value; +} + + +function sanitizeHtmlDeep($value) { + return array_map('sanitizeHtml', $value); +} + + +function sanitizeDbDeep($value) { + return array_map('sanitizeDb', $value); +} + + +function sanitizeCustomDeep($stringArray,$optChar,$altString = 'EasyGiant') +{ + $result = array(); + foreach ($stringArray as $key => $value) + { + $result[$key] = sanitizeCustom($value,$optChar,$altString); + } + return $result; +} + + +function sanitizeAllDeep($value) { + return array_map('sanitizeAll', $value); +} + + +function forceIntDeep($value) { + return array_map('forceInt', $value); +} + +function forceNatDeep($value) { + return array_map('forceNat', $value); +} + +function noneDeep($value) { + return array_map('none', $value); +} + + +function md5Deep($value) +{ + return array_map('md5', $value); +} + +function sha1Deep($value) +{ + return array_map('sha1', $value); +} + + + + + + + +function sanitizeAlnum($string) +{ + return ctype_alnum($string) ? sanitizeAll($string) : ''; +} + + +function sanitizeIp($ip) +{ + return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/',$ip) ? sanitizeAll($ip) : ''; +} + + +/* + CHECK FUNCTIONS +*/ + +//check if a string has the mail format (abc.efg@hij.klm.on) +//modification of the rule found at http://www.sastgroup.com/tutorials/8-espressioni-regolari-per-validare-un-po-di-tutto +//original rule: /^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/ +function checkMail($string) +{ + if (preg_match('/^[a-zA-Z0-9_\-]+([.][a-zA-Z0-9_\-]+){0,2}[@][a-zA-Z0-9_\-]+([.][a-zA-Z0-9_\-]+){0,2}[.][a-zA-Z]{2,4}$/',$string)) + { + return true; + } + else + { + return false; + } +} + + + +function wrap($string,$tag_class) {#wrap the string with the tag and its class + #$tag_class has to be an associative array (tag1=>class1,$tag2=>class2,.. )!! + $str_front=null; + $str_rear=null; + if (is_array($tag_class)) { + foreach ($tag_class as $tag => $class) { + $tag = str_replace('+','',$tag); + $str_class=isset($class) ? " class=\"".$class."\"" : null; + $str_front.="<".$tag.$str_class.">\n"; + $str_rear.="\n"; + } + } + return $str_front.$string.$str_rear; +} + +//generate a random password +//$start: start number of mt_rand +//$end: end number of mt_rand +function randString($length,$start = 33, $end = 126) +{ + $random = ''; + for ($i = 0; $i < $length; $i++) + { + $random .= chr(mt_rand($start, $end)); + } + return $random; +} + +//generate a random string +//$charNumb:number of characters of the final string +//$allowedChars: allowed characters +function generateString($charNumb = 8,$allowedChars = '0123456789abcdefghijklmnopqrstuvwxyz') +{ + $str = null; + for ($i = 0; $i < $charNumb; $i++) + { + $str .= substr($allowedChars, mt_rand(0, strlen($allowedChars)-1), 1); + } + return $str; +} + + +function getIp() +{ + $ip = ""; + + if (isset($_SERVER)) + { + if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) + { + $ip = sanitizeIp($_SERVER["HTTP_X_FORWARDED_FOR"]); + } else if (!empty($_SERVER["HTTP_CLIENT_IP"])) { + $ip = sanitizeIp($_SERVER["HTTP_CLIENT_IP"]); + } else { + $ip = sanitizeIp($_SERVER["REMOTE_ADDR"]); + } + } else { + if ( getenv( 'HTTP_X_FORWARDED_FOR' ) !== false ) { + $ip = sanitizeIp(getenv( 'HTTP_X_FORWARDED_FOR' )); + } else if ( getenv( 'HTTP_CLIENT_IP' ) !== false ) { + $ip = sanitizeIp(getenv( 'HTTP_CLIENT_IP' )); + } else { + $ip = sanitizeIp(getenv( 'REMOTE_ADDR' )); + } + } + return $ip; +} + + + +function getUserAgent() { + if (isset($_SERVER['HTTP_USER_AGENT'])) + { + return md5($_SERVER['HTTP_USER_AGENT']); + } + else + { + return md5('firefox'); + } +} + + +function xml_encode($string) +{ + $trans = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES); + foreach ($trans as $k=>$v) + { + $trans[$k]= "&#".ord($k).";"; + } + + return strtr($string, $trans); +} \ No newline at end of file diff --git a/h-source/Library/HeaderObj.php b/h-source/Library/HeaderObj.php new file mode 100644 index 0000000..f4fe65b --- /dev/null +++ b/h-source/Library/HeaderObj.php @@ -0,0 +1,28 @@ +domainName = $domainName; + } + + //redirect to $path after the time $time + //string that appears until the page is redirected + public function redirect($path,$time = 0,$string = null) + { + $completePath = Url::getRoot().$path; + header('Refresh: '.$time.';url='.$completePath); + if (isset($string)) echo $string; + exit; + } + +} diff --git a/h-source/Library/Helper/Array.php b/h-source/Library/Helper/Array.php new file mode 100755 index 0000000..32a4c27 --- /dev/null +++ b/h-source/Library/Helper/Array.php @@ -0,0 +1,11 @@ + null, + 'del' => null, + 'up' => null, + 'down' => null, + 'link' => null + ); + + //set the titles of the input:submit + public $submitTitles = array( + 'edit' => 'edit the record', + 'del' => 'delete the record', + 'up' => 'move up the record', + 'down' => 'move down the record', + 'link' => 'associate the record' + ); + + //$position: array. First element: page number, second element: number of pages + public $position = array(); + + //it can be: both, top, bottom, none + protected $_boundaries = 'none'; + + public function build($identifierName = 'identifier') + { + $this->_identifierName = $identifierName; + } + + public function setIdentifierName($identifierName) + { + $this->_identifierName = $identifierName; + } + + //add a list Item. $type: the type of the item, $field: the table.field to exctract (use colon to separate the table and the field),$action: controller/action,$value=if type == link->the value of the link + public function addItem($type, $action = '', $field = '', $name = '') { + if (!in_array($type,$this->_allowedItems)) { + throw new Exception('"'.$type. '" argument not allowed in '.__METHOD__.' method'); + } + $temp=array(); + $temp['type'] = $type; + $temp['action'] = $action; + $temp['field'] = $field; + $temp['name'] = $name; + $this->_itemsList[] = $temp; + + //set the $this->_head array + $head = array(); + $head['type'] = $type; + + if ($type === 'simpleText') { + $head['action'] = $this->extractFieldName($action); + } else { + $head['action'] = ' '; + } + $this->_head[] = $head; + } + + + //set the head of the table + //$columnsName: name of the columns. It has to be a comma-separated list of strings + public function setHead($columnsName = '') + { + //get the array from the list + $columnsArray = explode(',',$columnsName); + for ($i = 0; $i < count($columnsArray); $i++) + { + if ($i < count($this->_itemsList)) $this->_head[$i]['action'] = $columnsArray[$i]; + } + } + + + //$method to extract the field name from the $action string (;table:field;) + public function extractFieldName($string) { + $string = str_replace(';','',$string); + return $string; + } + + //replace the strings wrapped by ; with their correspondent value taken by the $recordArray associative array (a row of the select query) + public function replaceFields($string,$rowArray) { + $stringArray = explode(';',$string); + for ($i = 0; $i < count($stringArray); $i++) { + if (strstr($stringArray[$i],':')) { + //check if a function has been indicated + if (strstr($stringArray[$i],'|')) + { + //get the function + $firstArray = explode('|',$stringArray[$i]); + $func = $firstArray[0]; + //replace the fields + $temp = explode(':',$firstArray[1]); + $stringArray[$i] = $rowArray[$temp[0]][$temp[1]]; + + if (!function_exists($func)) { + throw new Exception('Error in '.__METHOD__.': function '.$func.' does not exists..'); + } + //apply the function + $stringArray[$i] = call_user_func($func,$stringArray[$i]); + } + else + { + $temp = explode(':',$stringArray[$i]); + $stringArray[$i] = $rowArray[$temp[0]][$temp[1]]; + } + } + } + return implode('',$stringArray); + } + + //call the method replaceFields upon the $items array using the associative array $rowArray + public function replaceAll($item,$rowArray) { + $item['action'] = $this->replaceFields($item['action'],$rowArray); + $item['field'] = $this->replaceFields($item['field'],$rowArray); + $item['name'] = $this->replaceFields($item['name'],$rowArray); + return $item; + } + + //wrap the column with the tag td + public function wrapColumn($string, $className = null) { + return wrap($string,array('td'=>$className)); + } + + //wrap the row with the tag tr + public function wrapRow($string,$className = null) { + return wrap($string,array('tr'=>$className)); + } + + public function wrapList($string) { + return wrap($string,array('table'=>'listTable')); + } + + //method to create the HTML of the head of the table + public function createHead() { + $htmlHead = null; + foreach ($this->_head as $item) { + $temp = $item['action']; + $htmlHead .= $this->wrapColumn($temp,$item['type']); + } + return $htmlHead; + } + + //create the HTML of a single row (values taken from the associative array $rowArray) + public function getRowList($rowArray) { + $htmlList = null; + foreach ($this->_itemsList as $item) { + $item = $this->replaceAll($item,$rowArray); + + if (($this->_boundaries === 'top' and $item['type'] === 'moveupForm') or ($this->_boundaries === 'bottom' and $item['type'] === 'movedownForm') or ($this->_boundaries === 'both' and ($item['type'] === 'moveupForm' or $item['type'] === 'movedownForm'))) + { + $htmlList .= $this->wrapColumn(' ',$item['type']); + } + else + { + $temp = call_user_func_array(array($this,$item['type']),array($item)); + $htmlList .= $this->wrapColumn($temp,$item['type']); + } + } + return $htmlList; + } + + //$index: record number + public function ifInBoundaries($index) + { + $this->_boundaries = 'none'; + + if (!empty($this->position)) + { + if ($this->_recordNumber === 1 and strcmp($this->position[0],1) === 0) + { + $this->_boundaries = 'both'; + } + else if ($index === 0 and strcmp($this->position[0],1) === 0) + { + $this->_boundaries = 'top'; + } + else if ($index === ($this->_recordNumber-1) and strcmp($this->position[0],$this->position[1]) === 0) + { + $this->_boundaries = 'bottom'; + } + } + + } + + //create the HTML of the entire list. $queryResult: the array coming from the select query + public function render($queryResult) + { + //set the number of records + $this->_recordNumber = count($queryResult); + $htmlList = null; + //create the HTML of the head of the record list + $htmlList .= $this->wrapRow($this->createHead(),'listHead'); + for ($i = 0; $i < count($queryResult); $i++) + { + $this->ifInBoundaries($i); + $temp = $this->getRowList($queryResult[$i]); + $htmlList .= $this->wrapRow($temp,'listRow'); + } + return $this->wrapList($htmlList); + } + + public function generalForm($itemArray, $submitName, $submitValue) + { + $string = "
viewStatus."' method='POST'>\n"; + $name = (strcmp($itemArray['name'],'') !== 0) ? $itemArray['name'] : $submitName; + + if (strcmp($this->submitImageType,'yes') === 0) + { + $string .= "\n"; + $string .= "\n"; + } + else + { + $string .= "\n"; + } + + $string .= "\n"; + $string .= "
\n"; + return $string; + } + + public function moveupForm($itemArray) + { + return $this->generalForm($itemArray, 'moveupAction', 'up'); + } + + public function movedownForm($itemArray) + { + return $this->generalForm($itemArray, 'movedownAction', 'down'); + } + + public function editForm($itemArray) + { + return $this->generalForm($itemArray, 'generalAction', 'edit'); + } + + public function delForm($itemArray) + { + return $this->generalForm($itemArray, 'delAction', 'del'); + } + + public function associateForm($itemArray) + { + return $this->generalForm($itemArray, 'generalAction', 'link'); + } + + public function simpleText($itemArray) { + $string = "".$itemArray['action']."\n"; + return $string; + } + + public function simpleLink($itemArray) { + $string = "viewStatus."'>".$itemArray['name']."\n"; + return $string; + } + +} \ No newline at end of file diff --git a/h-source/Library/Helper/Menu.php b/h-source/Library/Helper/Menu.php new file mode 100755 index 0000000..119ada8 --- /dev/null +++ b/h-source/Library/Helper/Menu.php @@ -0,0 +1,75 @@ + array( + 'title' => 'back', + 'class' => 'mainMenuItem', + 'text' => 'Back', + 'url' => 'main' + ), + + 'add' => array( + 'title' => 'add a new record', + 'class' => 'mainMenuItem', + 'text' => 'Add', + 'url' => 'form/insert' + ), + + 'panel' => array( + 'title' => 'back to the Panel', + 'class' => 'mainMenuItem', + 'text' => 'Panel', + 'url' => 'main' + ) + + ); + + public function build($controller = null, $panelController = null) + { + $this->controller = $controller; + $this->panelController = $panelController; + } + + //$voices: comma-separated list of links you want to print + public function render($linksList) + { + $linksArray = explode(',',$linksList); + $menu = null; + foreach ($linksArray as $linkName) + { + //check that the voice exists + if (array_key_exists($linkName,$this->links)) + { + //check that the text and the ure are defined + if (isset($this->links[$linkName]['text']) and isset($this->links[$linkName]['url'])) + { + $title = isset($this->links[$linkName]['title']) ? "title='".$this->links[$linkName]['title']."'" : null; + $class = isset($this->links[$linkName]['class']) ? "class='".$this->links[$linkName]['class']."'" : null; + + //choose the controller (current or panel) + $controller = (strcmp($linkName,'panel') === 0) ? $this->panelController.'/' : $this->controller.'/'; + $viewStatus = (strcmp($linkName,'panel') === 0) ? null : $this->viewStatus; + + $href = Url::getRoot($controller.$this->links[$linkName]['url'].$viewStatus); + $text = $this->links[$linkName]['text']; + $menu .= "
$text
\n"; + } + } + } + return $menu; + } + +} \ No newline at end of file diff --git a/h-source/Library/Helper/Pages.php b/h-source/Library/Helper/Pages.php new file mode 100755 index 0000000..eec58f6 --- /dev/null +++ b/h-source/Library/Helper/Pages.php @@ -0,0 +1,108 @@ +_variableArg = $variableArg; + $this->_urlViewAction =$urlViewAction; //url of the controller and (/) main action + $this->previousString = $previousString; + $this->nextString = $nextString; + + } + + //return the number of pages + public function getNumbOfPages() + { + return $this->_numbOfPages; + } + + //get the limit of the select query clause + public function getLimit($currentPage,$recordNumber,$recordPerPage) + { + $this->_currentPage = $currentPage; + $this->_numbOfPages=(($recordNumber%$recordPerPage)===0) ? (int) ($recordNumber/$recordPerPage) : ((int) ($recordNumber/$recordPerPage))+1; + $start=(($currentPage-1)*$recordPerPage); + return "$start,$recordPerPage"; + } + + //return the page list string + public function render($pageNumber,$numberOfPages) + { + $pageList = null; + $pageList .= $this->pageLink($this->_currentPage-1,$this->previousString); + $pageList .= $this->recursiveLink($pageNumber,$numberOfPages); + $pageList .= $this->pageLink($this->_currentPage+1,$this->nextString); + return $pageList; + } + + //recorsive function in order to write the page list + public function recursiveLink($pageNumber,$numberOfPages) + { + + if ($numberOfPages === 0) return null; + + if ($numberOfPages === 1) { + return $this->pageLink($pageNumber); + } else { + return $this->pageLink($pageNumber) . $this->recursiveLink($pageNumber+1,$numberOfPages-1); + } + } + + public function pageLink($pageNumber, $string = null) { + if ($pageNumber > 0 and $pageNumber <= $this->_numbOfPages) { + return $this->html($pageNumber,$string); + } else { + return null; + } + } + + //return the html link + public function html($pageNumber,$string = null) { + if (isset($string)) { + $strNumber = $string; + $strClass = "class='itemListPage'"; + } else { + if ($pageNumber === $this->_currentPage) + { + $strNumber = $pageNumber; + $strClass = "class='currentPage'"; + } + else + { + $strNumber = $pageNumber; + $strClass = "class='itemListPage'"; + } + } + $this->viewArgs[$this->_variableArg] = $pageNumber; + $viewStatus = Url::createUrl(array_values($this->viewArgs)); + $href= Url::getRoot(null) . $this->_urlViewAction .$viewStatus; + return $this->getATag($href,$strNumber,$strClass); + } + + //get the HTMl of the tag + //$href: href of the link + //$text: the text of the link + //$strClass: the class of the link + public function getATag($href,$text,$strClass) + { + return "$text"; + } + +} \ No newline at end of file diff --git a/h-source/Library/Helper/Popup.php b/h-source/Library/Helper/Popup.php new file mode 100755 index 0000000..9ceac72 --- /dev/null +++ b/h-source/Library/Helper/Popup.php @@ -0,0 +1,87 @@ +viewArgs[$this->pageArg] is set to 1 if $this->pageArg !== null + + //the type of the popup. If type !=exclusive, than each voice selected is added to the where clause. If type=exclusive, the selection of a popup voice causes the unselection of the other voices + public $type = null; + + //list of popup names + public $popupItems = array(); + + public function build($url, $popupArray = null, $type = 'exclusive', $pageArg = null) { + $this->url = $url; + $this->popupArray = $popupArray; + $this->pageArg = $pageArg; + $this->type = $type; + + foreach ($this->popupArray as $field => $popup) + { + $this->popupItems[] = $field; + } + } + + //check that the ViewArgs array is complete + public function checkViewArgs() + { + foreach ($this->popupArray as $field => $popup) + { + if (!array_key_exists($field,$this->viewArgs)) return false; + } + return true; + } + + //unselect the voices different from the current one + public function unselect($currentVoice) + { + foreach ($this->popupItems as $item) + { + if (strcmp($item,$currentVoice) !== 0) $this->viewArgs[$item] = Params::$nullQueryValue; + } + } + + public function render() { + $returnString = null; + if ($this->checkViewArgs()) + { + if (isset($this->viewArgs[$this->pageArg])) + { + $this->viewArgs[$this->pageArg] = 1; + } + foreach ($this->popupArray as $field => $popup) + { + if ($this->type === 'exclusive') $this->unselect($field); + //save the value of the current ViewArg + $tempArg = $this->viewArgs[$field]; + $returnString .= "\n"; + $this->viewArgs[$field] = $tempArg; + } + if (count($this->popupArray)>0) { + $returnString .= "\n"; + } + } + return $returnString; + } + +} \ No newline at end of file diff --git a/h-source/Library/Helper/index.html b/h-source/Library/Helper/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Helper/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Hooks.php b/h-source/Library/Hooks.php new file mode 100644 index 0000000..fa005b9 --- /dev/null +++ b/h-source/Library/Hooks.php @@ -0,0 +1,21 @@ +'value') + //$className: the class name of the select + //$idName: name of the id + static public function select($name, $value, $options, $className = null, $idName = null) + { + $strClass = isset($className) ? "class='".$className."'" : null; + $idStr = isset($idName) ? "id='".$idName."'" : null; + + $returnString = null; + $returnString .= "\n"; + return $returnString; + } + + //return the HTML of an + //$name: the name of the input + //$value: the value of the input + //$className: the class name of the input + //$idName: name of the id + static public function input($name, $value, $className = null, $idName = null) + { + $strClass = isset($className) ? "class='".$className."'" : null; + $idStr = isset($idName) ? "id='".$idName."'" : null; + + $returnString ="\n"; + return $returnString; + } + + //return the HTML of a checkBox + //$name: name of the checkBox (string) + //$value: the value of the checkBox (string or number) + //$option: option of the checkBox (string or number) + //$className: the class name of the checkBox (string) + //$idName: name of the id + static public function checkbox($name, $value, $option, $className = null, $idName = null) + { + $strClass = isset($className) ? "class='".$className."'" : null; + $idStr = isset($idName) ? "id='".$idName."'" : null; + + $str = (strcmp($value,$option) === 0) ? "checked = 'checked'" : null; + return "\n"; + } + + //return the HTML of a hidden entry + //$name: name of the hidden entry (string) + //$value: the value of the hidden entry (string or number) + static public function hidden($name, $value) + { + return "\n"; + } + + //return the HTML of a password entry + //$name: name of the password entry (string) + //$value: the value of the password entry (string or number) + //$idName: name of the id + static public function password($name, $value, $className = null, $idName = null) + { + $strClass = isset($className) ? "class='".$className."'" : null; + $idStr = isset($idName) ? "id='".$idName."'" : null; + + return "\n"; + } + + //return the HTML of a textarea + //$name: name of the textarea (string) + //$value: the value of the textarea (string or number) + //$idName: name of the id + static public function textarea($name, $value, $className = null, $idName = null) + { + $strClass = isset($className) ? "class='".$className."'" : null; + $idStr = isset($idName) ? "id='".$idName."'" : null; + + return "\n"; + } + + //return the HTML of a radio button + //$name: name of the radio button + //$value: the selected value of the radio button (set $value equal to null if you don't want to select an option) + //$options: options of the radio button. This param can be a comma-separated list of options or an associative array ('name'=>'value') + //$className: the class name of the radio button + //$position: position of the strings of the radio with respect to the "circles". It can be before or after + //$idName: name of the id + static public function radio($name, $value, $options, $className = null, $position = 'after', $idName = null) + { + $strClass = isset($className) ? "class='".$className."'" : null; + $idStr = isset($idName) ? "id='".$idName."'" : null; + + $returnString = null; + + if (is_string($options)) { + $tempArray = explode(',',$options); + foreach ($tempArray as $item) + { + $optionsArray[$item] = $item; + } + } else { + $optionsArray = $options; + } + + foreach ($optionsArray as $optionName => $optionValue) { + + if ($position === 'before') + { + $before = $optionName; + $after = null; + } + else + { + $before = null; + $after = $optionName; + } + + $str= (strcmp($value,$optionValue) === 0) ? "checked='checked'" : null; + $returnString .= "$before$after\n"; + } + + return $returnString; + } + +} \ No newline at end of file diff --git a/h-source/Library/Html/index.html b/h-source/Library/Html/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Html/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Image/Gd/Captcha.php b/h-source/Library/Image/Gd/Captcha.php new file mode 100644 index 0000000..ace4806 --- /dev/null +++ b/h-source/Library/Image/Gd/Captcha.php @@ -0,0 +1,85 @@ + 150, + 'boxHeight' => 100, + 'charNumber' => 6, + 'fontPath' => $here.'/External/Fonts/FreeFont/FreeMono.ttf', + 'undulation' => true, + 'align' => false, + 'charHeight' => 28 + ); + + //set the $this->scaffold->params array + if (is_array($params)) + { + foreach ($params as $key => $value) + { + $defaultParams[$key] = $value; + } + } + $this->params = $defaultParams; + + $this->string = generateString($this->params['charNumber']); + } + + public function render() + { + //space among characters + $space = $this->params['boxWidth'] / ($this->params['charNumber']+1); + //create the image box + $img = imagecreatetruecolor($this->params['boxWidth'],$this->params['boxHeight']); + + $background = imagecolorallocate($img,255,255,255); + $border = imagecolorallocate($img,0,0,0); + $colors[] = imagecolorallocate($img,mt_rand(0,125),mt_rand(0,125),mt_rand(0,125)); + $colors[] = imagecolorallocate($img,mt_rand(0,125),mt_rand(0,125),mt_rand(0,125)); + $colors[] = imagecolorallocate($img,mt_rand(0,125),mt_rand(0,125),mt_rand(0,125)); + + //create the background + imagefilledrectangle($img,1,1,$this->params['boxWidth']-2,$this->params['boxHeight']-2,$background); + imagerectangle($img,0,0,$this->params['boxWidth']-1,$this->params['boxHeight']-2,$border); + + //set the text + for ($i=0; $i< $this->params['charNumber']; $i++) + { + $color = $colors[$i % count($colors)]; + $char = substr($this->string,$i,1); + $fontPath = $this->params['fontPath']; + $angle = $this->params['undulation'] === false ? 0 : -20+rand(0,40); + $yposFixed = (int)(($this->params['boxHeight'])/2); + $ypos = $this->params['align'] === true ? $yposFixed : $yposFixed + mt_rand(0,10); + $charHeight = $this->params['charHeight']; + imagettftext($img,$charHeight + rand(0,8),$angle,($i+0.3)*$space,$ypos,$color,$fontPath,$char); + } + + $noiseColor = imagecolorallocate($img, mt_rand(125,255), mt_rand(125,255), mt_rand(125,255)); + /* generate random dots in background */ + for( $i=0; $i<($this->params['boxWidth'] * $this->params['boxHeight'])/7; $i++ ) { + imagefilledellipse($img, mt_rand(0,$this->params['boxWidth']), mt_rand(0,$this->params['boxHeight']), 1, 1, $noiseColor); + } + + $_SESSION['captchaString'] = $this->string; + header('Content-Type: image/png'); + imagepng($img); + imagedestroy($img); + } + +} \ No newline at end of file diff --git a/h-source/Library/Image/Gd/Thumbnail.php b/h-source/Library/Image/Gd/Thumbnail.php new file mode 100644 index 0000000..5981175 --- /dev/null +++ b/h-source/Library/Image/Gd/Thumbnail.php @@ -0,0 +1,151 @@ +basePath = $basePath; + + $defaultParams = array( + 'imgWidth' => 100, + 'imgHeight' => 100, + 'defaultImage' => null, + 'cropImage' => 'no', + 'horizAlign' => 'left', + 'vertAlign' => 'top' + ); + + //set the $this->scaffold->params array + if (is_array($params)) + { + foreach ($params as $key => $value) + { + $defaultParams[$key] = $value; + } + } + $this->params = $defaultParams; + } + + //create the thumbnail + //$imageName: the name of the file inside $this->basePath + public function render($imageFile) + { + $imagePath = $this->basePath . basename($imageFile); + + if (!file_exists($imagePath) and isset($this->params['defaultImage'])) $imagePath = $this->params['defaultImage']; + + $img = null; + $ext = strtolower(end(explode('.', $imagePath))); + + if (strcmp($ext,'jpg') === 0 or strcmp($ext,'jpeg') === 0) { + $img = @imagecreatefromjpeg($imagePath); + } else if (strcmp($ext,'png') === 0) { + $img = @imagecreatefrompng($imagePath); + } else if (strcmp($ext,'gif') === 0) { + $img = @imagecreatefromgif($imagePath); + } + + //If an image was successfully loaded, test the image for size + if ($img) { + //image size + $width = imagesx($img); + $height = imagesy($img); + + if ($this->params['cropImage'] === 'no') + { + $scale = min($this->params['imgWidth']/$width, $this->params['imgHeight']/$height); + } + else if ($this->params['cropImage'] === 'yes') + { + $scale = max($this->params['imgWidth']/$width, $this->params['imgHeight']/$height); + } + + if ($scale < 1) { + + $xSrc = 0; + $ySrc = 0; + + if ($this->params['cropImage'] === 'no') + { + $newWidth = floor($scale*$width); + $newHeight = floor($scale*$height); + } + else if ($this->params['cropImage'] === 'yes') + { + + $newWidth = $this->params['imgWidth']; + $newHeight = $this->params['imgHeight']; + $oldWidth = $width; + $oldHeight = $height; + $width = floor($newWidth/$scale); + $height = floor($newHeight/$scale); + + switch ($this->params['horizAlign']) + { + case 'left': + $xSrc = 0; + break; + case 'right': + $xSrc = floor(($oldWidth-$width)); + break; + case 'center': + $xSrc = floor(($oldWidth-$width)/2); + break; + default: + $xSrc = $this->params['horizAlign']; + } + + switch ($this->params['vertAlign']) + { + case 'top': + $ySrc = 0; + break; + case 'bottom': + $ySrc = floor(($oldHeight-$height)); + break; + case 'center': + $ySrc = floor(($oldHeight-$height)/2); + break; + default: + $ySrc = $this->params['vertAlign']; + } + + } + + //temp image + $tmpImg = imagecreatetruecolor($newWidth, $newHeight); + + //copy and resize + imagecopyresized($tmpImg, $img, 0, 0, $xSrc, $ySrc,$newWidth, $newHeight, $width, $height); + imagedestroy($img); + $img = $tmpImg; + } + + } + + if (!$img) { + $img = imagecreate($this->params['imgWidth'], $this->params['imgHeight']); + imagecolorallocate($img,200,200,200); + } + + //print the image + header("Content-type: image/jpeg"); + imagejpeg($img); + + } + +} \ No newline at end of file diff --git a/h-source/Library/Image/Gd/index.html b/h-source/Library/Image/Gd/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Image/Gd/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Image/index.html b/h-source/Library/Image/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Image/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Lang/Eng/DbCondStrings.php b/h-source/Library/Lang/Eng/DbCondStrings.php new file mode 100644 index 0000000..1edae98 --- /dev/null +++ b/h-source/Library/Lang/Eng/DbCondStrings.php @@ -0,0 +1,17 @@ +The value of ". $field ." is already present. Please choose a different value.\n"; + } + +} diff --git a/h-source/Library/Lang/Eng/ModelStrings.php b/h-source/Library/Lang/Eng/ModelStrings.php new file mode 100644 index 0000000..411d196 --- /dev/null +++ b/h-source/Library/Lang/Eng/ModelStrings.php @@ -0,0 +1,19 @@ + "
Query error: Contact the administrator!
\n", + "executed" => "
Operation executed!
\n", + "associate" => "
Referential integrity problem: record associated to some other record in a child table. Break the association before.
\n", + "no-id" => "
Alert: record identifier not defined!
\n", + "not-linked" => "
The Item is not associated : you can't dissociate it
", + "linked" => "
The Item is already associated: you can't associate it another time
" + ); + +} diff --git a/h-source/Library/Lang/Eng/UploadStrings.php b/h-source/Library/Lang/Eng/UploadStrings.php new file mode 100644 index 0000000..195fd5f --- /dev/null +++ b/h-source/Library/Lang/Eng/UploadStrings.php @@ -0,0 +1,27 @@ + "
Error: verify the permissions of the file/directory
\n", + "executed" => "
Operation executed!
\n", + "not-child" => "
The selected directory is not a child of the base directory
\n", + "not-dir" => "
The selected directory is not a directory
\n", + "not-empty" => "
The selected directory is not empty
\n", + "no-folder-specified" => "
No folder has been specified
\n", + "no-file-specified" => "
No file has been specified
\n", + "not-writable" => "
The folder is not writable
\n", + "not-writable-file" => "
The file is not writable
\n", + "dir-exists" => "
The directory is already present in the current folder
\n", + "no-upload-file" => "
There is no file to upload
\n", + "size-over" => "
The size of the file is too big
\n", + "not-allowed-ext" => "
The extension of the file you want to upload is not allowed
\n", + "file-exists" => "
The file is already present in the current folder
\n" + ); + +} diff --git a/h-source/Library/Lang/Eng/ValCondStrings.php b/h-source/Library/Lang/Eng/ValCondStrings.php new file mode 100644 index 0000000..b9d132e --- /dev/null +++ b/h-source/Library/Lang/Eng/ValCondStrings.php @@ -0,0 +1,76 @@ +". $element ." not defined!\n"; + } + + //if the elements are not equal + public function getNotEqualResultString($element) + { + return "
Different values: $element
\n"; + } + + //if the element is not alphabetic + public function getNotAlphabeticResultString($element) + { + return "
".$element." has to be alphabetic
\n"; + } + + //if the element is not alphanumeric + public function getNotAlphanumericResultString($element) + { + return "
".$element." has to be alphanumeric
\n"; + } + + //if the element is not a decimal digit + public function getNotDecimalDigitResultString($element) + { + return "
".$element." has to be a decimal digit
\n"; + } + + //if the element has the mail format + public function getNotMailFormatResultString($element) + { + return "
".$element." doesn't seem an e-mail address
\n"; + } + + //if the element is numeric + public function getNotNumericResultString($element) + { + return "
".$element." has to be a numeric
\n"; + } + + //if the element (string) length exceeds the value of characters (defined by $maxLength) + public function getLengthExceedsResultString($element,$maxLength) + { + return "
".$element." exceeds the value of $maxLength characters
\n"; + } + + //if the element is one of the strings indicated by $stringList (a comma-separated list of strings) + public function getIsForbiddenStringResultString($element,$stringList) + { + return "
".$element." can't be one of the following strings: $stringList
\n"; + } + + //if the element is not one of the strings indicated by $stringList (a comma-separated list of strings) + public function getIsNotStringResultString($element,$stringList) + { + return "
".$element." has to be one of the following strings: $stringList
\n"; + } + + //if the element is not one of the strings indicated by $stringList (a comma-separated list of strings) + public function getDoesntMatchResultString($element,$regExp) + { + return "
".$element." has to match the following regular expression: $regExp
\n"; + } + +} diff --git a/h-source/Library/Lang/Eng/index.html b/h-source/Library/Lang/Eng/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Lang/Eng/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Lang/ResultStrings.php b/h-source/Library/Lang/ResultStrings.php new file mode 100644 index 0000000..db1095c --- /dev/null +++ b/h-source/Library/Lang/ResultStrings.php @@ -0,0 +1,25 @@ +string[$stringName])) + { + return $this->string[$stringName]; + } + else + { + return 'result string not defined!'; + } + } + +} diff --git a/h-source/Library/Lang/index.html b/h-source/Library/Lang/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Lang/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/ModAbstract.php b/h-source/Library/ModAbstract.php new file mode 100644 index 0000000..885f64f --- /dev/null +++ b/h-source/Library/ModAbstract.php @@ -0,0 +1,25 @@ +simpleXmlObj = $simpleXmlObj; + } + + //define the abstract method to render (create the HTML) of the single module + //$xmlObject: simpleXML object + abstract public function render(); + +} diff --git a/h-source/Library/Model/Base.php b/h-source/Library/Model/Base.php new file mode 100755 index 0000000..1aaadca --- /dev/null +++ b/h-source/Library/Model/Base.php @@ -0,0 +1,1140 @@ +fields fields + public $form = null; //reference to a Form_Form object + public $formStruct = null; //the form structure + + public $submitName = null; //the current submitName (from the form) + public $identifierName = 'identifier'; + + public $notice = null; //a string explaining the result of the query applied (or not if an error occured): executed, error, etc + public $result = true; //the result of validate conditions, database conditions and query. It can be 'true' or 'false' + public $queryResult = false; //the result of the query + + //conditions that have to be satisfied before applying the query + //Ex: 'update'=>'checkEmpty:titolo,autore','submitName'=>'conditions' + public $strongConditions = array(); + + //conditions that have to be satisfied before applying the query + //Ex: 'update'=>'checkEmpty:titolo,autore','submitName'=>'conditions' + //do not return error if a value is equal to '' or null + public $softConditions = array(); + + //conditions that have to be satisfied before applying the query + //check that the new values inserted satisfy some conditions + //Ex: 'update'=>'checkUniqueCompl:titolo,autore;checkUnique:titolo','insert'=>'checkUnique:titolo' + public $databaseConditions = array(); + + public $popupArray = array(); //array of popup objects (see popup.php) + + public $supplInsertValues = array(); //associative array defining supplementary values to be inserted on each insert query. It has to have the following form: array(field1 => value1,field2 => value2, ...) + + public $supplUpdateValues = array(); //associative array defining supplementary values to be inserted on each update query. It has to have the following form: array(field1 => value1,field2 => value2, ...) + + public $select = null; //fields that have to be selected in select queries + public $where = array(); //associative array containing all the where clauses ($field => $value) + //group by, order by and limit clauses + public $groupBy = null; + public $orderBy = null; + public $limit = null; + + public $from = null; //from clause of the select queries + public $on = null; //join part of the where clause of the select queries + public $using = null; //using clause + + public $toList = false; //if the result have to be given in a list format + public $listArray = array(); //array containing the $key and the $value to be used to extract a list from a resultSet + + //logic operator between statements in the where clause of select queries + public $logicalOperators = array('AND'); + + protected $_tables='itemTable,boxTable,item_boxTable'; + protected $_idFields='id_item,id_box'; + protected $_tablesArray=array(); + protected $_idFieldsArray=array(); + protected $_where = array(); + + //the name of the field that has to be used to order the rows of the main table of the model + protected $_idOrder = null; + + protected $_onDelete = 'check'; //can be 'nocheck' or 'check'. check: referential integrity check. nocheck: no referential integrity check + protected $_reference = null; //array containing the child table that have a reference to this table and the foreign key of the child table-> array($childTable,$foreignKey) + + protected $_popupItemNames = array(); //the fields to be used as names in the popupArray elements. Associative array ($itemNameField1 => $itemNameValue1, ...) + + //the labels of the pop-up menus + protected $_popupLabels = array(); + + //functions that have to be applied upon the label fields of the popup menu + protected $_popupFunctions = array(); + + protected $_popupWhere = array(); //where clause for the pupup menu + + protected $_resultString; //reference to the class containing all the result strings of the db queries + protected $_dbCondString; //reference to the class containing all the result strings of the database conditions + + protected $_backupFields = ''; //field saved after the delFields method has been applied + protected $_backupValues = array(); //values saved after the delFields method has been applied + protected $_allowedDbMethods = array('update','insert','del','moveup','movedown'); //methods that can be called by the updateTable method + + protected $submitNames = array( + 'update' => 'updateAction', + 'insert' => 'insertAction', + 'del' =>'delAction', + 'moveup' =>'moveupAction', + 'movedown' =>'movedownAction' + ); + + protected $identifierValue = null; //the value of the identifier ($_POST[$this->identifier]) + protected $arrayExt; //arrayExt object (see library/arrayExt.php) + + protected $_arrayStrongCheck; //Array_Validate_Strong object + protected $_arraySoftCheck; //Array_Validate_Soft object + + public $db; //reference to the database layer class + protected $_lang = 'Eng'; //language of notices + + + public function __construct() { + $this->_tablesArray = explode(',',$this->_tables); + $this->_idFieldsArray = explode(',',$this->_idFields); + $this->_where[$this->_idFieldsArray[0]] = $this->_tablesArray[0]; + $this->arrayExt = new ArrayExt(); + + //initialize the validate objects + $this->_arrayStrongCheck = new Array_Validate_Strong($this->_lang); + $this->_arraySoftCheck = new Array_Validate_Soft($this->_lang); + + $this->identifierName = $this->_idFieldsArray[0]; + + //create the $_resultString object (result strings of the db queries) + $modelStringClass = 'Lang_'.$this->_lang.'_ModelStrings'; + if (!class_exists($modelStringClass)) + { + $modelStringClass = 'Lang_Eng_ModelStrings'; + } + $this->_resultString = new $modelStringClass(); + + //create the $_dbCondString object (result strings of the database conditions) + $dbCondStringClass = 'Lang_'.$this->_lang.'_DbCondStrings'; + if (!class_exists($dbCondStringClass)) + { + $dbCondStringClass = 'Lang_Eng_DbCondStrings'; + } + $this->_dbCondString = new $dbCondStringClass(); + + //instantiate the database class + $this->db = Factory_Db::getInstance(DATABASE_TYPE); + } + + //set the submitNames property (array) + //$methodName : the method name, $submitName: the submit name of the submit action of the form + public function setSubmitNames($methodName,$submitName) + { + if (!in_array($methodName,$this->_allowedDbMethods)) + { + throw new Exception('query type "'.$methodName. '" not allowed in '. __METHOD__); + } + $this->submitNames[$methodName] = $submitName; + } + + //get the last query executed + public function getQuery() + { + return $this->db->query; + } + + //get the where clause of the select query + public function getWhereQueryClause() + { + return $this->where; + } + + //set the where clause of the select query + //whereArray = array ($table_field => $value) + public function setWhereQueryClause($whereArray) + { + $this->where = $whereArray; + } + + //append the whereArray clause to $this_->whereClause + //whereArray = array ($table_field => $value) + public function appendWhereQueryClause($whereArray) + { + $this->where = array_merge($this->where,$whereArray); + } + + //drop the char $char from the beginning of the string $string + public function dropStartChar($string,$char) + { + while(strcmp($string[0],$char) === 0) + { + $string = substr($string,1); + } + return $string; + } + + //get the table name from $this->_where. If the table is not present then return $this->_tablesArray[0] + public function getTableName($field) + { + return isset($this->_where[$field]) ? $this->_where[$field] : $this->_tablesArray[0]; + } + + //method to create the where clause of the select query from the $this->where array + //$level: level of the ricorsion + //$whereClauseLevel: array containing the field=>value statements of the where clause. If $whereClause = null than $this->where is considered + public function createWhereClause($level = 0, $whereClauseLevel = null) + { + $whereClause = null; + $whereClauseArray = array(); + + $whereClause = isset($whereClauseLevel) ? $whereClauseLevel : $this->where; + + foreach ($whereClause as $field => $value) + { + if (is_array($value)) + { + $newValue = $this->createWhereClause($level+1, $value); + if (isset($newValue)) $whereClauseArray[] = $newValue; + } + else + { + $flag = 0; //equal where clause + if (isset($field)) + { + //drop the 'n:' and '-' chars from $field + $fieldClean = str_replace('n!',null,$field); + $fieldClean = $this->dropStartChar($fieldClean,'-'); + if (strcmp($value,Params::$nullQueryValue) !== 0 or (Params::$nullQueryValue === false)) + { + foreach (params::$whereClauseSymbolArray as $symbol) + { + if (strstr($value,$symbol)) + { + //check if write or not the table name + $tableName = strstr($field,'n!') ? null : $this->getTableName($field).'.'; + $whereClauseArray[] = $tableName.$fieldClean.' '.$value; + $flag = 1; //not equal where clause + break; + } + } + if ($flag === 0) + { + $value = '"'.$value.'"'; + //check if write or not the table name + $tableName = strstr($field,'n!') ? null : $this->getTableName($field).'.'; + $whereClauseArray[] = $tableName.$fieldClean.'='.$value; + } + } + } + } + } + //get the logic operator at the current level + $logicOper = isset($this->logicalOperators[$level]) ? ' '.$this->logicalOperators[$level].' ' : ' AND '; + $whereClause = !empty($whereClauseArray) ? implode($logicOper,$whereClauseArray) : null; + $whereClause = (isset($whereClause) and $level>0) ? '('.$whereClause.')' : $whereClause; + return $whereClause; + } + + + //get the submitName having its key (the method name) + public function getSubmitName($key) + { + if (!array_key_exists($key,$this->submitNames)) + { + return 'generalAction'; +// throw new Exception('query type "'.$key. '" not allowed in '.__METHOD__); + } + return $this->submitNames[$key]; + + } + + + //return the values, taken from the $_POST array, to be inserted inside the forms + //$queryType: insert or update + //$func: sanitize function to apply upon each value + //$id: if $queryType='update' that the values are taken from the record (of the main table of this model) having the primary key equal to $id + //$defaultValues = associative array of the form: array($entry=>$defaultValue) + //$functionsIfFromDb = associative array of the form: array($entry=>$function_to_be_applied) + public function getFormValues($queryType = 'insert', $func = 'sanitizeHtml',$id = null,$defaultValues = array(),$functionsIfFromDb = array()) + { + $arrayType = array('update','insert'); + $values = array(); + $idName = $this->identifierName; + if (in_array($queryType,$arrayType)) + { + $ident = null; + if (isset($id)) + { + $ident = (int)$id; + } + else if (isset($_POST[$idName])) + { + $ident = (int)$_POST[$idName]; + } + if ($this->result) + { + if ($queryType === 'update') + { + if (isset($ident)) + { + $recordArray = $this->selectId($ident); + + $fieldsArray = explode(',',$this->fields); + + foreach ($fieldsArray as $field) + { + $values[$field] = array_key_exists($field,$recordArray) ? $recordArray[$field] : ''; + } + + $values[$idName] = $ident; + + //apply the functions upon entries + foreach ($functionsIfFromDb as $entry => $funcUponEntry) + { + if (array_key_exists($entry,$values)) + { + if (!function_exists($funcUponEntry)) { + throw new Exception('Error in '.__METHOD__.': function '.$funcUponEntry. ' does not exists'); + } + + $values[$entry] = call_user_func($funcUponEntry,$values[$entry]); + } + } + + } + } + else if ($queryType === 'insert') + { + + $tempArray = is_array($defaultValues) ? $defaultValues : array(); + + $values = $this->arrayExt->subset($tempArray,$this->fields,$func); + + } + } + else + { + $values = $this->arrayExt->subset($_POST,$this->fields,$func); + + if ($queryType === 'update') + { + $values[$idName] = $ident; + } + } + } + return $values; + } + + + //method to set the properties $this->fields and $this->values + public function setFields($fields,$func = 'sanitizeAll') + { + $this->values = $this->arrayExt->subset($_POST,$fields,$func); + $this->fields = $this->extractFields($fields); + + //set the backup variables + $this->_backupFields = $this->fields; + $this->_backupValues = $this->values; + } + + + //clear the fields list + public function clearFields() + { + $this->_backupFields = $this->fields; + $this->_backupValues = $this->values; + $this->fields = ''; + $this->values = array(); + } + + //del the fields written in the $list argument. The $list argument has to be of the type: field1,field2,... + public function delFields($list) + { + $this->_backupFields = $this->fields; + $this->_backupValues = $this->values; + $this->values = $this->arrayExt->subsetComplementary($this->values,$list); + $this->fields = implode(',',array_keys($this->values)); + } + + //restore the fields and values saved in $_backupFields and $_backupValues + public function restoreFields() + { + $this->fields = $this->_backupFields; + $this->values = $this->_backupValues; + } + + //method to clean the $fields string deleting the colons (and the word after the colon) + public function extractFields($fields) { + $fieldsArray = explode(',',$fields); + $resultString = array(); + foreach ($fieldsArray as $field) { + if (strstr($field,':')) { + $temp = explode(':',$field); + $resultString[] = $temp[0]; + } else { + $resultString[] = $field; + } + } + return implode(',',$resultString); + } + + //add the supplementary value on insert and update queries + //$queryType: insert or update + public function setSupplValues($queryType) + { + if ($queryType === 'insert') + { + $supplValues = $this->supplInsertValues; + } + else if ($queryType === 'update') + { + $supplValues = $this->supplUpdateValues; + } + + $baseFields = implode(',',array_keys($this->values)); + + $supplFields = implode(',',array_keys($supplValues)); + $supplFields = (strcmp($supplFields,'') === 0) ? $supplFields : ',' . $supplFields; + + $fields = $baseFields . $supplFields; + $values = array_merge(array_values($this->values),array_values($supplValues)); + + return array($fields,$values); + } + + + //method to call the update query (overriding of the base_db del method) + //update the record with the primary key equal to $id (default) + //if $whereClause is set then use $whereClause as where clause of the update query + public function update($id = null, $whereClause = null) + { + if (!is_array($this->supplUpdateValues)) + { + throw new Exception('error in ' . __METHOD__ . ': the supplUpdateValues property has to be an array.'); + } + $el = $this->setSupplValues('update'); + $this->queryResult = false; + + if (isset($whereClause)) + { + $result = $this->db->update($this->_tablesArray[0],$el[0],$el[1],$whereClause); + $this->setNotice($result); + return $result; + } + else + { + if (isset($id)) + { + $where = $this->_idFieldsArray[0].'='.(int)($id); + $result = $this->db->update($this->_tablesArray[0],$el[0],$el[1],$where); + $this->setNotice($result); + return $result; + } + else + { + $this->notice = $this->_resultString->getString('no-id'); + $this->result = false; + $this->identifierValue = null; + return false; + } + } + } + + //method to call the insert query (overriding of the base_db del method) + public function insert() { + + $this->queryResult = false; + if (!is_array($this->supplInsertValues)) { + throw new Exception('error in ' . __METHOD__ . ': the supplInsertValues property has to be an array.'); + } + + if (isset($this->_idOrder)) + { + $maxValue = $this->db->getMax($this->_tablesArray[0],$this->_idOrder); + $this->supplInsertValues[$this->_idOrder] = (int)$maxValue + 1; + } + + $el = $this->setSupplValues('insert'); + + $result = $this->db->insert($this->_tablesArray[0],$el[0],$el[1]); + $this->setNotice($result); + return $result; + } + + //method to call the delete query (overriding of the base_db del method) + public function del($id = null, $whereClause = null) { + + $this->queryResult = false; + + if (isset($whereClause)) + { + $result = $this->db->del($this->_tablesArray[0],$whereClause); + $this->setNotice($result); + return $result; + } + else + { + if (isset($id)) { + $where = $this->_idFieldsArray[0].'='.(int)$id; + $result = $this->db->del($this->_tablesArray[0],$where); + $this->setNotice($result); + return $result; + } else { + $this->notice = $this->_resultString->getString('no-id'); + $this->result = false; + $this->identifierValue = null; + return false; + } + } + } + + //move to the top the record having $this->_idOrder = $id + //where clause + public function moveup($id) + { + return $this->move($id,'up'); + } + + //move to the top the record having $this->_idOrder = $id + //where clause + public function movedown($id) + { + return $this->move($id,'down'); + } + + //move the record having $this->_tablesArray[0] = $id + //$par: 'up' or 'down' + //where clause + public function move($id,$par = 'up') + { + $this->queryResult = false; + if (isset($id)) + { + $increm = ($par === 'up') ? 1 : -1; + + $backupLimit = $this->limit; + $this->limit = null; + + $data = $this->getFields($this->_tablesArray[0].'.'.$this->_idFieldsArray[0].','.$this->_tablesArray[0].'.'.$this->_idOrder); + + for($i = 0; $i < count($data); $i++) + { + if (strcmp($data[$i][$this->_tablesArray[0]][$this->_idFieldsArray[0]],$id) === 0) + { + if (($par === 'up' and $i !== 0) or ($par === 'down' and $i !== (count($data)-1))) + { + $prevOrder = $data[$i-$increm][$this->_tablesArray[0]][$this->_idOrder]; + $prevId = $data[$i-$increm][$this->_tablesArray[0]][$this->_idFieldsArray[0]]; + $currentOrder = $data[$i][$this->_tablesArray[0]][$this->_idOrder]; + $currentId = $data[$i][$this->_tablesArray[0]][$this->_idFieldsArray[0]]; + + //exchange the id_order of the two record + $res1 = $this->db->update($this->_tablesArray[0],$this->_idOrder,array($prevOrder),$this->_idFieldsArray[0]."='$currentId'"); + $res2 = $this->db->update($this->_tablesArray[0],$this->_idOrder,array($currentOrder),$this->_idFieldsArray[0]."='$prevId'"); + $result = ($res1 and $res2); + $this->setNotice($result); + return $result; + } + } + } + + $this->limit = $backupLimit; + } + else + { + $this->notice = $this->_resultString->getString('no-id'); + $this->result = false; + $this->identifierValue = null; + return false; + } + return false; + } + + public function setNotice($result) { + if ($result) { + $this->notice = $this->_resultString->getString('executed'); + $this->result = true; + $this->queryResult = true; + } else { + $this->notice = $this->_resultString->getString('error'); + $this->result = false; + $this->queryResult = false; + } + } + + //method used to verify that the value of a field is not duplicated + //$fieldsList: list of fields to check. Ex: field1,field2,... + //$where: the where clause + public function checkUnique($fieldsList,$where = null) + { + $errorString = null; + $numb = 0; + $fieldsArray = explode(',',$fieldsList); + $queryFieldsArray = explode(',',$this->fields); + foreach ($fieldsArray as $field) + { + if (in_array($field,$queryFieldsArray)) + { + if ($this->db->recordExists($this->_tablesArray[0],$field,$this->values[$field],$where)) + { + $errorString .= $this->_dbCondString->getNotUniqueString($field); + $numb++; + } + } + } + $this->notice = $errorString; + return $numb === 0 ? true : false; + } + + //like checkUnique: check all the records of the table apart from the record that has to be modified + public function checkUniqueCompl($fieldsList,$id = null) + { + if (isset($id)) + { + $where = $this->_idFieldsArray[0].'!='.(int)($id); + return $this->checkUnique($fieldsList,$where); + } else { + $this->notice = $this->_resultString->getString('no-id'); + return false; + } + } + + //method to apply the database conditions listed in the $this->databaseConditions associative array + //$queryType: indicates what set of validate conditions has to be considered (it's the key of the associative array) + public function applyDatabaseConditions($queryType,$id = null) + { + if (array_key_exists($queryType,$this->databaseConditions)) + { + if (!is_array($this->databaseConditions[$queryType])) + { + throw new Exception('error in method '.__METHOD__.' : databaseConditions['.$queryType.'] has to be an associative array'); + } + + foreach ($this->databaseConditions[$queryType] as $key => $values) + { + + //personalized error string + $altErrorString = null; + + //delete all the '+' chars + $key = $this->dropStartChar($key,'+'); + + if (strcmp($values,'all') === 0 or strstr($values,'all|')) + { + if (strstr($values,'all|')) + { + $values = str_replace('all|',$this->fields.'|',$values); + } + else + { + $values = $this->fields; + } + } + + if (strstr($values,'|')) + { + $temp = explode('|',$values); + $altErrorString = "
".$temp[1]."
\n"; + $values = $temp[0]; + } + + $allowedMethod = array('checkUnique','checkUniqueCompl'); + if (!in_array($key,$allowedMethod)) + { + throw new Exception('error in method '.__METHOD__.' : method "'.$key. '" not allowed in the property named databaseConditions'); + } + if (!call_user_func_array(array($this,$key),array($values,$id))) + { + if (isset($altErrorString)) $this->notice = $altErrorString; + $this->result = false; + $this->queryResult = false; + return false; + } + } + return true; + } else { + return true; + } + } + + + //method to apply the validate conditions listed in the $this->strongConditions associative array + //$queryType: indicates what set of validate conditions has to be considered (it's the key of the associative array) + //$strength: 'strong' or 'soft' + public function applyValidateConditions($queryType,$strength = 'strong') + { + if ($strength === 'strong') + { + $validateObj = $this->_arrayStrongCheck; + $conditions = $this->strongConditions; + $errString = 'strongConditions'; + } + else + { + $validateObj = $this->_arraySoftCheck; + $conditions = $this->softConditions; + $errString = 'softConditions'; + + if (Params::$nullQueryValue !== false) + { + $conditions['insert']['+++++checkIsNotStrings|'.Params::$nullQueryValue] = 'all'; + $conditions['update']['+++++checkIsNotStrings|'.Params::$nullQueryValue] = 'all'; + } + } + + if (array_key_exists($queryType,$conditions)) + { + if (!is_array($conditions[$queryType])) + { + throw new Exception('error in method '.__METHOD__.' : '.$errString.'['.$queryType.'] has to be an associative array'); + } + + foreach ($conditions[$queryType] as $key => $values) + { + + //personalized error string + $altErrorString = null; + + //delete all the '+' chars + $key = $this->dropStartChar($key,'+'); + + if (strcmp($values,'all') === 0 or strstr($values,'all|')) + { + if (strstr($values,'all|')) + { + $values = str_replace('all|',$this->fields.'|',$values); + } + else + { + $values = $this->fields; + } + } + + if (strstr($values,'|')) + { + $temp = explode('|',$values); + $altErrorString = "
".$temp[1]."
\n"; + $values = $temp[0]; + } + + $baseArgs = array($_POST,$values); + + if (strstr($key,'|')) + { + $funcArray = explode('|',$key); + $funcName = $funcArray[0]; + array_shift($funcArray); + $funcArgs = array_merge($baseArgs,$funcArray); + } + else + { + $funcName = $key; + $funcArgs = $baseArgs; + } + + if (!method_exists($validateObj,$funcName) or $funcName === 'checkGeneric') + { + throw new Exception('error in method '.__METHOD__.' :method "'.$funcName. '" not allowed in '.$errString); + } + if (!call_user_func_array(array($validateObj,$funcName),$funcArgs)) + { + $this->notice .= (isset($altErrorString)) ? $altErrorString : $validateObj->errorString; + $this->result = false; + $this->queryResult = false; + return false; + } + } + return true; + } else { + return true; + } + } + + + //apply, in sequence, the strong,soft and database conditions + //$methodName: insert,update + //$id: the id of the record. It is necessary for database conditions + public function checkConditions($methodName,$id = null) + { + if ($this->applyValidateConditions($methodName,'strong')) + { + if ($this->applyValidateConditions($methodName,'soft')) + { + if ($this->applyDatabaseConditions($methodName,$id)) + { + return true; + } + } + } + return false; + } + + //method that calls the function indicated in $this->submitNames. Ex: if $_POST['delAction'] is found, then the "del" method is called. + public function updateTable($methodsList = '',$id = null) { + + $allowedMethodsArray = explode(',',$methodsList); + $resultArray = array(); + $this->identifierValue = null; + if (isset($id)) + { + $this->identifierValue = (int)$id; + } + else if (isset($_POST[$this->identifierName])) + { + $this->identifierValue = (int)$_POST[$this->identifierName]; + } + foreach ($this->submitNames as $methodName => $submitName) + { + if (array_key_exists($submitName,$_POST)) + { + $this->submitName = $submitName; + if (method_exists($this,$methodName)) + { + //if the method is allowed + if (in_array($methodName,$allowedMethodsArray)) + { + if ($this->checkConditions($methodName,$this->identifierValue)) + { + $this->notice = null; + call_user_func_array(array($this,$methodName),array($this->identifierValue)); + } + } + } + else + { + throw new Exception('method '.$methodName.' not defined in class '.__CLASS__.'; error in method '.__METHOD__.''); + } + return; //only one cycle! + } + } + } + + //method to build the array of popup objects + public function popupBuild() + { + foreach ($this->_popupItemNames as $field => $itemName) + { +// if (array_key_exists($field,$this->_where)) +// { + $fieldClean = str_replace('n!',null,$field); + $itemNameClean = str_replace('n!',null,$itemName); + $fieldClean = $this->dropStartChar($fieldClean,'-'); + $itemNameClean = $this->dropStartChar($itemNameClean,'-'); + + //fields that have to be extracted + $queryFields = ($fieldClean === $itemNameClean) ? $fieldClean : $fieldClean.','.$itemNameClean; + + $table = $this->getTableName($field); + $this->popupArray[$field] = new Popup(); + + $popupWhereClause = array_key_exists($field,$this->_popupWhere) ? $this->_popupWhere[$field] : null; + + $result = $this->db->select($table,$queryFields,$popupWhereClause,$fieldClean); + + if ($result and $result !== false) + { + //get the label of the popup menu + $label = array_key_exists($field,$this->_popupLabels) ? $this->_popupLabels[$field] : $table.' : '.$itemNameClean; + $this->popupArray[$field]->name = $label; + + //get the table name + $fieldTable = isset($result[0][$table][$fieldClean]) ? $table : Params::$aggregateKey; + $itemNameTable = isset($result[0][$table][$itemNameClean]) ? $table : Params::$aggregateKey; + + foreach ($result as $row) + { + $this->popupArray[$field]->itemsValue[] = $row[$fieldTable][$fieldClean]; + + if (array_key_exists($field,$this->_popupFunctions)) + { + if (!function_exists($this->_popupFunctions[$field])) + { + throw new Exception('Error in '.__METHOD__.': function '.$this->_popupFunctions[$field]. ' does not exists'); + } + + $tempName = call_user_func($this->_popupFunctions[$field],$row[$itemNameTable][$itemNameClean]); + } + else + { + $tempName = $row[$itemNameTable][$itemNameClean]; + } + + $this->popupArray[$field]->itemsName[] = $tempName; + } + } +// } + } + } + + + //get the element before and after the current one + //$key: the key of the self::$where array that indicates the field to be used in order to find out the records before and after + //$fields: the fields that have to be extracted + public function getNeighbours($key,$fields = '') + { + //backup of the values + $tempWhere = $this->where; + $tempLimit = $this->limit; + $tempOrderBy = $this->orderBy; + $this->limit = 1; + //before + $this->where[$key] = '<'.$tempWhere[$key]; + $this->orderBy = $this->getTableName($key).'.'.$key.' DESC'; + $dataAfter = $this->getFields($fields); + //after + $this->where[$key] = '>'.$tempWhere[$key]; + $this->orderBy = $this->getTableName($key).'.'.$key; + $dataBefore = $this->getFields($fields); + //restore the previous values + $this->where = $tempWhere; + $this->limit = $tempLimit; + $this->orderBy = $tempOrderBy; + $result[0] = isset($dataBefore[0]) ? $dataBefore[0] : null; + $result[1] = isset($dataAfter[0]) ? $dataAfter[0] : null; + return $result; + } + + //set the $select property and return the current object + public function select($fields = null) + { + $this->select = $fields; + return $this; + } + + //set the $from property and return the current object + public function from($tables = null) + { + $this->from = isset($tables) ? $tables : $this->_tables; + return $this; + } + + //set the $on property and return the current object + public function on($joinClause = '-') + { + $this->on = $joinClause; + return $this; + } + + //set the $using property and return the current object + public function using($using = null) + { + $this->using = $using; + return $this; + } + + //set the $where property and return the current object + public function where($where = array()) + { + $this->where = $where; + return $this; + } + + //append the $where array to the ::where property and return the current object + public function aWhere($where = array()) + { + $this->appendWhereQueryClause($where); + return $this; + } + + //set the $groupBy property and return the current object + public function groupBy($groupBy = null) + { + $this->groupBy = $groupBy; + return $this; + } + + //set the $orderBy property and return the current object + public function orderBy($orderBy = null) + { + $this->orderBy = $orderBy; + return $this; + } + + //set the $limit property and return the current object + public function limit($limit = null) + { + $this->limit = $limit; + return $this; + } + + //set the $listArray property + public function toList($key, $value = null) + { + $this->listArray = array($key,$value); + $this->toList = true; + return $this; + } + + //reset all the clauses of the select query + public function clear() + { + $this->select = null; + $this->where = array(); + $this->groupBy = null; + $this->orderBy = null; + $this->limit = null; + $this->from = null; + $this->on = null; + $this->using = null; + $this->toList = false; + return $this; + } + + //initialize and populate the ::form property (reference to a Form_Form object) + public function setForm($defAction = null, $defSubmit = array(), $defMethod = 'POST') + { + if (isset($this->formStruct)) + { + $action = array_key_exists('action',$this->formStruct) ? $this->formStruct['action'] : $defAction; + $submit = array_key_exists('submit',$this->formStruct) ? $this->formStruct['submit'] : $defSubmit; + $entries = array_key_exists('entries',$this->formStruct) ? $this->formStruct['entries'] : null; + $method = array_key_exists('post',$this->formStruct) ? $this->formStruct['post'] : $defMethod; + + $this->form = new Form_Form($action,$submit,$method); + + if (isset($entries)) + { + $this->form->setEntries($entries); + } + + $copy = $this->form->entry; + + foreach ($copy as $name => $entry) + { + if (strcmp($entry->type,'Select') === 0 and isset($entry->options)) + { + if (!is_array($entry->options)) + { + if (strstr($entry->options,'foreign::')) + { + $elements = explode('::',$entry->options); + + for ($i = 0; $i < count($elements); $i++) + { + if (strcmp($elements[$i],'--') === 0) $elements[$i] = null; + } + //send the query + array_shift($elements); + $resultSet = call_user_func_array(array($this->db,'select'),$elements); + + $single = true; + + if (strstr($elements[1],',')) + { + $args = explode(',',$elements[1]); + //add the table name + $args[0] = $elements[0].'.'.$args[0]; + $args[1] = $elements[0].'.'.$args[1]; + //associative array + $single = false; + } + else + { + $args[0] = $elements[0].'.'.$elements[1]; + $args[1] = null; + } + + $list = $this->getList($resultSet,$args[0],$args[1]); + + $this->form->entry[$name]->options = ($single) ? implode(',',array_values($list)) : $list; + } + } + } + } + + } + else + { + $this->form = new Form_Form($defAction,$defSubmit,$defMethod); + } + } + + //get a list from a result set + //$resultSet: the result set coming from a select query + public function getList($resultSet, $key, $value = null) + { + $list = array(); + + if (strstr($key,'.')) + { + $arr = explode('.',$key); + $keyTable = $arr[0]; + $keyField = $arr[1]; + } + else + { + $keyTable = $this->_tablesArray[0]; + $keyField = $key; + } + + if (!isset($value)) + { + foreach ($resultSet as $row) + { + $list[] = $row[$keyTable][$keyField]; + } + } + else + { + if (strstr($value,'.')) + { + $arr = explode('.',$value); + $valueTable = $arr[0]; + $valueField = $arr[1]; + } + else + { + $valueTable = $this->_tablesArray[0]; + $valueField = $value; + } + + foreach ($resultSet as $row) + { + $list[$row[$keyTable][$keyField]] = $row[$valueTable][$valueField]; + } + + } + return $list; + } + + // Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). + public function lastId() + { + return $this->db->lastId(); + } + + //send a free query + public function query($query) + { + return $this->db->query($query); + } + + //the text of the error message from previous MySQL operation + public function getError() + { + return $this->db->getError(); + } + + //the numerical value of the error message from previous MySQL operation + public function getErrno() + { + return $this->db->getErrno(); + } + + //define the abstract method to get the value of the record $id of the main table + abstract public function selectId($id); + + //define the abstract method to get the fields from the tables + abstract public function getFields(); + +} \ No newline at end of file diff --git a/h-source/Library/Model/Map.php b/h-source/Library/Model/Map.php new file mode 100755 index 0000000..7a36c6f --- /dev/null +++ b/h-source/Library/Model/Map.php @@ -0,0 +1,439 @@ +identifierName] + protected $_boxIdentifierValue = null; //the id of the box that has to be associated with the item + + public function __construct() + { + //add some submit names (method => form_submit_value) + $this->submitNames['associate'] = 'associateAction'; + $this->submitNames['dissociate'] = 'dissociateAction'; + //add the allowed methods + $this->_allowedDbMethods[] = 'associate'; + $this->_allowedDbMethods[] = 'dissociate'; + parent::__construct(); + } + + public function createMapWhere($choice) + { //create the where join clause + //$choice=(first,last,all) + if (isset($this->on)) + { + return $this->on; + } + else + { + $first = $this->_tablesArray[0].'.'.$this->_idFieldsArray[0].'='.$this->_tablesArray[2].'.'.$this->_idFieldsArray[0]; + $last = $this->_tablesArray[1].'.'.$this->_idFieldsArray[1].'='.$this->_tablesArray[2].'.'.$this->_idFieldsArray[1]; + switch ($choice) { + case 'first': + return $first; + break; + case 'last': + return $last; + break; + case 'all': + return $first. ' and '.$last; + break; + } + } + } + + //check if a join query is necessary or not + //$val: 0 or 1 (items or boxes) + //$whereClauseLevel: array containing the field=>value statements of the where clause. If $whereClause = null than $this->where is considered + public function checkIfJoinNeeded($val, $whereClauseLevel = null) + { + $whereClause = isset($whereClauseLevel) ? $whereClauseLevel : $this->where; + + foreach ($whereClause as $field => $value) + { + if (is_array($value)) + { + if ($this->checkIfJoinNeeded($val, $value) === true) return true; + } + else + { + if (strcmp($this->getTableName($field),$this->_tablesArray[$val]) !== 0) + { + if (strcmp($value,Params::$nullQueryValue) !== 0 or (Params::$nullQueryValue === false)) return true; + } + } + } + //return false if no where clause has been defined + return false; + } + + //method to create the where clause and the list of tables of the select query + public function mapQueryElements($val) + { +// $val = $element === 'Items' ? 0 : 1; + $tables = $this->_tablesArray[$val]; + $where = null; + $fields = $this->_tablesArray[$val].'.*'; + + if ($this->checkIfJoinNeeded($val)) + { + $tables = $this->_tables; + $fields = $this->_tablesArray[$val].'.*'; + $wherePlus = $this->createWhereClause(); + $wherePlus = isset($wherePlus) ? ' AND ' . $wherePlus : null; + $where = $this->createMapWhere('all') . $wherePlus; + } + else + { + $where = $this->createWhereClause(); + } + + return array('tables' => $tables,'where' => $where,'fields' => $fields); + } + + //$element: Items or Boxes. + //get all Item or Boxes + public function getAll($element = 'Items') + { + return $this->getFields('',$element); + } + + //method to get the values of the selected fields + //$fields: the fields that have to be excracted from the tableName + public function getFields($fields = '',$element = 'Items') + { + //get all Item or Boxes + if ((strcmp($element,'Items') !== 0) and (strcmp($element,'Boxes') !== 0)) + { + throw new Exception('"'.$element. '" argument not allowed in '.__METHOD__.' method'); + } + $val = $element === 'Items' ? 0 : 1; + + $elements = $this->mapQueryElements($val); + + $queryFields = (strcmp($fields,'') === 0) ? $elements['fields'] : $fields; + + return $row = $this->db->select($elements['tables'],$queryFields,$elements['where'],$this->groupBy,$this->orderBy,$this->limit); + + } + + public function send($element = 'Items') + { + $table = $this->getFields($this->select, $element); + + if ($this->toList) + { + $key = $this->listArray[0]; + $value = isset($this->listArray[1]) ? $this->listArray[1] : null; + $this->toList = false; + return $this->getList($table, $key, $value); + } + else + { + return $table; + } + } + + //the fields that have to be extracted from the table + public function getTable($fields = null) + { + return isset($fields) ? $this->getFields($fields) : $this->getAll(); + } + + //select the values of a specified record + //$id: the id (primary key) of the record + //$fields: the comma separated list of fields that have to be extracted + public function selectId($id,$fields = null) + { + $id = (int)$id; + $this->setWhereQueryClause(array($this->_idFieldsArray[0] => $id)); + + if (isset($fields)) + { + $values = $this->getFields($fields,'Items'); + } + else + { + $values = $this->getAll('Items'); + } + + return (count($values) > 0) ? $values[0][$this->_tablesArray[0]] : array(); + } + + //get the number of records (items or boxes) + public function recordNumber($element) + { + $val = $element === 'Items' ? 0 : 1; + + $elements = $this->mapQueryElements($val); + return $this->db->get_num_rows($elements['tables'],$elements['where'],$this->groupBy); + } + + //get the number of records (only items) + public function rowNumber() + { + return $this->recordNumber('Items'); + } + + public function getMax($field) + { + $elements = $this->mapQueryElements(0); + return $this->db->getMax($elements['tables'],$field,$elements['where'],$this->groupBy); + } + + public function getMin($field) + { + $elements = $this->mapQueryElements(0); + return $this->db->getMin($elements['tables'],$field,$elements['where'],$this->groupBy); + } + + public function getSum($field) + { + $elements = $this->mapQueryElements(0); + return $this->db->getSum($elements['tables'],$field,$elements['where'],$this->groupBy); + } + + public function getAvg($field) + { + $elements = $this->mapQueryElements(0); + return $this->db->getAvg($elements['tables'],$field,$elements['where'],$this->groupBy); + } + + //check if the table has the field $field equal to $value + public function has($field,$value) + { + $elements = $this->mapQueryElements(0); + return $this->db->recordExists($elements['tables'],$field,$value,$elements['where'],$this->groupBy); + } + + //associate an item with a box + //$idItem : name of the field of the Items table, $idGroup : name of the field of the Boxes table + public function associate($idItem = null,$idGroup = null) + { + $this->queryResult = false; + if (isset($idItem) and isset($idGroup)) + { + $idItem = (int)$idItem; + $idGroup = (int)$idGroup; + $values = array($idItem,$idGroup); //values relative to the fields $this->_idFields + $var = $this->checkAssociation($idItem,$idGroup); + if (!$var) + { + $result = $this->db->insert($this->_tablesArray[2],$this->_idFields,$values); + $this->setNotice($result); + return $result; + } + else + { + if (strcmp($this->printAssError,'yes') === 0) $this->notice = $this->_resultString->getString('linked'); + $this->result = false; + } + } + else + { + $this->notice = $this->_resultString->getString('no-id'); + $this->result = false; + } + return false; + } + + //associate an item with a box + //$idItem : name of the field of the Items table, $idGroup : name of the field of the Boxes table + public function dissociate($idItem = null,$idGroup = null) + { + $this->queryResult = false; + if (isset($idItem) and isset($idGroup)) + { + $idItem = (int)$idItem; + $idGroup = (int)$idGroup; + $var = $this->checkAssociation($idItem,$idGroup); + if ($var) + { + $result = $this->db->del($this->_tablesArray[2],$this->_idFieldsArray[0].'='.$idItem.' and '.$this->_idFieldsArray[1].'='.$idGroup); + $this->setNotice($result); + return $result; + } + else + { + if (strcmp($this->printAssError,'yes') === 0) $this->notice = $this->_resultString->getString('not-linked'); + $this->result = false; + } + } + else + { + $this->notice = $this->_resultString->getString('no-id'); + $this->result = false; + } + return false; + } + + public function checkAssociation($idItem,$idGroup) + { + $idItem = (int)$idItem; + $idGroup = (int)$idGroup; + $numRow = $this->db->get_num_rows($this->_tablesArray[2],$this->_idFieldsArray[0].'='.$idItem.' and '.$this->_idFieldsArray[1].'='.$idGroup); + if ($numRow === 1) + { + return true; + } + else + { + return false; + } + } + + //check what items are associate to a box + //itemsArray:array of items to check + public function checkAssociationDeep($itemsArray) + { + $associatedItems = array(); + $itemsArray = is_array($itemsArray) ? array_values($itemsArray) : array($itemsArray); + foreach ($itemsArray as $item) { + if ($this->db->recordExists($this->_tablesArray[2],$this->_idFieldsArray[0],$item)) + { + $associatedItems[] = $item; + } + } + return $associatedItems; + } + + //method to call the delete query (overriding of the del method of Model.php) + //check the referential integrity + public function del($id = null, $whereClause = null) + { + $this->queryResult = false; + + if (isset($whereClause)) + { + return parent::del(null,$whereClause); + } + else + { + if ($this->_onDelete === 'check') + { + if ($this->db->recordExists($this->_tablesArray[2],$this->_idFieldsArray[0],(int)$id)) + { + $this->notice = $this->_resultString->getString('associate'); + $this->identifierValue = null; + $this->result = false; + } + else + { + return parent::del((int)$id); + } + } + else if ($this->_onDelete === 'nocheck') + { + return parent::del((int)$id); + } + } + return false; + } + + //override of the updateTable method of the parent class + //method that calls the function indicated in $this->submitNames. Ex: if $_POST['delAction'] is found, then the "del" method is called. + public function updateTable($methodsList = '',$id = null) + { + $allowedMethodsArray = explode(',',$methodsList); + $resultArray = array(); + $this->identifierValue = null; + if (isset($id)) + { + $this->identifierValue = (int)$id; + } + else if (isset($_POST[$this->identifierName])) + { + $this->identifierValue = (int)$_POST[$this->identifierName]; + } + foreach ($this->submitNames as $methodName => $submitName) { + if (array_key_exists($submitName,$_POST)) + { + $this->submitName = $submitName; + if (method_exists($this,$methodName)) + { + if (in_array($methodName,$allowedMethodsArray)) + { + if ($this->checkConditions($methodName,$this->identifierValue)) + { + $this->notice = null; + $methodArray = array('associate','dissociate'); + if (in_array($methodName,$methodArray)) + { + $this->_boxIdentifierValue = null; + if (isset($_POST[$this->boxIdentifierName])) + { + $this->_boxIdentifierValue = (int)$_POST[$this->boxIdentifierName]; + } + call_user_func_array(array($this,$methodName),array($this->identifierValue,$this->_boxIdentifierValue)); + } + else + { + call_user_func_array(array($this,$methodName),array($this->identifierValue)); + } + } + } + } + else + { + throw new Exception('method "'.$methodName. '" not defined in class '.__CLASS__.'; error in method '.__METHOD__); + } + return; //only one cycle! + } + } + } + + //method to obtain one columns from the tables $this->_tablesArray as an associative array + //$valueField: the column that have to be extracted (array_values of the resulting associative array), $keyField: the column that have to play the role of array_keys + //$valueField = field:table, $keyField = field:table + public function getFieldArray($valueField,$keyField = null, $groupBy = null, $orderBy = null, $limit = null) + { + + $keyField = isset($keyField) ? $keyField : $valueField; + $valueFieldArray = explode(':',$valueField); + $keyFieldArray = explode(':',$keyField); + + $keyFieldTable = $keyFieldArray[0]; + $valueFieldTable = $valueFieldArray[0]; + + $keyFieldName = $keyFieldArray[1]; + $valueFieldName = $valueFieldArray[1]; + + $fields = implode('.',$keyFieldArray) . ',' . implode('.',$valueFieldArray); + + $temp = $this->where; //save the $this->where array + $this->where = array(); + + $val = array_search($keyFieldTable,$this->_tablesArray); + + if (strcmp($keyFieldTable,$valueFieldTable) !== 0) + { + throw new Exception("the tables '$valueFieldTable' and '$keyFieldTable' do not match in ".__METHOD__); + } + + if ($val === false or !in_array($val,array(0,1))) + { + throw new Exception("the table '$keyFieldTable' is not allowed in ".__METHOD__); + } + + $elements = $this->mapQueryElements($val); + + $table = $this->db->select($elements['tables'],$fields,$elements['where'],$groupBy,$orderBy,$limit); + $this->where = $temp; + + $returnArray = array(); + foreach ($table as $record) { + $returnArray[$record[$keyFieldTable][$keyFieldName]] = $record[$valueFieldTable][$valueFieldName]; + } + + return $returnArray; + + } + +} \ No newline at end of file diff --git a/h-source/Library/Model/Tree.php b/h-source/Library/Model/Tree.php new file mode 100755 index 0000000..d7b655d --- /dev/null +++ b/h-source/Library/Model/Tree.php @@ -0,0 +1,287 @@ +_tablesArray + public function createTreeWhere($index) { + if (isset($this->on)) + { + return $this->on; + } + else + { + $whereArray = array(); + for ($i = $index; $i < (count($this->_tablesArray)-1); $i++) + { + $whereArray[] = $this->_tablesArray[$i].'.'.$this->_idFieldsArray[$i+1].'='.$this->_tablesArray[$i+1].'.'.$this->_idFieldsArray[$i+1]; + } + $whereString = !empty($whereArray) ? implode(' and ',$whereArray) : null; + return $whereString; + } + } + + //create the list of tables of the select query + //$index: the index of $this->_tablesArray + public function createTablesList($index) { + if (isset($this->from)) + { + return $this->from; + } + else + { + $tablesString = null; + for ($i = $index; $i < (count($this->_tablesArray)-1); $i++) + { + $tablesString .= $this->_tablesArray[$i] . ','; + } + $tablesString .= $this->_tablesArray[count($this->_tablesArray)-1]; + return $tablesString; + } + } + + //method to create the list of fields of the select query + public function createFieldsList($index) { + $fieldsString = null; + for ($i = $index; $i < (count($this->_tablesArray)-1); $i++) + { + $fieldsString .= $this->_tablesArray[$i] . '.*,'; + } + $fieldsString .= $this->_tablesArray[count($this->_tablesArray)-1].'.*'; + return $fieldsString; + } + + + //method to create the where clause and the list of tables and fields of the select query + //$tableName: the table name ($this->_tablesArray) + //$choice:all->all the tables in $this->_arrayTables, other value->only the table of $this->_arrayTables ad index $index + //return: $elements = array('tables'=>$tables,'where'=>$where,'fields'=>$fields) + public function treeQueryElements($tableName,$choice = 'all') + { + $index = array_search($tableName,$this->_tablesArray); + $subArray = ($choice === 'all') ? array_slice($this->_tablesArray,$index) : array($tableName); //this array is necessary to verify that the where clause makes sense + $tables = ($choice === 'all') ? $this->createTablesList($index) : $tableName; + $where = ($choice === 'all') ? $this->createTreeWhere($index) : null; + $fields = ($choice === 'all') ? $this->createFieldsList($index) : $tableName.'.*'; + + $wherePlus = $this->createWhereClause(); + + if (!isset($this->on)) + { + $on = null; + + if (isset($where) and isset($wherePlus)) + { + $where .= ' AND ' . $wherePlus; + } + else if (!isset($where) and isset($wherePlus)) + { + $where .= $wherePlus; + } + } + else + { + $on = (strcmp($where,'-') !== 0) ? $where : null; + $where = $wherePlus; + } + + return array('tables' => $tables,'where' => $where,'fields'=>$fields,'on'=>$on); + } + + + //method to obtain the values of the whole tree + //$choice:all->all the tables in $this->_arrayTables, other value->only the table of $this->_arrayTables ad index $index + public function getAll($choice = 'all') { + return $this->getFields('',$choice); + } + + //method to get the values of the selected fields + //it walks the tree by means of a join query + //$fields: the fields that have to be excracted from the tableName + public function getFields($fields = '',$choice = 'all') + { + $elements = $this->treeQueryElements($this->_tablesArray[0],$choice); + + $queryFields = (strcmp($fields,'') === 0) ? $elements['fields'] : $fields; + + return $row = $this->db->select($elements['tables'],$queryFields,$elements['where'],$this->groupBy,$this->orderBy,$this->limit,$elements['on'],$this->using); + } + + public function send() + { + $table = $this->getFields($this->select); + + if ($this->toList) + { + $key = $this->listArray[0]; + $value = isset($this->listArray[1]) ? $this->listArray[1] : null; + $this->toList = false; + return $this->getList($table, $key, $value); + } + else + { + return $table; + } + } + + //call the getAll method with $tableName = $this->_tablesArray[0] + //the fields that have to be extracted from the table + public function getTable($fields = null) { + return isset($fields) ? $this->getFields($fields) : $this->getAll(); + } + + //select the values of a specified record + //$id: the id (primary key) of the record + //$fields: the comma separated list of fields that have to be extracted + public function selectId($id,$fields = null) { + $this->setWhereQueryClause(array($this->_idFieldsArray[0] => (int)$id)); + + $this->using = null; + + if (isset($fields)) + { + $values = $this->getFields($fields,'other'); + } + else + { + $values = $this->getAll('other'); + } + + return (count($values) > 0) ? $values[0][$this->_tablesArray[0]] : array(); + + } + + //get the number of records () + //the number of records of the table $tableName is returned + public function rowNumber() { + $elements = $this->treeQueryElements($this->_tablesArray[0]); + return $this->db->get_num_rows($elements['tables'],$elements['where'],$this->groupBy,$elements['on'],$this->using); + } + + public function getMax($field) + { + $elements = $this->treeQueryElements($this->_tablesArray[0]); + return $this->db->getMax($elements['tables'],$field,$elements['where'],$this->groupBy,$elements['on'],$this->using); + } + + public function getMin($field) + { + $elements = $this->treeQueryElements($this->_tablesArray[0]); + return $this->db->getMin($elements['tables'],$field,$elements['where'],$this->groupBy,$elements['on'],$this->using); + } + + public function getSum($field) + { + $elements = $this->treeQueryElements($this->_tablesArray[0]); + return $this->db->getSum($elements['tables'],$field,$elements['where'],$this->groupBy,$elements['on'],$this->using); + } + + public function getAvg($field) + { + $elements = $this->treeQueryElements($this->_tablesArray[0]); + return $this->db->getAvg($elements['tables'],$field,$elements['where'],$this->groupBy,$elements['on'],$this->using); + } + + //check if the table has the field $field equal to $value + public function has($field,$value) + { + $elements = $this->treeQueryElements($this->_tablesArray[0]); + return $this->db->recordExists($elements['tables'],$field,$value,$elements['where'],$this->groupBy,$elements['on'],$this->using); + } + +// //get the number of records of the table $this->_tablesArray[0] +// public function rowNumber() { +// return $this->recordNumber($this->_tablesArray[0]); +// } + + //method to call the delete query (overriding of the del method of Model.php) + //check the referential integrity + public function del($id = null, $whereClause = null) + { + $this->queryResult = false; + + if (isset($whereClause)) + { + return parent::del(null,$whereClause); + } + else + { + if ($this->_onDelete === 'check' and isset($this->_reference)) + { + if (isset($this->_reference[0]) and isset($this->_reference[1])) + { + if ($this->db->recordExists($this->_reference[0],$this->_reference[1],(int)$id)) + { + $this->notice = $this->_resultString->getString('associate'); + $this->identifierValue = null; + $this->result = false; + } + else + { + return parent::del((int)$id); + } + } + else + { + throw new Exception('you have forgotten to set \'$this->_reference\' or you have forgotten to set $this->_onDelete = \'nocheck\''); + } + } + else + { + return parent::del((int)$id); + } + } + return false; + } + + //method to obtain one columns from the tables $this->_tablesArray as an associative array + //$valueField: the column that have to be extracted (array_values of the resulting associative array), $keyField: the column that have to play the role of array_keys + public function getFieldArray($valueField,$keyField = null, $groupBy = null, $orderBy = null, $limit = null) { + + $keyField = isset($keyField) ? $keyField : $valueField; + $valueFieldArray = explode(':',$valueField); + $keyFieldArray = explode(':',$keyField); + + $keyFieldTable = $keyFieldArray[0]; + $valueFieldTable = $valueFieldArray[0]; + + $keyFieldName = $keyFieldArray[1]; + $valueFieldName = $valueFieldArray[1]; + + $fields = implode('.',$keyFieldArray) . ',' . implode('.',$valueFieldArray); + + $temp = $this->where; //save the $this->where array + $this->where = array(); + + if (strcmp($keyFieldTable,$valueFieldTable) !== 0) { + throw new Exception("the tables '$valueFieldTable' and '$keyFieldTable' do not match in ".__METHOD__); + } + + if (!in_array($keyFieldTable,$this->_tablesArray)) { + throw new Exception("the table '$keyFieldTable' is not allowed in ".__METHOD__); + } + + $elements = $this->treeQueryElements($keyFieldTable,''); + + $table = $this->db->select($elements['tables'],$fields,$elements['where'],$groupBy,$orderBy,$limit,$elements['on'],$this->using); + $this->where = $temp; + + $returnArray = array(); + foreach ($table as $record) { + $returnArray[$record[$keyFieldTable][$keyFieldName]] = $record[$valueFieldTable][$valueFieldName]; + } + + return $returnArray; + + } + +} \ No newline at end of file diff --git a/h-source/Library/Model/index.html b/h-source/Library/Model/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Model/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/Params.php b/h-source/Library/Params.php new file mode 100644 index 0000000..9ec0ba5 --- /dev/null +++ b/h-source/Library/Params.php @@ -0,0 +1,37 @@ +','!=','<=','>=','in(','not in('); + + //is the mbstring extension enabled? + public static $mbStringLoaded = false; + +} \ No newline at end of file diff --git a/h-source/Library/Popup.php b/h-source/Library/Popup.php new file mode 100755 index 0000000..55ea7f5 --- /dev/null +++ b/h-source/Library/Popup.php @@ -0,0 +1,15 @@ +'.__METHOD__.': function '.$func. ' does not exists'); + } + return isset($_GET[$name]) ? call_user_func($func,$_GET[$name]) : $default; + } + + public function post($name, $default = null, $func = 'none') + { + if (!function_exists($func)) + { + throw new Exception('Error in '.__METHOD__.': function '.$func. ' does not exists'); + } + return isset($_POST[$name]) ? call_user_func($func,$_POST[$name]) : $default; + } + + public function cookie($name, $default = null, $func = 'none') + { + if (!function_exists($func)) + { + throw new Exception('Error in '.__METHOD__.': function '.$func. ' does not exists'); + } + return isset($_COOKIE[$name]) ? call_user_func($func,$_COOKIE[$name]) : $default; + } + +} \ No newline at end of file diff --git a/h-source/Library/Scaffold.php b/h-source/Library/Scaffold.php new file mode 100755 index 0000000..2ac3fa5 --- /dev/null +++ b/h-source/Library/Scaffold.php @@ -0,0 +1,272 @@ +HTML,..) + + public $mainMenu = null; //the reference to the MenuHelper object + public $pageList = null; //the reference to the PageDivisionHelper object + public $itemList = null; //the reference to the ListHelper object + public $popupMenu = null; //the reference to the PopupHelper object + + public $form = null; //the reference to the form object + public $entries = null; //the entries of the form (string having entries separated by comma) + public $values = array(); //the values inserted in the form (taken from the table if $this->queryType === 'update' or if an error occured during the databse query, otherwise taken from the $_POST array) + + //the list of fields of the select query + public $fields = null; + + public function __construct($type,$controller,$model,$viewArgs,$params = null) { + + $this->_type = $type; + $this->_controller = $controller; + $this->model = $model; + $this->viewArgs = $viewArgs; + + $autoParams = array( + 'mainAction' => 'main', + 'modifyAction' => 'form/update', + 'associateAction' => 'associate', + 'panelController' => 'panel', + 'pageList' => true, + 'pageVariable' => 'page', + 'recordPerPage' => 10, + 'mainMenu' => 'panel,add', + 'formMenu' => 'panel,back', + 'postSubmitValue' => 'Save', + 'popup' => false, + 'popupType' => 'exclusive' + ); + + //set the $this->scaffold->params array + if (is_array($params)) { + foreach ($params as $key => $value) { + $autoParams[$key] = $value; + } + } + $this->params = $autoParams; + + } + + //ad some clauses to the select query + //whereArray = array ($table_field => $value) + public function appendWhereQueryClause($whereArray) + { + $this->model->appendWhereQueryClause($whereArray); + } + + //set clauses to the select query + //whereArray = array ($table_field => $value) + public function setWhereQueryClause($whereArray) + { + $this->model->setWhereQueryClause($whereArray); + } + + //initialize the main scaffold (ListHelper) + //$recordList: field of the table to show, $primaryKey: the key of the table + public function loadMain($recordList,$primaryKey,$theme = 'edit,del') + { + $this->_primaryKey = $primaryKey; + + $recordListArray = explode(',',$recordList); + foreach ($recordListArray as $record) { + $this->itemList->addItem("simpleText",";$record;"); + } + + $themeArray = explode(',',$theme); + + foreach ($themeArray as $el) + { + switch ($el) + { + case 'moveup': + $this->itemList->addItem('moveupForm',$this->_controller.'/'.$this->params['mainAction'],$primaryKey); + break; + case 'movedown': + $this->itemList->addItem('movedownForm',$this->_controller.'/'.$this->params['mainAction'],$primaryKey); + break; + case 'link': + $this->itemList->addItem('associateForm',$this->_controller.'/'.$this->params['associateAction'],$primaryKey); + break; + case 'edit': + $this->itemList->addItem('editForm',$this->_controller.'/'.$this->params['modifyAction'],$primaryKey); + break; + case 'del': + $this->itemList->addItem('delForm',$this->_controller.'/'.$this->params['mainAction'],$primaryKey); + break; + } + } + + } + + //initialize the form + //$queryType = insert/update + //$action: the action of the form (controller/action/queryString) + public function loadForm($queryType,$action) + { + $this->queryType = $queryType; + $submitName = $this->model->getSubmitName($queryType); + $value = $this->params['postSubmitValue']; + $viewStatus = Url::createUrl(array_values($this->viewArgs)); + $this->model->setForm($action.$viewStatus,array($submitName => $value),'POST'); + $this->form = $this->model->form; + } + + //function to obtain the values to use in the form + //$func = function to validate the values + //$id = the id of the record (used if $_POST[$this->m[$this->model]->identifierName] is not present) + public function getFormValues($func = 'sanitizeHtml',$id = null,$defaultValues = array(),$functionsIfFromDb = array()) + { + if ($this->_type === 'form') + { + $this->values = $this->model->getFormValues($this->queryType,$func,$id,$defaultValues,$functionsIfFromDb); + } + } + + //set the head of the table + //$columnsName: name of the columns. It has to be a comma-separated list of strings + public function setHead($columnsName) + { + $this->itemList->setHead($columnsName); + } + + //method to set the type of the entries of the form + //$entries: string containing the list of the entries where each entry is separated by comma: entry1,entry2,entry3 + //$entryType: associative array that describes the entries of the form. The key is the entry name while the value is the entry type (textarea,inputText,etc) + public function setFormEntries($entries = 'model',$entryType = array(),$optionsArray = array()) + { + if ($this->_type === 'form') + { + if ($entries === 'model') + { + $this->entries = $this->model->fields; + if ($this->queryType === 'update') + { + $this->entries .= ','. $this->model->identifierName; + } + } + else + { + $this->entries = null; + } + $entriesArray = explode(',',$this->entries); + if (isset($this->form)) + { + foreach ($entriesArray as $entry) + { + $type = isset($entryType[$entry]) ? $entryType[$entry] : 'InputText'; + $options = isset($optionsArray[$entry]) ? $optionsArray[$entry] : null; + $this->form->setEntry($entry,$type,$options); + } + if ($this->queryType === 'update') + { + $this->form->setEntry($this->model->identifierName,'Hidden'); + } + } + else + { + throw new Exception('form object has not been initialized. Call the scaffold->loadForm method before'); + } + } + } + + //add an item to the list of items + public function addItem($type, $action = '', $field = '', $name = '') { + if ($this->_type === 'main') { + $this->itemList->addItem($type, $action, $field, $name); + } + } + + //update the table + public function update($methodsList = '',$id = null) { + $this->model->updateTable($methodsList,$id); + } + + //method to create the HTML of the scaffold + //$values: the values to insert in the from entries + public function render($values = null,$subset = null) + { + + if ($this->_type === 'main') + { + + $recordNumber = $this->model->rowNumber(); + + if (isset($this->viewArgs[$this->params['pageVariable']])) + { + $page = $this->viewArgs[$this->params['pageVariable']]; + } + else + { + $this->params['pageList'] = false; + } + + $recordPerPage = $this->params['recordPerPage']; + + if ($this->params['pageList'] === true) + { + $this->model->limit = $this->pageList->getLimit($page,$recordNumber,$recordPerPage); + $this->html['pageList'] = $this->pageList->render((int)($page-2),5); + $position = array($page,$this->pageList->getNumbOfPages()); + } + else + { + $this->model->limit = null; + $this->html['pageList'] = null; + $position = array(1,1); + } + + $values = $this->model->getTable($this->fields); + + $primaryKey = $this->_primaryKey; + + //pass the variable position + $this->itemList->position = $position; + $this->html['main'] = $this->itemList->render($values); + + $this->html['menu'] = $this->mainMenu->render($this->params['mainMenu']); + + $popupHtml = null; + if ($this->params['popup'] === true) + { + $this->html['popup'] = $this->popupMenu->render(); + $popupHtml = "
\n".$this->html['popup']."\n
\n"; + } + + $this->html['all'] = "\n".$this->model->notice."\n $popupHtml \n
\n".$this->html['main']."\n
\n"."
\n
\n".$this->html['pageList']."
\n
\n\n"; + + } + else if ($this->_type === 'form') + { + + $subset = (!isset($subset)) ? $this->entries : $subset; + $values = (!isset($values)) ? $this->values : $values; + $this->html['menu'] = $this->mainMenu->render($this->params['formMenu']); + $this->html['main'] = $this->form->render($values,$subset); + $this->html['all'] = "\n".$this->model->notice."\n
\n".$this->html['main']."
\n"; + + } + + return $this->html['all']; + + } + +} \ No newline at end of file diff --git a/h-source/Library/Strings/Functions.php b/h-source/Library/Strings/Functions.php new file mode 100644 index 0000000..eabc0d8 --- /dev/null +++ b/h-source/Library/Strings/Functions.php @@ -0,0 +1,30 @@ +controller = $controller; + $this->baseUrl = MOD_REWRITE_MODULE === true ? 'http://' . DOMAIN_NAME : 'http://' . DOMAIN_NAME . '/index.php'; + $this->baseUrlSrc = 'http://' . DOMAIN_NAME; + } + + + public function set($values) + { + $this->_data = $values; + } + + public function append($values) + { + $this->_data = array_merge($this->_data,$values); + } + + //clean the $this->viewFiles array + public function clean() { + $this->_viewFiles = array(); + $this->_lastView = null; + } + + public function load($fileName,$option = 'none') { + if ((strcmp($option,'last') !== 0) and (strcmp($option,'none') !== 0)) { + throw new Exception('"'.$option. '" argument not allowed in '.__METHOD__.' method'); + } + if ($option === 'last') { + $this->_lastView = $fileName; + } else { + $this->_viewFiles[] = $fileName; + } + } + + + public function render() { + extract($this->_data); + + foreach ($this->_viewFiles as $file) { + if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Views' . DS . ucwords($this->controller) . DS . $file . '.php')) { + include (ROOT . DS . APPLICATION_PATH . DS . 'Views' . DS . ucwords($this->controller) . DS . $file . '.php'); + } else { + include (ROOT . DS . APPLICATION_PATH . DS . 'Views' . DS . $file . '.php'); + } + } + + if (isset($this->_lastView)) { + if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Views' . DS . ucwords($this->controller) . DS . $this->_lastView . '.php')) { + include (ROOT . DS . APPLICATION_PATH . DS . 'Views' . DS . ucwords($this->controller) . DS . $this->_lastView . '.php'); + } else { + include (ROOT . DS . APPLICATION_PATH . DS . 'Views' . DS . $this->_lastView . '.php'); + } + } + + } + +} diff --git a/h-source/Library/Url.php b/h-source/Library/Url.php new file mode 100755 index 0000000..4e2ca5e --- /dev/null +++ b/h-source/Library/Url.php @@ -0,0 +1,36 @@ +_params = $params; + + $this->_sessionsTable = $params['sessionsTable']; + $this->_usersTable = $params['usersTable']; + $this->_groupsTable = $params['groupsTable']; + $this->_manyToManyTable = $params['manyToManyTable']; + $this->_accessesTable = $params['accessesTable']; + $this->_login = Url::getRoot(null) . $params['users_controller'] . '/' . $params['users_login_action'] ; + $this->_main = Url::getRoot(null) . $params['panel_controller'] . '/' . $params['panel_main_action'] ; + $this->_retype = Url::getRoot(null) . $params['users_controller'] . '/' . $params['hijacking_action'] ; + $this->_db = Factory_Db::getInstance($params['database_type']); + } + + private function acquireCookie() { #obtain cookie + #cookie + $this->uid = NULL; + global $_COOKIE; + $this->uid = isset($_COOKIE[$this->_params['cookie_name']]) ? sanitizeAlnum($_COOKIE[$this->_params['cookie_name']]) : null; + } + + private function cleanSessions() + { + #cancello le sessioni scadute + $row = $this->_db->select($this->_sessionsTable,'creation_date',"uid='".$this->uid."'"); + if ($row) + { + if ($row[0][$this->_sessionsTable]['creation_date']) + { + if($row[0][$this->_sessionsTable]['creation_date'] + $this->_params['session_expire'] <= time()) + { + setcookie($this->_params['cookie_name'],'',time()-3600,$this->_params['cookie_path']); + } + } + } + $this->_db->del($this->_sessionsTable,"creation_date + " . $this->_params['session_expire'] . " <= ".time()); + } + + public function checkStatus() + { #controlla se l'utente è già loggato + $this->acquireCookie(); #ottengo il cookie + $this->cleanSessions(); #elimino le sessioni vecchie + $row=$this->_db->select($this->_usersTable.','.$this->_sessionsTable,$this->_usersTable.'.id_user,username,token,user_agent',$this->_usersTable.".id_user=".$this->_sessionsTable.".id_user and uid='".$this->uid."'"); + if (count($row) === 1 and $row !== false) + { + $this->status['user']=$row[0][$this->_usersTable]['username']; + $this->status['status']='logged'; + $this->status['id_user']=$row[0][$this->_usersTable]['id_user']; + $this->status['user_agent'] = $row[0][$this->_sessionsTable]['user_agent']; + $this->status['token'] = $row[0][$this->_sessionsTable]['token']; + $this->obtainGroups(); + } else { + $this->status['user']='sconosciuto'; + $this->status['status']='not-logged'; + $this->status['id_user']=''; + $this->status['user_agent']=''; + $this->status['token'] = ''; + $this->status['groups'] = array(); + } + } + + public function redirect($val,$time = 3) { #fa il redirect dell'utente + if ($val === 'logged') { + header('Refresh: '.$time.';url='.$this->_main); + if ($time !== 0) echo "You are already logged, ".$this->status['user'].".."; + } else if ($val === 'accepted') { + header('Refresh: '.$time.';url='.$this->_main); + if ($time !== 0) echo "Hi ".$this->status['user'].".."; + } else if ($val === 'login-error') { + header('Refresh: '.$time.';url='.$this->_login); + if ($time !== 0) echo "Wrong username or password..."; + } else if ($val === 'not-logged') { + header('Refresh: '.$time.';url='.$this->_login); + if ($time !== 0) echo "Limited access... sorry"; + } else if ($val === 'not-authorized') { + header('Refresh: '.$time.';url='.$this->_main); + if ($time !== 0) echo "Your account doesn't allow you to manage this page.. sorry!"; + } else if ($val === 'stolen') { + header('Refresh: '.$time.';url='.$this->_login); + if ($time !== 0) echo "Your session have been probably intercepted! Please login another time."; + } else if ($val === 'retype') { + header('Refresh: '.$time.';url='.$this->_retype); + if ($time !== 0) echo "Your session have been probably intercepted. Please type your password another time."; + } else if ($val === 'wait') { + header('Refresh: '.$time.';url='.$this->_login); + if ($time !== 0) echo "You have to wait ".$this->_params['time_after_failure']." seconds before you can try to login another time"; + } + exit; + } + + //obtain the group of the user + private function obtainGroups() + { + $tables = $this->_usersTable.','.$this->_groupsTable.','.$this->_manyToManyTable; + $fields = $this->_groupsTable.'.name'; + $where = $this->_usersTable.'.id_user='.$this->_manyToManyTable.'.id_user and '.$this->_groupsTable.'.id_group='.$this->_manyToManyTable.'.id_group and '.$this->_usersTable.'.id_user='.$this->status['id_user']; + $groups = $this->_db->select($tables,$fields,$where); + $this->status['groups'] = array(); + foreach ($groups as $group) + { + $this->status['groups'][] = $group[$this->_groupsTable]['name']; + } + } + + //$groups: string with name of groups separated by comma; ex: base,root,users + public function checkAccess($groups) + { + $groupsArray = explode (',',$groups); + foreach ($this->status['groups'] as $group) + { + if (in_array($group,$groupsArray)) return true; + } + return false; + } + + //check that the user is logged and, if present, check the group of the user (if loggeg) + //$groups: comma-separated list of groups whose users can access the page + //$time: time before the redirect is carried out + public function check($groups = null, $time = 3) + { + $this->checkStatus(); + if (strcmp($this->status['status'],'not-logged') === 0) + { + $this->redirect('not-logged',$time); + } + else if (strcmp($this->status['status'],'logged') === 0) + { + if ($this->_params['hijacking_check']) + { + if (!$this->checkHijacking()) + { + if ($this->_params['on_hijacking_event'] === 'forceout') + { + $this->logout(); + $this->redirect('stolen',$time); + } + else if ($this->_params['on_hijacking_event'] === 'redirect') + { + $this->redirect('retype',$time); + } + } + } +// $this->obtainGroups(); + if (isset($groups)) + { + $permission = $this->checkAccess($groups); + if (!$permission) $this->redirect('not-authorized',$time); + } + } + } + + //check if someone have stolen your uid + private function checkHijacking() + { + if (array_key_exists('user_agent',$this->status)) + { + if (strcmp($this->status['user_agent'],'') !== 0) + { + if (strcmp($this->status['user_agent'],getUserAgent()) === 0) + { + return true; + } + } + } + return false; + } + + //check CSRF + //$token: token to check + public function checkCSRF($token) + { + if (strcmp($this->status['token'],'') !== 0) + { + if (strcmp($this->status['token'],$token) === 0) + { + return true; + } + } + return false; + } + + //get an array containing all the users currently logged + public function getUsersLogged() + { + $usersLogged = array(); + $data=$this->_db->select($this->_usersTable.','.$this->_sessionsTable,'DISTINCT '.$this->_usersTable.'.username',$this->_usersTable.".id_user=".$this->_sessionsTable.".id_user"); + foreach ($data as $row) + { + $usersLogged[] = $row[$this->_usersTable]['username']; + } + return $usersLogged; + } + + //get the password of the current user + public function getPassword() + { + $row=$this->_db->select($this->_usersTable,'password',"id_user=".$this->status['id_user']); + if ($row !== false) + { + return $row[0][$this->_usersTable]['password']; + } + else + { + return false; + } + } + + private function checkPassword($user,$pwd) { #check username and password + + if (!in_array($this->_params['password_hash'],Params::$allowedHashFunc)) + { + throw new Exception('Error in '.__METHOD__.' : the hash func has to be '.implode(' or ',Params::$allowedHashFunc)); + } + //calculate the hash of the password + $pwd = call_user_func($this->_params['password_hash'],$pwd); + + $row=$this->_db->select($this->_usersTable,$this->_usersTable.'.id_user,username,password',"username=\"".$user."\" and password=\"".$pwd."\" and has_confirmed=0"); + if (count($row) === 1 and $row !== false) + { + $this->status['user'] = $row[0][$this->_usersTable]['username']; + $this->status['status'] = 'accepted'; + $this->status['id_user'] = $row[0][$this->_usersTable]['id_user']; + } + else + { + $this->status['user'] = 'unknown'; + $this->status['status'] = 'login-error'; + $this->status['id_user'] = ''; + if ($this->_db->recordExists($this->_usersTable,'username',$user)) + { + $this->_db->update($this->_usersTable,'last_failure',array(time()),'username="'.$user.'"'); + } + } + } + + //check that enough time is passed since the last failure of the user + private function checkLastFailure($user) + { + //current time + $now = time(); + //max time + $max = $now - $this->_params['time_after_failure']; + $data = $this->_db->select($this->_usersTable,'last_failure','username="'.$user.'"'); + if (count($data) === 1 and $data !== false) + { + if ($data[0][$this->_usersTable]['last_failure'] < $max) + { + return true; + } + return false; + } + else + { + return true; + } + } + + public function login($user,$pwd) + { + $user = sanitizeAll($user); + $this->checkStatus(); + //check if already logged + if ($this->status['status'] === 'logged') + { +// $this->redirect('logged'); + return 'logged'; + } + else + { + if ($this->checkLastFailure($user)) + { + $this->checkPassword($user,$pwd); + if ($this->status['status']==='accepted') + { + $this->uid = md5(randString(10).uniqid(mt_rand(),true)); + $this->_token = md5(randString(12)); + $userAgent = getUserAgent(); + $this->_db->insert($this->_sessionsTable,'id_user,uid,token,creation_date,user_agent',array($this->status['id_user'],$this->uid,$this->_token,time(),$userAgent)); + setcookie($this->_params['cookie_name'],$this->uid,0,$this->_params['cookie_path']); #magic cookie + $this->updateAccesses(); + + $this->_db->del($this->_sessionsTable,'id_user='.$this->status['id_user'].' AND uid != "'.$this->uid.'"'); + +// $this->redirect('accepted'); + return 'accepted'; + } + else if ($this->status['status']==='login-error') + { +// $this->redirect('login-error'); + return 'login-error'; + } + } + else + { +// $this->redirect('wait'); + return 'wait'; + } + } +// $this->redirect('login-error'); + return 'login-error'; + } + + private function updateAccesses() + { + $ip=getIp(); #ip + $date=date('d'). "-" . date('m') . "-" . date('Y'); #date + $ora=date('H') . ":" . date('i'); #time + $values=array($ip,$date,$ora,$this->status['user']); + $res=$this->_db->insert($this->_accessesTable,'ip,data,ora,username',$values); + } + + //force out an user + //$id: the id of the user + public function forceOut($id) + { + $id = (int)$id; + if ($this->_db->del($this->_sessionsTable,'id_user='.$id)) + { + return true; + } + return false; + } + + public function logout() + { + $this->checkStatus(); + if ($this->status['status'] === 'logged') + { + setcookie ($this->_params['cookie_name'], "", time() - 3600,$this->_params['cookie_path']); + if ($this->_db->del($this->_sessionsTable,'id_user='.$this->status['id_user'])) + { + return 'was-logged'; + } + else + { + return 'error'; + } + } + else + { + return 'not-logged'; + } + } + +} \ No newline at end of file diff --git a/h-source/Library/Users/index.html b/h-source/Library/Users/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/Users/index.html @@ -0,0 +1 @@ + diff --git a/h-source/Library/index.html b/h-source/Library/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/h-source/Library/index.html @@ -0,0 +1 @@ + -- cgit v1.2.3