123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851 |
- <?php
- // Copyright (C) 2010 Combodo SARL
- //
- // This program is free software; you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation; version 3 of the License.
- //
- // This program is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with this program; if not, write to the Free Software
- // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- /**
- * Typology for the attributes
- *
- * @author Erwan Taloc <erwan.taloc@combodo.com>
- * @author Romain Quetiez <romain.quetiez@combodo.com>
- * @author Denis Flaven <denis.flaven@combodo.com>
- * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
- */
- require_once('MyHelpers.class.inc.php');
- require_once('ormdocument.class.inc.php');
- /**
- * MissingColumnException - sent if an attribute is being created but the column is missing in the row
- *
- * @package iTopORM
- */
- class MissingColumnException extends Exception
- {}
- /**
- * add some description here...
- *
- * @package iTopORM
- */
- define('EXTKEY_RELATIVE', 1);
- /**
- * add some description here...
- *
- * @package iTopORM
- */
- define('EXTKEY_ABSOLUTE', 2);
- /**
- * Propagation of the deletion through an external key - ask the user to delete the referencing object
- *
- * @package iTopORM
- */
- define('DEL_MANUAL', 1);
- /**
- * Propagation of the deletion through an external key - ask the user to delete the referencing object
- *
- * @package iTopORM
- */
- define('DEL_AUTO', 2);
- /**
- * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
- *
- * @package iTopORM
- */
- abstract class AttributeDefinition
- {
- abstract public function GetType();
- abstract public function GetTypeDesc();
- abstract public function GetEditClass();
- protected $m_sCode;
- private $m_aParams = array();
- protected $m_sHostClass = '!undefined!';
- protected function Get($sParamName) {return $this->m_aParams[$sParamName];}
- protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
- protected function GetOptional($sParamName, $default)
- {
- if (array_key_exists($sParamName, $this->m_aParams))
- {
- return $this->m_aParams[$sParamName];
- }
- else
- {
- return $default;
- }
- }
-
- public function __construct($sCode, $aParams)
- {
- $this->m_sCode = $sCode;
- $this->m_aParams = $aParams;
- $this->ConsistencyCheck();
- }
- public function OverloadParams($aParams)
- {
- foreach ($aParams as $sParam => $value)
- {
- if (!array_key_exists($sParam, $this->m_aParams))
- {
- throw new CoreException("Unknown attribute definition parameter '$sParam', please select a value in {".implode(", ", array_keys($this->m_aParams))."}");
- }
- else
- {
- $this->m_aParams[$sParam] = $value;
- }
- }
- }
- public function SetHostClass($sHostClass)
- {
- $this->m_sHostClass = $sHostClass;
- }
- public function GetHostClass()
- {
- return $this->m_sHostClass;
- }
- // Note: I could factorize this code with the parameter management made for the AttributeDef class
- // to be overloaded
- static protected function ListExpectedParams()
- {
- return array();
- }
- private function ConsistencyCheck()
- {
- // Check that any mandatory param has been specified
- //
- $aExpectedParams = $this->ListExpectedParams();
- foreach($aExpectedParams as $sParamName)
- {
- if (!array_key_exists($sParamName, $this->m_aParams))
- {
- $aBacktrace = debug_backtrace();
- $sTargetClass = $aBacktrace[2]["class"];
- $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
- throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
- }
- }
- }
- // table, key field, name field
- public function ListDBJoins()
- {
- return "";
- // e.g: return array("Site", "infrid", "name");
- }
- public function IsDirectField() {return false;}
- public function IsScalar() {return false;}
- public function IsLinkSet() {return false;}
- public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
- public function IsExternalField() {return false;}
- public function IsWritable() {return false;}
- public function IsNullAllowed() {return true;}
- public function GetNullValue() {return null;}
- public function GetCode() {return $this->m_sCode;}
- public function GetLabel() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $this->m_sCode);}
- public function GetLabel_Obsolete()
- {
- // Written for compatibility with a data model written prior to version 0.9.1
- if (array_key_exists('label', $this->m_aParams))
- {
- return $this->m_aParams['label'];
- }
- else
- {
- return $this->GetLabel();
- }
- }
- public function GetDescription() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');}
- public function GetHelpOnEdition() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');}
- public function GetDescription_Obsolete()
- {
- // Written for compatibility with a data model written prior to version 0.9.1
- if (array_key_exists('description', $this->m_aParams))
- {
- return $this->m_aParams['description'];
- }
- else
- {
- return $this->GetDescription();
- }
- }
- public function GetValuesDef() {return null;}
- public function GetPrerequisiteAttributes() {return array();}
- public function MakeRealValue($proposedValue) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
- public function GetSQLExpressions() {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
- public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
- public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
- public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
- public function RequiresIndex() {return false;}
- public function GetValidationPattern()
- {
- return '';
- }
-
- public function CheckValue($value)
- {
- return true;
- }
-
- public function MakeValue()
- {
- $sComputeFunc = $this->Get("compute_func");
- if (empty($sComputeFunc)) return null;
- return call_user_func($sComputeFunc);
- }
-
- abstract public function GetDefaultValue();
- //
- // To be overloaded in subclasses
- //
-
- abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
- abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
- //abstract protected GetBasicFilterHTMLInput();
- abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
- public function GetFilterDefinitions()
- {
- return array();
- }
- public function GetEditValue($sValue)
- {
- return (string)$sValue;
- }
- public function GetAsHTML($sValue)
- {
- return Str::pure2html((string)$sValue);
- }
- public function GetAsXML($sValue)
- {
- return Str::pure2xml((string)$sValue);
- }
- public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
- {
- return (string)$sValue;
- }
- public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
- {
- $oValSetDef = $this->GetValuesDef();
- if (!$oValSetDef) return null;
- return $oValSetDef->GetValues($aArgs, $sBeginsWith);
- }
- }
- /**
- * Set of objects directly linked to an object, and being part of its definition
- *
- * @package iTopORM
- */
- class AttributeLinkedSet extends AttributeDefinition
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
- }
- public function GetType() {return "Array of objects";}
- public function GetTypeDesc() {return "Any kind of objects [subclass] of the same class";}
- public function GetEditClass() {return "List";}
- public function IsWritable() {return true;}
- public function IsLinkSet() {return true;}
- public function IsIndirect() {return false;}
- public function GetValuesDef() {return $this->Get("allowed_values");}
- public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
- public function GetDefaultValue($aArgs = array())
- {
- // Note: so far, this feature is a prototype,
- // later, the argument 'this' should always be present in the arguments
- //
- if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
- {
- $aValues = $this->Get('default_value')->GetValues($aArgs);
- $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
- return $oSet;
- }
- else
- {
- return DBObjectSet::FromScratch($this->Get('linked_class'));
- }
- }
- public function GetLinkedClass() {return $this->Get('linked_class');}
- public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
- public function GetBasicFilterOperators() {return array();}
- public function GetBasicFilterLooseOperator() {return '';}
- public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
- public function GetAsHTML($sValue)
- {
- return "ERROR: LIST OF OBJECTS";
- }
- public function GetAsXML($sValue)
- {
- return "ERROR: LIST OF OBJECTS";
- }
- public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
- {
- return "ERROR: LIST OF OBJECTS";
- }
- }
- /**
- * Set of objects linked to an object (n-n), and being part of its definition
- *
- * @package iTopORM
- */
- class AttributeLinkedSetIndirect extends AttributeLinkedSet
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
- }
- public function IsIndirect() {return true;}
- public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
- public function GetEditClass() {return "LinkedSet";}
- }
- /**
- * Abstract class implementing default filters for a DB column
- *
- * @package iTopORM
- */
- class AttributeDBFieldVoid extends AttributeDefinition
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
- }
- // To be overriden, used in GetSQLColumns
- protected function GetSQLCol() {return "VARCHAR(255)";}
- public function GetType() {return "Void";}
- public function GetTypeDesc() {return "Any kind of value, from the DB";}
- public function GetEditClass() {return "String";}
-
- public function GetValuesDef() {return $this->Get("allowed_values");}
- public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
- public function IsDirectField() {return true;}
- public function IsScalar() {return true;}
- public function IsWritable() {return true;}
- public function GetSQLExpr() {return $this->Get("sql");}
- public function GetDefaultValue() {return $this->MakeRealValue("");}
- public function IsNullAllowed() {return false;}
- //
- protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
- public function GetSQLExpressions()
- {
- $aColumns = array();
- // Note: to optimize things, the existence of the attribute is determine by the existence of one column with an empty suffix
- $aColumns[''] = $this->Get("sql");
- return $aColumns;
- }
- public function FromSQLToValue($aCols, $sPrefix = '')
- {
- $value = $this->MakeRealValue($aCols[$sPrefix.'']);
- return $value;
- }
- public function GetSQLValues($value)
- {
- $aValues = array();
- $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
- return $aValues;
- }
- public function GetSQLColumns()
- {
- $aColumns = array();
- $aColumns[$this->Get("sql")] = $this->GetSQLCol();
- return $aColumns;
- }
- public function GetFilterDefinitions()
- {
- return array($this->GetCode() => new FilterFromAttribute($this));
- }
- public function GetBasicFilterOperators()
- {
- return array("="=>"equals", "!="=>"differs from");
- }
- public function GetBasicFilterLooseOperator()
- {
- return "=";
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- $sQValue = CMDBSource::Quote($value);
- switch ($sOpCode)
- {
- case '!=':
- return $this->GetSQLExpr()." != $sQValue";
- break;
- case '=':
- default:
- return $this->GetSQLExpr()." = $sQValue";
- }
- }
- }
- /**
- * Base class for all kind of DB attributes, with the exception of external keys
- *
- * @package iTopORM
- */
- class AttributeDBField extends AttributeDBFieldVoid
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
- }
- public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"));}
- public function IsNullAllowed() {return $this->Get("is_null_allowed");}
- }
- /**
- * Map an integer column to an attribute
- *
- * @package iTopORM
- */
- class AttributeInteger extends AttributeDBField
- {
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- //return array_merge(parent::ListExpectedParams(), array());
- }
- public function GetType() {return "Integer";}
- public function GetTypeDesc() {return "Numeric value (could be negative)";}
- public function GetEditClass() {return "String";}
- protected function GetSQLCol() {return "INT(11)";}
-
- public function GetValidationPattern()
- {
- return "^[0-9]+$";
- }
- public function GetBasicFilterOperators()
- {
- return array(
- "!="=>"differs from",
- "="=>"equals",
- ">"=>"greater (strict) than",
- ">="=>"greater than",
- "<"=>"less (strict) than",
- "<="=>"less than",
- "in"=>"in"
- );
- }
- public function GetBasicFilterLooseOperator()
- {
- // Unless we implement an "equals approximately..." or "same order of magnitude"
- return "=";
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- $sQValue = CMDBSource::Quote($value);
- switch ($sOpCode)
- {
- case '!=':
- return $this->GetSQLExpr()." != $sQValue";
- break;
- case '>':
- return $this->GetSQLExpr()." > $sQValue";
- break;
- case '>=':
- return $this->GetSQLExpr()." >= $sQValue";
- break;
- case '<':
- return $this->GetSQLExpr()." < $sQValue";
- break;
- case '<=':
- return $this->GetSQLExpr()." <= $sQValue";
- break;
- case 'in':
- if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
- return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
- break;
- case '=':
- default:
- return $this->GetSQLExpr()." = \"$value\"";
- }
- }
- public function MakeRealValue($proposedValue)
- {
- //return intval($proposedValue); could work as well
- if ($proposedValue == '') return null;
- return (int)$proposedValue;
- }
- public function ScalarToSQL($value)
- {
- assert(is_numeric($value) || is_null($value));
- return $value; // supposed to be an int
- }
- }
- /**
- * Map a boolean column to an attribute
- *
- * @package iTopORM
- */
- class AttributeBoolean extends AttributeInteger
- {
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- //return array_merge(parent::ListExpectedParams(), array());
- }
- public function GetType() {return "Boolean";}
- public function GetTypeDesc() {return "Boolean";}
- public function GetEditClass() {return "Integer";}
- protected function GetSQLCol() {return "TINYINT(1)";}
-
- public function MakeRealValue($proposedValue)
- {
- if ((int)$proposedValue) return true;
- return false;
- }
- public function ScalarToSQL($value)
- {
- assert(is_bool($value));
- if ($value) return 1;
- return 0;
- }
- }
- /**
- * Map a varchar column (size < ?) to an attribute
- *
- * @package iTopORM
- */
- class AttributeString extends AttributeDBField
- {
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- //return array_merge(parent::ListExpectedParams(), array());
- }
- public function GetType() {return "String";}
- public function GetTypeDesc() {return "Alphanumeric string";}
- public function GetEditClass() {return "String";}
- protected function GetSQLCol() {return "VARCHAR(255)";}
- public function CheckValue($value)
- {
- $sRegExp = $this->GetValidationPattern();
- if (empty($sRegExp))
- {
- return true;
- }
- else
- {
- $sRegExp = str_replace('/', '\\/', $sRegExp);
- return preg_match("/$sRegExp/", $value);
- }
- }
- public function GetBasicFilterOperators()
- {
- return array(
- "="=>"equals",
- "!="=>"differs from",
- "Like"=>"equals (no case)",
- "NotLike"=>"differs from (no case)",
- "Contains"=>"contains",
- "Begins with"=>"begins with",
- "Finishes with"=>"finishes with"
- );
- }
- public function GetBasicFilterLooseOperator()
- {
- return "Contains";
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- $sQValue = CMDBSource::Quote($value);
- switch ($sOpCode)
- {
- case '=':
- case '!=':
- return $this->GetSQLExpr()." $sOpCode $sQValue";
- case 'Begins with':
- return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
- case 'Finishes with':
- return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
- case 'Contains':
- return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
- case 'NotLike':
- return $this->GetSQLExpr()." NOT LIKE $sQValue";
- case 'Like':
- default:
- return $this->GetSQLExpr()." LIKE $sQValue";
- }
- }
- public function MakeRealValue($proposedValue)
- {
- if (is_null($proposedValue)) return null;
- return (string)$proposedValue;
- // if (!settype($proposedValue, "string"))
- // {
- // throw new CoreException("Failed to change the type of '$proposedValue' to a string");
- // }
- }
- public function ScalarToSQL($value)
- {
- if (!is_string($value) && !is_null($value))
- {
- throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
- }
- return $value;
- }
- public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
- {
- $sFrom = array("\r\n", $sTextQualifier);
- $sTo = array("\n", $sTextQualifier.$sTextQualifier);
- $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
- return '"'.$sEscaped.'"';
- }
- }
- /**
- * An attibute that matches an object class
- *
- * @package iTopORM
- */
- class AttributeClass extends AttributeString
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
- }
- public function __construct($sCode, $aParams)
- {
- $this->m_sCode = $sCode;
- $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
- parent::__construct($sCode, $aParams);
- }
- public function GetAsHTML($sValue)
- {
- return MetaModel::GetName($sValue);
- }
- public function RequiresIndex()
- {
- return true;
- }
- }
- /**
- * An attibute that matches one of the language codes availables in the dictionnary
- *
- * @package iTopORM
- */
- class AttributeApplicationLanguage extends AttributeString
- {
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- }
- public function __construct($sCode, $aParams)
- {
- $this->m_sCode = $sCode;
- $aAvailableLanguages = Dict::GetLanguages();
- $aLanguageCodes = array();
- foreach($aAvailableLanguages as $sLangCode => $aInfo)
- {
- $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
- }
- $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
- parent::__construct($sCode, $aParams);
- }
- public function RequiresIndex()
- {
- return true;
- }
- }
- /**
- * The attribute dedicated to the finalclass automatic attribute
- *
- * @package iTopORM
- */
- class AttributeFinalClass extends AttributeString
- {
- public function __construct($sCode, $aParams)
- {
- $this->m_sCode = $sCode;
- $aParams["allowed_values"] = null;
- parent::__construct($sCode, $aParams);
- $this->m_sValue = $this->Get("default_value");
- }
- public function IsWritable()
- {
- return false;
- }
- public function RequiresIndex()
- {
- return true;
- }
- public function SetFixedValue($sValue)
- {
- $this->m_sValue = $sValue;
- }
- public function GetDefaultValue()
- {
- return $this->m_sValue;
- }
- public function GetAsHTML($sValue)
- {
- return MetaModel::GetName($sValue);
- }
- }
- /**
- * Map a varchar column (size < ?) to an attribute that must never be shown to the user
- *
- * @package iTopORM
- */
- class AttributePassword extends AttributeString
- {
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- //return array_merge(parent::ListExpectedParams(), array());
- }
- public function GetEditClass() {return "Password";}
- protected function GetSQLCol() {return "VARCHAR(64)";}
- public function GetFilterDefinitions()
- {
- // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
- // not allowed to search on passwords!
- return array();
- }
- public function GetAsHTML($sValue)
- {
- if (strlen($sValue) == 0)
- {
- return '';
- }
- else
- {
- return '******';
- }
- }
- }
- /**
- * Map a text column (size > ?) to an attribute
- *
- * @package iTopORM
- */
- class AttributeText extends AttributeString
- {
- public function GetType() {return "Text";}
- public function GetTypeDesc() {return "Multiline character string";}
- public function GetEditClass() {return "Text";}
- protected function GetSQLCol() {return "TEXT";}
- public function GetAsHTML($sValue)
- {
- return str_replace("\n", "<br>\n", parent::GetAsHTML($sValue));
- }
- public function GetAsXML($value)
- {
- return Str::pure2xml($value);
- }
- }
- /**
- * Specialization of a string: email
- *
- * @package iTopORM
- */
- class AttributeEmailAddress extends AttributeString
- {
- public function GetTypeDesc() {return "Email address(es)";}
- public function GetValidationPattern()
- {
- return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
- }
- }
- /**
- * Specialization of a string: IP address
- *
- * @package iTopORM
- */
- class AttributeIPAddress extends AttributeString
- {
- public function GetTypeDesc() {return "IP address";}
- public function GetValidationPattern()
- {
- $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
- return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
- }
- }
- /**
- * Specialization of a string: OQL expression
- *
- * @package iTopORM
- */
- class AttributeOQL extends AttributeString
- {
- public function GetTypeDesc() {return "OQL expression";}
- }
- /**
- * Specialization of a string: template
- *
- * @package iTopORM
- */
- class AttributeTemplateString extends AttributeString
- {
- public function GetTypeDesc() {return "Template string";}
- }
- /**
- * Specialization of a text: template
- *
- * @package iTopORM
- */
- class AttributeTemplateText extends AttributeText
- {
- public function GetTypeDesc() {return "Multiline template string";}
- }
- /**
- * Specialization of a text: wiki formatting
- *
- * @package iTopORM
- */
- class AttributeWikiText extends AttributeText
- {
- public function GetTypeDesc() {return "Multiline string with special formatting such as links to objects";}
- public function GetAsHTML($value)
- {
- // [SELECT xxxx.... [label]] => hyperlink to a result list
- // {SELECT xxxx.... [label]} => result list displayed inline
- // [myclass/nnn [label]] => hyperlink to an object
- // {myclass/nnn/attcode} => attribute displayed inline
- // etc.
- return parent::GetAsHTML($value);
- }
- }
- /**
- * Map a enum column to an attribute
- *
- * @package iTopORM
- */
- class AttributeEnum extends AttributeString
- {
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- //return array_merge(parent::ListExpectedParams(), array());
- }
- public function GetType() {return "Enum";}
- public function GetTypeDesc() {return "List of predefined alphanumeric strings";}
- public function GetEditClass() {return "String";}
- protected function GetSQLCol()
- {
- $oValDef = $this->GetValuesDef();
- if ($oValDef)
- {
- $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
- }
- else
- {
- $aValues = array();
- }
- if (count($aValues) > 0)
- {
- // The syntax used here do matters
- // In particular, I had to remove unnecessary spaces to
- // make sure that this string will match the field type returned by the DB
- // (used to perform a comparison between the current DB format and the data model)
- return "ENUM(".implode(",", $aValues).")";
- }
- else
- {
- return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
- }
- }
- public function RequiresIndex()
- {
- return false;
- }
- public function GetBasicFilterOperators()
- {
- return parent::GetBasicFilterOperators();
- }
- public function GetBasicFilterLooseOperator()
- {
- return parent::GetBasicFilterLooseOperator();
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- return parent::GetBasicFilterSQLExpr($sOpCode, $value);
- }
- public function GetAsHTML($sValue)
- {
- $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
- $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
- // later, we could imagine a detailed description in the title
- return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
- }
- public function GetEditValue($sValue)
- {
- $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
- return $sLabel;
- }
- public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
- {
- $aRawValues = parent::GetAllowedValues($aArgs, $sBeginsWith);
- if (is_null($aRawValues)) return null;
- $aLocalizedValues = array();
- foreach ($aRawValues as $sKey => $sValue)
- {
- $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
- }
- return $aLocalizedValues;
- }
- public function MakeRealValue($proposedValue)
- {
- // For an enum, let's consider an empty value like a null value
- // Could be implemented by changing the UI : no value => let the default value
- if ($proposedValue == '') return null;
- return parent::MakeRealValue($proposedValue);
- }
- }
- /**
- * Map a date+time column to an attribute
- *
- * @package iTopORM
- */
- class AttributeDateTime extends AttributeDBField
- {
- //const MYDATETIMEZONE = "UTC";
- const MYDATETIMEZONE = "Europe/Paris";
- static protected $const_TIMEZONE = null; // set once for all upon object construct
- static public function InitStatics()
- {
- // Init static constant once for all (remove when PHP allows real static const)
- self::$const_TIMEZONE = new DateTimeZone(self::MYDATETIMEZONE);
- // #@# Init default timezone -> do not get a notice... to be improved !!!
- // duplicated in the email test page (the mail function does trigger a notice as well)
- date_default_timezone_set(self::MYDATETIMEZONE);
- }
- static protected function GetDateFormat()
- {
- return "Y-m-d H:i:s";
- }
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- //return array_merge(parent::ListExpectedParams(), array());
- }
- public function GetType() {return "Date";}
- public function GetTypeDesc() {return "Date and time";}
- public function GetEditClass() {return "DateTime";}
- protected function GetSQLCol() {return "TIMESTAMP";}
- public static function GetAsUnixSeconds($value)
- {
- $oDeadlineDateTime = new DateTime($value, self::$const_TIMEZONE);
- $iUnixSeconds = $oDeadlineDateTime->format('U');
- return $iUnixSeconds;
-
- }
- // #@# THIS HAS TO REVISED
- // Having null not allowed was interpreted by mySQL
- // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
- // Then, on each update of the record, the field was modified.
- // We will have to specify the default value if we want to restore this option
- // In fact, we could also have more verbs dedicated to the DB:
- // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
- public function IsNullAllowed() {return true;}
- public function GetDefaultValue()
- {
- $default = parent::GetDefaultValue();
- if (!parent::IsNullAllowed())
- {
- if (empty($default))
- {
- $default = date(self::GetDateFormat());
- }
- }
- return $default;
- }
- // END OF THE WORKAROUND
- ///////////////////////////////////////////////////////////////
- public function GetValidationPattern()
- {
- return "^([0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30))))( (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])){0,1}|0000-00-00 00:00:00|0000-00-00$";
- }
- public function GetBasicFilterOperators()
- {
- return array(
- "="=>"equals",
- "!="=>"differs from",
- "<"=>"before",
- "<="=>"before",
- ">"=>"after (strictly)",
- ">="=>"after",
- "SameDay"=>"same day (strip time)",
- "SameMonth"=>"same year/month",
- "SameYear"=>"same year",
- "Today"=>"today",
- ">|"=>"after today + N days",
- "<|"=>"before today + N days",
- "=|"=>"equals today + N days",
- );
- }
- public function GetBasicFilterLooseOperator()
- {
- // Unless we implement a "same xxx, depending on given precision" !
- return "=";
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- $sQValue = CMDBSource::Quote($value);
- switch ($sOpCode)
- {
- case '=':
- case '!=':
- case '<':
- case '<=':
- case '>':
- case '>=':
- return $this->GetSQLExpr()." $sOpCode $sQValue";
- case 'SameDay':
- return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
- case 'SameMonth':
- return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
- case 'SameYear':
- return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
- case 'Today':
- return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
- case '>|':
- return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
- case '<|':
- return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
- case '=|':
- return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
- default:
- return $this->GetSQLExpr()." = $sQValue";
- }
- }
-
- public function MakeRealValue($proposedValue)
- {
- if (is_null($proposedValue))
- {
- return null;
- }
- if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
- {
- return null;
- }
- if (!is_numeric($proposedValue))
- {
- return $proposedValue;
- }
- return date(self::GetDateFormat(), $proposedValue);
- }
- public function ScalarToSQL($value)
- {
- if (is_null($value))
- {
- return null;
- }
- elseif (empty($value))
- {
- // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
- return '0000-00-00 00:00:00';
- }
- return $value;
- }
- public function GetAsHTML($value)
- {
- return Str::pure2html($value);
- }
- public function GetAsXML($value)
- {
- return Str::pure2xml($value);
- }
- public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
- {
- $sFrom = array("\r\n", $sTextQualifier);
- $sTo = array("\n", $sTextQualifier.$sTextQualifier);
- $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
- return '"'.$sEscaped.'"';
- }
- }
- /**
- * Map a date+time column to an attribute
- *
- * @package iTopORM
- */
- class AttributeDate extends AttributeDateTime
- {
- const MYDATEFORMAT = "Y-m-d";
- static protected function GetDateFormat()
- {
- return "Y-m-d";
- }
- static public function InitStatics()
- {
- // Nothing to do...
- }
- static protected function ListExpectedParams()
- {
- return parent::ListExpectedParams();
- //return array_merge(parent::ListExpectedParams(), array());
- }
- public function GetType() {return "Date";}
- public function GetTypeDesc() {return "Date";}
- public function GetEditClass() {return "Date";}
- protected function GetSQLCol() {return "DATE";}
- public function GetValidationPattern()
- {
- return "^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
- }
- }
- // Init static constant once for all (remove when PHP allows real static const)
- AttributeDate::InitStatics();
- /**
- * A dead line stored as a date & time
- * The only difference with the DateTime attribute is the display:
- * relative to the current time
- */
- class AttributeDeadline extends AttributeDateTime
- {
- public function GetAsHTML($value)
- {
- $sResult = '';
- if ($value !== null)
- {
- $value = AttributeDateTime::GetAsUnixSeconds($value);
- $difference = $value - time();
-
- if ($difference >= 0)
- {
- $sResult = self::FormatDuration($difference);
- }
- else
- {
- $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
- }
- }
- return $sResult;
- }
- static function FormatDuration($duration)
- {
- $days = floor($duration / 86400);
- $hours = floor(($duration - (86400*$days)) / 3600);
- $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
- $sResult = '';
-
- if ($duration < 60)
- {
- // Less than 1 min
- $sResult =Dict::S('UI:Deadline_LessThan1Min');
- }
- else if ($duration < 3600)
- {
- // less than 1 hour, display it in minutes
- $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
- }
- else if ($duration < 86400)
- {
- // Less that 1 day, display it in hours/minutes
- $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
- }
- else
- {
- // Less that 1 day, display it in hours/minutes
- $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
- }
- return $sResult;
- }
- }
- // Init static constant once for all (remove when PHP allows real static const)
- AttributeDateTime::InitStatics();
- /**
- * Map a foreign key to an attribute
- * AttributeExternalKey and AttributeExternalField may be an external key
- * the difference is that AttributeExternalKey corresponds to a column into the defined table
- * where an AttributeExternalField corresponds to a column into another table (class)
- *
- * @package iTopORM
- */
- class AttributeExternalKey extends AttributeDBFieldVoid
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
- }
- public function GetType() {return "Extkey";}
- public function GetTypeDesc() {return "Link to another object";}
- public function GetEditClass() {return "ExtKey";}
- protected function GetSQLCol() {return "INT(11)";}
- public function RequiresIndex()
- {
- return true;
- }
- public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
- public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
- public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
- public function GetKeyAttCode() {return $this->GetCode();}
-
- public function GetDefaultValue() {return 0;}
- public function IsNullAllowed() {return $this->Get("is_null_allowed");}
- public function GetNullValue() {return 0;}
- public function GetBasicFilterOperators()
- {
- return parent::GetBasicFilterOperators();
- }
- public function GetBasicFilterLooseOperator()
- {
- return parent::GetBasicFilterLooseOperator();
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- return parent::GetBasicFilterSQLExpr($sOpCode, $value);
- }
- // overloaded here so that an ext key always have the answer to
- // "what are your possible values?"
- public function GetValuesDef()
- {
- $oValSetDef = $this->Get("allowed_values");
- if (!$oValSetDef)
- {
- // Let's propose every existing value
- $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
- }
- return $oValSetDef;
- }
- public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
- {
- try
- {
- return parent::GetAllowedValues($aArgs, $sBeginsWith);
- }
- catch (MissingQueryArgument $e)
- {
- // Some required arguments could not be found, enlarge to any existing value
- $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
- return $oValSetDef->GetValues($aArgs, $sBeginsWith);
- }
- }
- public function GetDeletionPropagationOption()
- {
- return $this->Get("on_target_delete");
- }
- public function MakeRealValue($proposedValue)
- {
- return (int)$proposedValue;
- }
- }
- /**
- * An attribute which corresponds to an external key (direct or indirect)
- *
- * @package iTopORM
- */
- class AttributeExternalField extends AttributeDefinition
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
- }
- public function GetType() {return "ExtkeyField";}
- public function GetTypeDesc() {return "Field of an object pointed to by the current object";}
- public function GetEditClass() {return "ExtField";}
- protected function GetSQLCol()
- {
- // throw new CoreException("external attribute: does it make any sense to request its type ?");
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetSQLCol();
- }
- public function GetLabel()
- {
- $oRemoteAtt = $this->GetExtAttDef();
- $sDefault = $oRemoteAtt->GetLabel();
- return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
- }
- public function GetDescription()
- {
- $oRemoteAtt = $this->GetExtAttDef();
- $sDefault = $oRemoteAtt->GetDescription();
- return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
- }
- public function GetHelpOnEdition()
- {
- $oRemoteAtt = $this->GetExtAttDef();
- $sDefault = $oRemoteAtt->GetHelpOnEdition();
- return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
- }
- public function IsExternalKey($iType = EXTKEY_RELATIVE)
- {
- switch($iType)
- {
- case EXTKEY_ABSOLUTE:
- // see further
- $oRemoteAtt = $this->GetExtAttDef();
- return $oRemoteAtt->IsExternalKey($iType);
- case EXTKEY_RELATIVE:
- return false;
- default:
- throw new CoreException("Unexpected value for argument iType: '$iType'");
- }
- }
- public function GetTargetClass($iType = EXTKEY_RELATIVE)
- {
- return $this->GetKeyAttDef($iType)->GetTargetClass();
- }
- public function IsExternalField() {return true;}
- public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
- public function GetExtAttCode() {return $this->Get("target_attcode");}
- public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
- {
- switch($iType)
- {
- case EXTKEY_ABSOLUTE:
- // see further
- $oRemoteAtt = $this->GetExtAttDef();
- if ($oRemoteAtt->IsExternalField())
- {
- return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
- }
- else if ($oRemoteAtt->IsExternalKey())
- {
- return $oRemoteAtt;
- }
- return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
- case EXTKEY_RELATIVE:
- return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
- default:
- throw new CoreException("Unexpected value for argument iType: '$iType'");
- }
- }
- public function GetExtAttDef()
- {
- $oKeyAttDef = $this->GetKeyAttDef();
- $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
- if (!is_object($oExtAttDef)) throw new CoreException("Invalid external field ".$this->GetCode()." in class ".$this->GetHostClass().". The class ".$oKeyAttDef->Get("targetclass")." has no attribute ".$this->Get("target_attcode"));
- return $oExtAttDef;
- }
- public function GetSQLExpr()
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetSQLExpr();
- }
- public function GetDefaultValue()
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetDefaultValue();
- }
- public function IsNullAllowed()
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->IsNullAllowed();
- }
- public function IsScalar()
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->IsScalar();
- }
- public function GetFilterDefinitions()
- {
- return array($this->GetCode() => new FilterFromAttribute($this));
- }
- public function GetBasicFilterOperators()
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetBasicFilterOperators();
- }
- public function GetBasicFilterLooseOperator()
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetBasicFilterLooseOperator();
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
- }
- public function MakeRealValue($proposedValue)
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->MakeRealValue($proposedValue);
- }
- public function ScalarToSQL($value)
- {
- // This one could be used in case of filtering only
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->ScalarToSQL($value);
- }
- // Do not overload GetSQLExpression here because this is handled in the joins
- //public function GetSQLExpressions() {return array();}
- // Here, we get the data...
- public function FromSQLToValue($aCols, $sPrefix = '')
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
- }
- public function GetAsHTML($value)
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetAsHTML($value);
- }
- public function GetAsXML($value)
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetAsXML($value);
- }
- public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"')
- {
- $oExtAttDef = $this->GetExtAttDef();
- return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
- }
- }
- /**
- * Map a varchar column to an URL (formats the ouput in HMTL)
- *
- * @package iTopORM
- */
- class AttributeURL extends AttributeString
- {
- static protected function ListExpectedParams()
- {
- //return parent::ListExpectedParams();
- return array_merge(parent::ListExpectedParams(), array("target"));
- }
- public function GetType() {return "Url";}
- public function GetTypeDesc() {return "Absolute or relative URL as a text string";}
- public function GetEditClass() {return "String";}
- public function GetAsHTML($sValue)
- {
- $sTarget = $this->Get("target");
- if (empty($sTarget)) $sTarget = "_blank";
- $sLabel = Str::pure2html($sValue);
- if (strlen($sLabel) > 40)
- {
- // Truncate the length to about 40 characters, by removing the middle
- $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
- }
- return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
- }
- public function GetValidationPattern()
- {
- return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$";
- }
- }
- /**
- * A blob is an ormDocument, it is stored as several columns in the database
- *
- * @package iTopORM
- */
- class AttributeBlob extends AttributeDefinition
- {
- static protected function ListExpectedParams()
- {
- return array_merge(parent::ListExpectedParams(), array("depends_on"));
- }
- public function GetType() {return "Blob";}
- public function GetTypeDesc() {return "Document";}
- public function GetEditClass() {return "Document";}
-
- public function IsDirectField() {return true;}
- public function IsScalar() {return true;}
- public function IsWritable() {return true;}
- public function GetDefaultValue() {return "";}
- public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
- // Facilitate things: allow the user to Set the value from a string
- public function MakeRealValue($proposedValue)
- {
- if (!is_object($proposedValue))
- {
- return new ormDocument($proposedValue, 'text/plain');
- }
- return $proposedValue;
- }
- public function GetSQLExpressions()
- {
- $aColumns = array();
- // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
- $aColumns[''] = $this->GetCode().'_mimetype';
- $aColumns['_data'] = $this->GetCode().'_data';
- $aColumns['_filename'] = $this->GetCode().'_filename';
- return $aColumns;
- }
- public function FromSQLToValue($aCols, $sPrefix = '')
- {
- if (!isset($aCols[$sPrefix]))
- {
- $sAvailable = implode(', ', array_keys($aCols));
- throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
- }
- $sMimeType = $aCols[$sPrefix];
- if (!isset($aCols[$sPrefix.'_data']))
- {
- $sAvailable = implode(', ', array_keys($aCols));
- throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
- }
- $data = $aCols[$sPrefix.'_data'];
- if (!isset($aCols[$sPrefix.'_filename']))
- {
- $sAvailable = implode(', ', array_keys($aCols));
- throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
- }
- $sFileName = $aCols[$sPrefix.'_filename'];
- $value = new ormDocument($data, $sMimeType, $sFileName);
- return $value;
- }
- public function GetSQLValues($value)
- {
- // #@# Optimization: do not load blobs anytime
- // As per mySQL doc, selecting blob columns will prevent mySQL from
- // using memory in case a temporary table has to be created
- // (temporary tables created on disk)
- // We will have to remove the blobs from the list of attributes when doing the select
- // then the use of Get() should finalize the load
- if ($value instanceOf ormDocument)
- {
- $aValues = array();
- $aValues[$this->GetCode().'_data'] = $value->GetData();
- $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
- $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
- }
- else
- {
- $aValues = array();
- $aValues[$this->GetCode().'_data'] = '';
- $aValues[$this->GetCode().'_mimetype'] = '';
- $aValues[$this->GetCode().'_filename'] = '';
- }
- return $aValues;
- }
- public function GetSQLColumns()
- {
- $aColumns = array();
- $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
- $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
- $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
- return $aColumns;
- }
- public function GetFilterDefinitions()
- {
- return array();
- // still not working... see later...
- return array(
- $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
- $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
- $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
- );
- }
- public function GetBasicFilterOperators()
- {
- return array();
- }
- public function GetBasicFilterLooseOperator()
- {
- return '=';
- }
- public function GetBasicFilterSQLExpr($sOpCode, $value)
- {
- return 'true';
- }
- public function GetAsHTML($value)
- {
- if (is_object($value))
- {
- return $value->GetAsHTML();
- }
- }
- public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
- {
- return ''; // Not exportable in CSV !
- }
-
- public function GetAsXML($value)
- {
- return ''; // Not exportable in XML, or as CDATA + some subtags ??
- }
- }
- // Indexed array having two dimensions
- class AttributeTable extends AttributeText
- {
- public function GetType() {return "Table";}
- public function GetTypeDesc() {return "Array with 2 dimensions";}
- public function GetEditClass() {return "Text";}
- protected function GetSQLCol() {return "TEXT";}
- // Facilitate things: allow the user to Set the value from a string
- public function MakeRealValue($proposedValue)
- {
- if (!is_array($proposedValue))
- {
- return array(0 => array(0 => $proposedValue));
- }
- return $proposedValue;
- }
- public function FromSQLToValue($aCols, $sPrefix = '')
- {
- try
- {
- $value = @unserialize($aCols[$sPrefix.'']);
- if ($value === false)
- {
- $value = $this->MakeRealValue($aCols[$sPrefix.'']);
- }
- }
- catch(Exception $e)
- {
- $value = $this->MakeRealValue($aCols[$sPrefix.'']);
- }
- return $value;
- }
- public function GetSQLValues($value)
- {
- $aValues = array();
- $aValues[$this->Get("sql")] = serialize($value);
- return $aValues;
- }
- public function GetAsHTML($value)
- {
- if (!is_array($value))
- {
- throw new CoreException('Expecting an array', array('found' => get_class($value)));
- }
- if (count($value) == 0)
- {
- return "";
- }
- $sRes = "<TABLE class=\"listResults\">";
- $sRes .= "<TBODY>";
- foreach($value as $iRow => $aRawData)
- {
- $sRes .= "<TR>";
- foreach ($aRawData as $iCol => $cell)
- {
- $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
- $sRes .= "<TD>$sCell</TD>";
- }
- $sRes .= "</TR>";
- }
- $sRes .= "</TBODY>";
- $sRes .= "</TABLE>";
- return $sRes;
- }
- }
- // The PHP value is a hash array, it is stored as a TEXT column
- class AttributePropertySet extends AttributeTable
- {
- public function GetType() {return "PropertySet";}
- public function GetTypeDesc() {return "List of properties (name and value)";}
- public function GetEditClass() {return "Text";}
- protected function GetSQLCol() {return "TEXT";}
- // Facilitate things: allow the user to Set the value from a string
- public function MakeRealValue($proposedValue)
- {
- if (!is_array($proposedValue))
- {
- return array('?' => (string)$proposedValue);
- }
- return $proposedValue;
- }
- public function GetAsHTML($value)
- {
- if (!is_array($value))
- {
- throw new CoreException('Expecting an array', array('found' => get_class($value)));
- }
- if (count($value) == 0)
- {
- return "";
- }
- $sRes = "<TABLE class=\"listResults\">";
- $sRes .= "<TBODY>";
- foreach($value as $sProperty => $sValue)
- {
- $sRes .= "<TR>";
- $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
- $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
- $sRes .= "</TR>";
- }
- $sRes .= "</TBODY>";
- $sRes .= "</TABLE>";
- return $sRes;
- }
- }
- ?>
|