From 07f5140771388c9e0c8a99b0dd2e5d950bdb173b Mon Sep 17 00:00:00 2001 From: Yuchen Pei Date: Thu, 14 Oct 2021 15:16:42 +1100 Subject: moving h-source subdir out. --- Library/Model/#Base.php# | 1273 ++++++++++++++++++++++++++++++++++++++++++++++ Library/Model/Base.php | 1273 ++++++++++++++++++++++++++++++++++++++++++++++ Library/Model/Map.php | 453 +++++++++++++++++ Library/Model/Tree.php | 307 +++++++++++ Library/Model/index.html | 1 + 5 files changed, 3307 insertions(+) create mode 100755 Library/Model/#Base.php# create mode 100755 Library/Model/Base.php create mode 100755 Library/Model/Map.php create mode 100755 Library/Model/Tree.php create mode 100644 Library/Model/index.html (limited to 'Library/Model') diff --git a/Library/Model/#Base.php# b/Library/Model/#Base.php# new file mode 100755 index 0000000..4162a56 --- /dev/null +++ b/Library/Model/#Base.php# @@ -0,0 +1,1273 @@ +. + +if (!defined('EG')) die('Direct access not allowed!'); + +abstract class Model_Base +{ + + public $fields = ''; //the fields that have to be manipulated by the update and insert query + public $values = array(); //the values that corresponding to the $this->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 = array(); //on array + public $using = array(); //using array + public $join = array(); //join array + + 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'); + + public $files = null; //reference to the Files_Upload class + + 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 = null; //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]; + + //set the language of notices + $this->_lang = Params::$language; + + //create the $_resultString object (result strings of the db queries) + $modelStringClass = 'Lang_'.$this->_lang.'_ModelStrings'; + if (!class_exists($modelStringClass)) + { + $modelStringClass = 'Lang_En_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_En_DbCondStrings'; + } + $this->_dbCondString = new $dbCondStringClass(); + + //instantiate the database class + $this->db = Factory_Db::getInstance(DATABASE_TYPE); + + //instantiate the Files_Upload class + $params = array( + 'filesPermission' => 0777, + 'language' => $this->_lang, + 'allowedExtensions' => 'png,jpg,jpeg,gif', + 'maxFileSize' => 20000000, + 'fileUploadKey' => 'userfile' + ); + + $this->files = new Files_Upload(ROOT."/media/",$params); + } + + //sanitize all the $values property + public function sanitize() + { + $keys = implode(',',array_keys($this->values)); + $this->values = $this->arrayExt->subset($this->values,$keys,'sanitizeDb'); + } + + //change a resulting string from a db query + public function setString($key,$value) + { + $this->_resultString->string[$key] = $value; + } + + //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, $operator = null) + { + $whereClause = null; + $whereClauseArray = array(); + + $whereClause = isset($whereClauseLevel) ? $whereClauseLevel : $this->where; + + foreach ($whereClause as $field => $value) + { + if (is_array($value)) + { + if (strstr($field,"OR")) + { + $op = " OR "; + } + else if (strstr($field,"AND")) + { + $op = " AND "; + } + else + { + $op = null; + } + $newValue = $this->createWhereClause($level+1, $value, $op); + 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 + if (isset($operator)) + { + $logicOper = $operator; + } + else + { + $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()) + { + @session_start(); + if (is_array($func)) + { + $funcPost = $func[0]; + $funcDb = $func[1]; + } + else + { + $funcPost = $func; + $funcDb = 'none'; + } + + $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); + + $values = $this->arrayExt->subset($recordArray,$this->fields,$funcDb); + +// 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 exist'); + } + + $values[$entry] = call_user_func($funcUponEntry,$values[$entry]); + } + } + + //set values of $_SESSION array + foreach ($values as $k => $v) + { + if (isset($this->formStruct['entries'][$k]['type'])) + { + if ($this->formStruct['entries'][$k]['type'] === 'File') + { + $_SESSION['form_'.$k] = $v; + } + } + } + } + } + else if ($queryType === 'insert') + { + + $tempArray = is_array($defaultValues) ? $defaultValues : array(); + + $values = $this->arrayExt->subset($tempArray,$this->fields,$funcPost); + + } + } + else + { + $values = $this->arrayExt->subset($_POST,$this->fields,$funcPost); + + if ($queryType === 'update') + { + $values[$idName] = $ident; + + //take values from $_SESSION array + $tempFieldArray = explode(',',$this->fields); + + for ($i = 0; $i < count($tempFieldArray); $i++) + { + if (isset($this->formStruct['entries'][$tempFieldArray[$i]]['type'])) + { + if ($this->formStruct['entries'][$tempFieldArray[$i]]['type'] === 'File') + { + if (isset($_SESSION['form_'.$tempFieldArray[$i]])) + { + $values[$tempFieldArray[$i]] = $_SESSION['form_'.$tempFieldArray[$i]]; + } + } + } + } + } + } + } + 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 exist'); + } + + $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; + $this->using[] = null; + return $this; + } + + //set the $using property and return the current object + public function using($using = null) + { + $this->using[] = $using; + $this->on[] = null; + return $this; + } + + //set the $join property and return the current object + public function left($string = null) + { + $this->join[] = "l:$string"; + return $this; + } + + //set the $join property and return the current object + public function right($string = null) + { + $this->join[] = "r:$string"; + return $this; + } + + //set the $join property and return the current object + public function inner($string = null) + { + $this->join[] = "i:$string"; + 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 = array(); + $this->using = array(); + $this->join = array(); + $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', $defEnctype = null) + { + 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; + $enctype = array_key_exists('enctype',$this->formStruct) ? $this->formStruct['enctype'] : $defEnctype; + + $this->form = new Form_Form($action,$submit,$method,$enctype); + + 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,$defEnctype); + } + } + + //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/Library/Model/Base.php b/Library/Model/Base.php new file mode 100755 index 0000000..4162a56 --- /dev/null +++ b/Library/Model/Base.php @@ -0,0 +1,1273 @@ +. + +if (!defined('EG')) die('Direct access not allowed!'); + +abstract class Model_Base +{ + + public $fields = ''; //the fields that have to be manipulated by the update and insert query + public $values = array(); //the values that corresponding to the $this->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 = array(); //on array + public $using = array(); //using array + public $join = array(); //join array + + 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'); + + public $files = null; //reference to the Files_Upload class + + 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 = null; //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]; + + //set the language of notices + $this->_lang = Params::$language; + + //create the $_resultString object (result strings of the db queries) + $modelStringClass = 'Lang_'.$this->_lang.'_ModelStrings'; + if (!class_exists($modelStringClass)) + { + $modelStringClass = 'Lang_En_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_En_DbCondStrings'; + } + $this->_dbCondString = new $dbCondStringClass(); + + //instantiate the database class + $this->db = Factory_Db::getInstance(DATABASE_TYPE); + + //instantiate the Files_Upload class + $params = array( + 'filesPermission' => 0777, + 'language' => $this->_lang, + 'allowedExtensions' => 'png,jpg,jpeg,gif', + 'maxFileSize' => 20000000, + 'fileUploadKey' => 'userfile' + ); + + $this->files = new Files_Upload(ROOT."/media/",$params); + } + + //sanitize all the $values property + public function sanitize() + { + $keys = implode(',',array_keys($this->values)); + $this->values = $this->arrayExt->subset($this->values,$keys,'sanitizeDb'); + } + + //change a resulting string from a db query + public function setString($key,$value) + { + $this->_resultString->string[$key] = $value; + } + + //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, $operator = null) + { + $whereClause = null; + $whereClauseArray = array(); + + $whereClause = isset($whereClauseLevel) ? $whereClauseLevel : $this->where; + + foreach ($whereClause as $field => $value) + { + if (is_array($value)) + { + if (strstr($field,"OR")) + { + $op = " OR "; + } + else if (strstr($field,"AND")) + { + $op = " AND "; + } + else + { + $op = null; + } + $newValue = $this->createWhereClause($level+1, $value, $op); + 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 + if (isset($operator)) + { + $logicOper = $operator; + } + else + { + $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()) + { + @session_start(); + if (is_array($func)) + { + $funcPost = $func[0]; + $funcDb = $func[1]; + } + else + { + $funcPost = $func; + $funcDb = 'none'; + } + + $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); + + $values = $this->arrayExt->subset($recordArray,$this->fields,$funcDb); + +// 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 exist'); + } + + $values[$entry] = call_user_func($funcUponEntry,$values[$entry]); + } + } + + //set values of $_SESSION array + foreach ($values as $k => $v) + { + if (isset($this->formStruct['entries'][$k]['type'])) + { + if ($this->formStruct['entries'][$k]['type'] === 'File') + { + $_SESSION['form_'.$k] = $v; + } + } + } + } + } + else if ($queryType === 'insert') + { + + $tempArray = is_array($defaultValues) ? $defaultValues : array(); + + $values = $this->arrayExt->subset($tempArray,$this->fields,$funcPost); + + } + } + else + { + $values = $this->arrayExt->subset($_POST,$this->fields,$funcPost); + + if ($queryType === 'update') + { + $values[$idName] = $ident; + + //take values from $_SESSION array + $tempFieldArray = explode(',',$this->fields); + + for ($i = 0; $i < count($tempFieldArray); $i++) + { + if (isset($this->formStruct['entries'][$tempFieldArray[$i]]['type'])) + { + if ($this->formStruct['entries'][$tempFieldArray[$i]]['type'] === 'File') + { + if (isset($_SESSION['form_'.$tempFieldArray[$i]])) + { + $values[$tempFieldArray[$i]] = $_SESSION['form_'.$tempFieldArray[$i]]; + } + } + } + } + } + } + } + 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 exist'); + } + + $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; + $this->using[] = null; + return $this; + } + + //set the $using property and return the current object + public function using($using = null) + { + $this->using[] = $using; + $this->on[] = null; + return $this; + } + + //set the $join property and return the current object + public function left($string = null) + { + $this->join[] = "l:$string"; + return $this; + } + + //set the $join property and return the current object + public function right($string = null) + { + $this->join[] = "r:$string"; + return $this; + } + + //set the $join property and return the current object + public function inner($string = null) + { + $this->join[] = "i:$string"; + 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 = array(); + $this->using = array(); + $this->join = array(); + $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', $defEnctype = null) + { + 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; + $enctype = array_key_exists('enctype',$this->formStruct) ? $this->formStruct['enctype'] : $defEnctype; + + $this->form = new Form_Form($action,$submit,$method,$enctype); + + 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,$defEnctype); + } + } + + //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/Library/Model/Map.php b/Library/Model/Map.php new file mode 100755 index 0000000..7a093e1 --- /dev/null +++ b/Library/Model/Map.php @@ -0,0 +1,453 @@ +. + +if (!defined('EG')) die('Direct access not allowed!'); + +class Model_Map extends Model_Base { + +// //many to many model + + public $printAssError = 'yes'; //'yes': print association error if the association/dissociation is already present. 'no': doen't print association error + public $boxIdentifierName = 'boxIdentifier';//key of the value of the $_POST array that represent the id of the Box that we want to associate with the Item having the id $_POST[$this->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) + $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; + + $tempWhere = $this->where; + $this->setWhereQueryClause(array($this->_idFieldsArray[0] => $id)); + + if (isset($fields)) + { + $values = $this->getFields($fields,'Items'); + } + else + { + $values = $this->getAll('Items'); + } + + $this->where = $tempWhere; + + 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/Library/Model/Tree.php b/Library/Model/Tree.php new file mode 100755 index 0000000..f7f95ea --- /dev/null +++ b/Library/Model/Tree.php @@ -0,0 +1,307 @@ +. + +if (!defined('EG')) die('Direct access not allowed!'); + +class Model_Tree extends Model_Base { + + public function __construct() { + parent::__construct(); + } + + //method to create the first part of where clause + //$index: the index of $this->_tablesArray + public function createTreeWhere($index) { + if (!empty($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 (empty($this->on)) + { + $on = array(); + + if (isset($where) and isset($wherePlus)) + { + $where .= ' AND ' . $wherePlus; + } + else if (!isset($where) and isset($wherePlus)) + { + $where .= $wherePlus; + } + } + else + { + $on = $where; + $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,$this->join); + } + + 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) { + $tempWhere = $this->where; + $this->setWhereQueryClause(array($this->_idFieldsArray[0] => (int)$id)); + + $this->using = null; + + if (isset($fields)) + { + $values = $this->getFields($fields,'other'); + } + else + { + $values = $this->getAll('other'); + } + + $this->where = $tempWhere; + + 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,$this->join); + } + + 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,$this->join); + } + + 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,$this->join); + } + + 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,$this->join); + } + + 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,$this->join); + } + + //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,$this->join); + } + +// //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/Library/Model/index.html b/Library/Model/index.html new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/Library/Model/index.html @@ -0,0 +1 @@ + -- cgit v1.2.3