attributedef.class.inc.php 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Typology for the attributes
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once('ormdocument.class.inc.php');
  26. require_once('ormpassword.class.inc.php');
  27. require_once('ormcaselog.class.inc.php');
  28. /**
  29. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  30. *
  31. * @package iTopORM
  32. */
  33. class MissingColumnException extends Exception
  34. {}
  35. /**
  36. * add some description here...
  37. *
  38. * @package iTopORM
  39. */
  40. define('EXTKEY_RELATIVE', 1);
  41. /**
  42. * add some description here...
  43. *
  44. * @package iTopORM
  45. */
  46. define('EXTKEY_ABSOLUTE', 2);
  47. /**
  48. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  49. *
  50. * @package iTopORM
  51. */
  52. define('DEL_MANUAL', 1);
  53. /**
  54. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  55. *
  56. * @package iTopORM
  57. */
  58. define('DEL_AUTO', 2);
  59. /**
  60. * Fully silent delete... not yet implemented
  61. */
  62. define('DEL_SILENT', 2);
  63. /**
  64. * For HierarchicalKeys only: move all the children up one level automatically
  65. */
  66. define('DEL_MOVEUP', 3);
  67. /**
  68. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  69. *
  70. * @package iTopORM
  71. */
  72. abstract class AttributeDefinition
  73. {
  74. public function GetType()
  75. {
  76. return Dict::S('Core:'.get_class($this));
  77. }
  78. public function GetTypeDesc()
  79. {
  80. return Dict::S('Core:'.get_class($this).'+');
  81. }
  82. abstract public function GetEditClass();
  83. protected $m_sCode;
  84. private $m_aParams = array();
  85. protected $m_sHostClass = '!undefined!';
  86. protected function Get($sParamName) {return $this->m_aParams[$sParamName];}
  87. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  88. protected function GetOptional($sParamName, $default)
  89. {
  90. if (array_key_exists($sParamName, $this->m_aParams))
  91. {
  92. return $this->m_aParams[$sParamName];
  93. }
  94. else
  95. {
  96. return $default;
  97. }
  98. }
  99. public function __construct($sCode, $aParams)
  100. {
  101. $this->m_sCode = $sCode;
  102. $this->m_aParams = $aParams;
  103. $this->ConsistencyCheck();
  104. }
  105. public function GetParams()
  106. {
  107. return $this->m_aParams;
  108. }
  109. public function SetHostClass($sHostClass)
  110. {
  111. $this->m_sHostClass = $sHostClass;
  112. }
  113. public function GetHostClass()
  114. {
  115. return $this->m_sHostClass;
  116. }
  117. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  118. // to be overloaded
  119. static protected function ListExpectedParams()
  120. {
  121. return array();
  122. }
  123. private function ConsistencyCheck()
  124. {
  125. // Check that any mandatory param has been specified
  126. //
  127. $aExpectedParams = $this->ListExpectedParams();
  128. foreach($aExpectedParams as $sParamName)
  129. {
  130. if (!array_key_exists($sParamName, $this->m_aParams))
  131. {
  132. $aBacktrace = debug_backtrace();
  133. $sTargetClass = $aBacktrace[2]["class"];
  134. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  135. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  136. }
  137. }
  138. }
  139. // table, key field, name field
  140. public function ListDBJoins()
  141. {
  142. return "";
  143. // e.g: return array("Site", "infrid", "name");
  144. }
  145. public function GetFinalAttDef()
  146. {
  147. return $this;
  148. }
  149. public function IsDirectField() {return false;}
  150. public function IsScalar() {return false;}
  151. public function IsLinkSet() {return false;}
  152. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  153. public function IsHierarchicalKey() {return false;}
  154. public function IsExternalField() {return false;}
  155. public function IsWritable() {return false;}
  156. public function IsNullAllowed() {return true;}
  157. public function GetCode() {return $this->m_sCode;}
  158. public function GetLabel($sDefault = null)
  159. {
  160. // If no default value is specified, let's define the most relevant one for developping purposes
  161. if (is_null($sDefault))
  162. {
  163. $sDefault = $this->m_sCode;
  164. }
  165. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, '');
  166. if (strlen($sLabel) == 0)
  167. {
  168. // Nothing found: go higher in the hierarchy (if possible)
  169. //
  170. $sLabel = $sDefault;
  171. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  172. if ($sParentClass)
  173. {
  174. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  175. {
  176. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  177. $sLabel = $oAttDef->GetLabel($sDefault);
  178. }
  179. }
  180. }
  181. return $sLabel;
  182. }
  183. /**
  184. * Get the label corresponding to the given value
  185. * To be overloaded for localized enums
  186. */
  187. public function GetValueLabel($sValue)
  188. {
  189. return GetAsHTML($sValue);
  190. }
  191. public function GetLabel_Obsolete()
  192. {
  193. // Written for compatibility with a data model written prior to version 0.9.1
  194. if (array_key_exists('label', $this->m_aParams))
  195. {
  196. return $this->m_aParams['label'];
  197. }
  198. else
  199. {
  200. return $this->GetLabel();
  201. }
  202. }
  203. public function GetDescription($sDefault = null)
  204. {
  205. // If no default value is specified, let's define the most relevant one for developping purposes
  206. if (is_null($sDefault))
  207. {
  208. $sDefault = '';
  209. }
  210. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');
  211. if (strlen($sLabel) == 0)
  212. {
  213. // Nothing found: go higher in the hierarchy (if possible)
  214. //
  215. $sLabel = $sDefault;
  216. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  217. if ($sParentClass)
  218. {
  219. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  220. {
  221. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  222. $sLabel = $oAttDef->GetDescription($sDefault);
  223. }
  224. }
  225. }
  226. return $sLabel;
  227. }
  228. public function GetHelpOnEdition($sDefault = null)
  229. {
  230. // If no default value is specified, let's define the most relevant one for developping purposes
  231. if (is_null($sDefault))
  232. {
  233. $sDefault = '';
  234. }
  235. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');
  236. if (strlen($sLabel) == 0)
  237. {
  238. // Nothing found: go higher in the hierarchy (if possible)
  239. //
  240. $sLabel = $sDefault;
  241. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  242. if ($sParentClass)
  243. {
  244. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  245. {
  246. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  247. $sLabel = $oAttDef->GetHelpOnEdition($sDefault);
  248. }
  249. }
  250. }
  251. return $sLabel;
  252. }
  253. public function GetHelpOnSmartSearch()
  254. {
  255. $aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
  256. foreach ($aParents as $sClass)
  257. {
  258. $sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
  259. if ($sHelp != '-missing-')
  260. {
  261. return $sHelp;
  262. }
  263. }
  264. return '';
  265. }
  266. public function GetDescription_Obsolete()
  267. {
  268. // Written for compatibility with a data model written prior to version 0.9.1
  269. if (array_key_exists('description', $this->m_aParams))
  270. {
  271. return $this->m_aParams['description'];
  272. }
  273. else
  274. {
  275. return $this->GetDescription();
  276. }
  277. }
  278. public function GetValuesDef() {return null;}
  279. public function GetPrerequisiteAttributes() {return array();}
  280. public function GetNullValue() {return null;}
  281. public function IsNull($proposedValue) {return is_null($proposedValue);}
  282. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  283. public function Equals($val1, $val2) {return ($val1 == $val2);}
  284. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  285. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  286. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  287. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  288. public function RequiresIndex() {return false;}
  289. public function GetOrderBySQLExpressions($sClassAlias)
  290. {
  291. // Note: This is the responsibility of this function to place backticks around column aliases
  292. return array('`'.$sClassAlias.$this->GetCode().'`');
  293. }
  294. // Import - differs slightly from SQL input, but identical in most cases
  295. //
  296. public function GetImportColumns() {return $this->GetSQLColumns();}
  297. public function FromImportToValue($aCols, $sPrefix = '')
  298. {
  299. $aValues = array();
  300. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  301. {
  302. // This is working, based on the assumption that importable fields
  303. // are not computed fields => the expression is the name of a column
  304. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  305. }
  306. return $this->FromSQLToValue($aValues, $sPrefix);
  307. }
  308. public function GetValidationPattern()
  309. {
  310. return '';
  311. }
  312. public function CheckFormat($value)
  313. {
  314. return true;
  315. }
  316. public function GetMaxSize()
  317. {
  318. return null;
  319. }
  320. public function MakeValue()
  321. {
  322. $sComputeFunc = $this->Get("compute_func");
  323. if (empty($sComputeFunc)) return null;
  324. return call_user_func($sComputeFunc);
  325. }
  326. abstract public function GetDefaultValue();
  327. //
  328. // To be overloaded in subclasses
  329. //
  330. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  331. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  332. //abstract protected GetBasicFilterHTMLInput();
  333. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  334. public function GetFilterDefinitions()
  335. {
  336. return array();
  337. }
  338. public function GetEditValue($sValue, $oHostObj = null)
  339. {
  340. return (string)$sValue;
  341. }
  342. public function GetAsHTML($sValue, $oHostObject = null)
  343. {
  344. return Str::pure2html((string)$sValue);
  345. }
  346. public function GetAsXML($sValue, $oHostObject = null)
  347. {
  348. return Str::pure2xml((string)$sValue);
  349. }
  350. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  351. {
  352. return (string)$sValue;
  353. }
  354. public function GetAllowedValues($aArgs = array(), $sContains = '')
  355. {
  356. $oValSetDef = $this->GetValuesDef();
  357. if (!$oValSetDef) return null;
  358. return $oValSetDef->GetValues($aArgs, $sContains);
  359. }
  360. /**
  361. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  362. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  363. * does nothing special, and just calls the default (loose) operator
  364. * @param string $sSearchText The search string to analyze for smart patterns
  365. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  366. * @param Hash $aParams Values of the query parameters
  367. * @return Expression The search condition to be added (AND) to the current search
  368. */
  369. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  370. {
  371. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  372. $oRightExpr = new VariableExpression($sParamName);
  373. $sOperator = $this->GetBasicFilterLooseOperator();
  374. switch ($sOperator)
  375. {
  376. case 'Contains':
  377. $aParams[$sParamName] = "%$sSearchText%";
  378. $sSQLOperator = 'LIKE';
  379. break;
  380. default:
  381. $sSQLOperator = $sOperator;
  382. $aParams[$sParamName] = $sSearchText;
  383. }
  384. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  385. return $oNewCondition;
  386. }
  387. }
  388. /**
  389. * Set of objects directly linked to an object, and being part of its definition
  390. *
  391. * @package iTopORM
  392. */
  393. class AttributeLinkedSet extends AttributeDefinition
  394. {
  395. static protected function ListExpectedParams()
  396. {
  397. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  398. }
  399. public function GetEditClass() {return "List";}
  400. public function IsWritable() {return true;}
  401. public function IsLinkSet() {return true;}
  402. public function IsIndirect() {return false;}
  403. public function GetValuesDef() {return $this->Get("allowed_values");}
  404. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  405. public function GetDefaultValue($aArgs = array())
  406. {
  407. // Note: so far, this feature is a prototype,
  408. // later, the argument 'this' should always be present in the arguments
  409. //
  410. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  411. {
  412. $aValues = $this->Get('default_value')->GetValues($aArgs);
  413. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  414. return $oSet;
  415. }
  416. else
  417. {
  418. return DBObjectSet::FromScratch($this->Get('linked_class'));
  419. }
  420. }
  421. public function GetLinkedClass() {return $this->Get('linked_class');}
  422. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  423. public function GetBasicFilterOperators() {return array();}
  424. public function GetBasicFilterLooseOperator() {return '';}
  425. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  426. public function GetAsHTML($sValue, $oHostObject = null)
  427. {
  428. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  429. {
  430. $sValue->Rewind();
  431. $aItems = array();
  432. while ($oObj = $sValue->Fetch())
  433. {
  434. // Show only relevant information (hide the external key to the current object)
  435. $aAttributes = array();
  436. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  437. {
  438. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  439. if ($oAttDef->IsExternalField()) continue;
  440. $sAttValue = $oObj->GetAsHTML($sAttCode);
  441. if (strlen($sAttValue) > 0)
  442. {
  443. $aAttributes[] = $sAttValue;
  444. }
  445. }
  446. $sAttributes = implode(', ', $aAttributes);
  447. $aItems[] = $sAttributes;
  448. }
  449. return implode('<br/>', $aItems);
  450. }
  451. return null;
  452. }
  453. public function GetAsXML($sValue, $oHostObject = null)
  454. {
  455. return "Sorry, no yet implemented";
  456. }
  457. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  458. {
  459. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  460. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  461. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  462. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  463. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  464. {
  465. $sValue->Rewind();
  466. $aItems = array();
  467. while ($oObj = $sValue->Fetch())
  468. {
  469. $sObjClass = get_class($oObj);
  470. // Show only relevant information (hide the external key to the current object)
  471. $aAttributes = array();
  472. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  473. {
  474. if ($sAttCode == 'finalclass')
  475. {
  476. if ($sObjClass == $this->GetLinkedClass())
  477. {
  478. // Simplify the output if the exact class could be determined implicitely
  479. continue;
  480. }
  481. }
  482. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  483. if ($oAttDef->IsExternalField()) continue;
  484. if (!$oAttDef->IsDirectField()) continue;
  485. if (!$oAttDef->IsScalar()) continue;
  486. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '');
  487. if (strlen($sAttValue) > 0)
  488. {
  489. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  490. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  491. }
  492. }
  493. $sAttributes = implode($sSepAttribute, $aAttributes);
  494. $aItems[] = $sAttributes;
  495. }
  496. $sRes = implode($sSepItem, $aItems);
  497. }
  498. else
  499. {
  500. $sRes = '';
  501. }
  502. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  503. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  504. return $sRes;
  505. }
  506. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  507. public function GetImportColumns()
  508. {
  509. $aColumns = array();
  510. $aColumns[$this->GetCode()] = 'TEXT';
  511. return $aColumns;
  512. }
  513. // Specific to this kind of attribute : transform a string into a value
  514. public function MakeValueFromString($sProposedValue, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  515. {
  516. if (is_null($sSepItem) || empty($sSepItem))
  517. {
  518. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  519. }
  520. if (is_null($sSepAttribute) || empty($sSepAttribute))
  521. {
  522. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  523. }
  524. if (is_null($sSepValue) || empty($sSepValue))
  525. {
  526. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  527. }
  528. if (is_null($sAttributeQualifier) || empty($sAttributeQualifier))
  529. {
  530. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  531. }
  532. $sTargetClass = $this->Get('linked_class');
  533. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  534. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  535. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  536. $aLinks = array();
  537. foreach($aInput as $aRow)
  538. {
  539. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  540. $aExtKeys = array();
  541. $aValues = array();
  542. foreach($aRow as $sCell)
  543. {
  544. $iSepPos = strpos($sCell, $sSepValue);
  545. if ($iSepPos === false)
  546. {
  547. // Houston...
  548. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  549. }
  550. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  551. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  552. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  553. {
  554. $sKeyAttCode = $aMatches[1];
  555. $sRemoteAttCode = $aMatches[2];
  556. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  557. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  558. {
  559. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  560. }
  561. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  562. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  563. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  564. {
  565. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  566. }
  567. }
  568. else
  569. {
  570. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  571. {
  572. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  573. }
  574. $aValues[$sAttCode] = $sValue;
  575. }
  576. }
  577. // 2nd - Instanciate the object and set the value
  578. if (isset($aValues['finalclass']))
  579. {
  580. $sLinkClass = $aValues['finalclass'];
  581. if (!is_subclass_of($sLinkClass, $sTargetClass))
  582. {
  583. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  584. }
  585. }
  586. elseif (MetaModel::IsAbstract($sTargetClass))
  587. {
  588. throw new CoreException('Missing finalclass for link attribute specification');
  589. }
  590. else
  591. {
  592. $sLinkClass = $sTargetClass;
  593. }
  594. $oLink = MetaModel::NewObject($sLinkClass);
  595. foreach ($aValues as $sAttCode => $sValue)
  596. {
  597. $oLink->Set($sAttCode, $sValue);
  598. }
  599. // 3rd - Set external keys from search conditions
  600. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  601. {
  602. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  603. $sKeyClass = $oKeyAttDef->GetTargetClass();
  604. $oExtKeyFilter = new CMDBSearchFilter($sKeyClass);
  605. $aReconciliationDesc = array();
  606. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  607. {
  608. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  609. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  610. }
  611. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  612. switch($oExtKeySet->Count())
  613. {
  614. case 0:
  615. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  616. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  617. break;
  618. case 1:
  619. $oRemoteObj = $oExtKeySet->Fetch();
  620. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  621. break;
  622. default:
  623. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  624. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  625. // Found several matches, ambiguous
  626. }
  627. }
  628. // Check (roughly) if such a link is valid
  629. $aErrors = array();
  630. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  631. {
  632. if ($oAttDef->IsExternalKey())
  633. {
  634. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  635. {
  636. continue; // Don't check the key to self
  637. }
  638. }
  639. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  640. {
  641. $aErrors[] = $sAttCode;
  642. }
  643. }
  644. if (count($aErrors) > 0)
  645. {
  646. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  647. }
  648. $aLinks[] = $oLink;
  649. }
  650. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  651. return $oSet;
  652. }
  653. public function Equals($val1, $val2)
  654. {
  655. if ($val1 === $val2) return true;
  656. if (is_object($val1) != is_object($val2))
  657. {
  658. return false;
  659. }
  660. if (!is_object($val1))
  661. {
  662. // string ?
  663. // todo = implement this case ?
  664. return false;
  665. }
  666. // Both values are Object sets
  667. return $val1->HasSameContents($val2);
  668. }
  669. }
  670. /**
  671. * Set of objects linked to an object (n-n), and being part of its definition
  672. *
  673. * @package iTopORM
  674. */
  675. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  676. {
  677. static protected function ListExpectedParams()
  678. {
  679. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  680. }
  681. public function IsIndirect() {return true;}
  682. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  683. public function GetEditClass() {return "LinkedSet";}
  684. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  685. }
  686. /**
  687. * Abstract class implementing default filters for a DB column
  688. *
  689. * @package iTopORM
  690. */
  691. class AttributeDBFieldVoid extends AttributeDefinition
  692. {
  693. static protected function ListExpectedParams()
  694. {
  695. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  696. }
  697. // To be overriden, used in GetSQLColumns
  698. protected function GetSQLCol() {return "VARCHAR(255)";}
  699. public function GetEditClass() {return "String";}
  700. public function GetValuesDef() {return $this->Get("allowed_values");}
  701. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  702. public function IsDirectField() {return true;}
  703. public function IsScalar() {return true;}
  704. public function IsWritable() {return true;}
  705. public function GetSQLExpr() {return $this->Get("sql");}
  706. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  707. public function IsNullAllowed() {return false;}
  708. //
  709. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  710. public function GetSQLExpressions($sPrefix = '')
  711. {
  712. $aColumns = array();
  713. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  714. $aColumns[''] = $this->Get("sql");
  715. return $aColumns;
  716. }
  717. public function FromSQLToValue($aCols, $sPrefix = '')
  718. {
  719. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  720. return $value;
  721. }
  722. public function GetSQLValues($value)
  723. {
  724. $aValues = array();
  725. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  726. return $aValues;
  727. }
  728. public function GetSQLColumns()
  729. {
  730. $aColumns = array();
  731. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  732. return $aColumns;
  733. }
  734. public function GetFilterDefinitions()
  735. {
  736. return array($this->GetCode() => new FilterFromAttribute($this));
  737. }
  738. public function GetBasicFilterOperators()
  739. {
  740. return array("="=>"equals", "!="=>"differs from");
  741. }
  742. public function GetBasicFilterLooseOperator()
  743. {
  744. return "=";
  745. }
  746. public function GetBasicFilterSQLExpr($sOpCode, $value)
  747. {
  748. $sQValue = CMDBSource::Quote($value);
  749. switch ($sOpCode)
  750. {
  751. case '!=':
  752. return $this->GetSQLExpr()." != $sQValue";
  753. break;
  754. case '=':
  755. default:
  756. return $this->GetSQLExpr()." = $sQValue";
  757. }
  758. }
  759. }
  760. /**
  761. * Base class for all kind of DB attributes, with the exception of external keys
  762. *
  763. * @package iTopORM
  764. */
  765. class AttributeDBField extends AttributeDBFieldVoid
  766. {
  767. static protected function ListExpectedParams()
  768. {
  769. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  770. }
  771. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  772. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  773. }
  774. /**
  775. * Map an integer column to an attribute
  776. *
  777. * @package iTopORM
  778. */
  779. class AttributeInteger extends AttributeDBField
  780. {
  781. static protected function ListExpectedParams()
  782. {
  783. return parent::ListExpectedParams();
  784. //return array_merge(parent::ListExpectedParams(), array());
  785. }
  786. public function GetEditClass() {return "String";}
  787. protected function GetSQLCol() {return "INT(11)";}
  788. public function GetValidationPattern()
  789. {
  790. return "^[0-9]+$";
  791. }
  792. public function GetBasicFilterOperators()
  793. {
  794. return array(
  795. "!="=>"differs from",
  796. "="=>"equals",
  797. ">"=>"greater (strict) than",
  798. ">="=>"greater than",
  799. "<"=>"less (strict) than",
  800. "<="=>"less than",
  801. "in"=>"in"
  802. );
  803. }
  804. public function GetBasicFilterLooseOperator()
  805. {
  806. // Unless we implement an "equals approximately..." or "same order of magnitude"
  807. return "=";
  808. }
  809. public function GetBasicFilterSQLExpr($sOpCode, $value)
  810. {
  811. $sQValue = CMDBSource::Quote($value);
  812. switch ($sOpCode)
  813. {
  814. case '!=':
  815. return $this->GetSQLExpr()." != $sQValue";
  816. break;
  817. case '>':
  818. return $this->GetSQLExpr()." > $sQValue";
  819. break;
  820. case '>=':
  821. return $this->GetSQLExpr()." >= $sQValue";
  822. break;
  823. case '<':
  824. return $this->GetSQLExpr()." < $sQValue";
  825. break;
  826. case '<=':
  827. return $this->GetSQLExpr()." <= $sQValue";
  828. break;
  829. case 'in':
  830. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  831. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  832. break;
  833. case '=':
  834. default:
  835. return $this->GetSQLExpr()." = \"$value\"";
  836. }
  837. }
  838. public function GetNullValue()
  839. {
  840. return null;
  841. }
  842. public function IsNull($proposedValue)
  843. {
  844. return is_null($proposedValue);
  845. }
  846. public function MakeRealValue($proposedValue, $oHostObj)
  847. {
  848. if (is_null($proposedValue)) return null;
  849. if ($proposedValue === '') return null; // 0 is transformed into '' !
  850. return (int)$proposedValue;
  851. }
  852. public function ScalarToSQL($value)
  853. {
  854. assert(is_numeric($value) || is_null($value));
  855. return $value; // supposed to be an int
  856. }
  857. }
  858. /**
  859. * Display an integer between 0 and 100 as a percentage / horizontal bar graph
  860. *
  861. * @package iTopORM
  862. */
  863. class AttributePercentage extends AttributeInteger
  864. {
  865. public function GetAsHTML($sValue, $oHostObject = null)
  866. {
  867. $iWidth = 5; // Total width of the percentage bar graph, in em...
  868. $iValue = (int)$sValue;
  869. if ($iValue > 100)
  870. {
  871. $iValue = 100;
  872. }
  873. else if ($iValue < 0)
  874. {
  875. $iValue = 0;
  876. }
  877. if ($iValue > 90)
  878. {
  879. $sColor = "#cc3300";
  880. }
  881. else if ($iValue > 50)
  882. {
  883. $sColor = "#cccc00";
  884. }
  885. else
  886. {
  887. $sColor = "#33cc00";
  888. }
  889. $iPercentWidth = ($iWidth * $iValue) / 100;
  890. return "<div style=\"width:{$iWidth}em;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px;display:inline-block;border: 1px #ccc solid;\"><div style=\"width:{$iPercentWidth}em; display:inline-block;background-color:$sColor;\">&nbsp;</div></div>&nbsp;$sValue %";
  891. }
  892. }
  893. /**
  894. * Map a decimal value column (suitable for financial computations) to an attribute
  895. * internally in PHP such numbers are represented as string. Should you want to perform
  896. * a calculation on them, it is recommended to use the BC Math functions in order to
  897. * retain the precision
  898. *
  899. * @package iTopORM
  900. */
  901. class AttributeDecimal extends AttributeDBField
  902. {
  903. static protected function ListExpectedParams()
  904. {
  905. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  906. }
  907. public function GetEditClass() {return "String";}
  908. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  909. public function GetValidationPattern()
  910. {
  911. $iNbDigits = $this->Get('digits');
  912. $iPrecision = $this->Get('decimals');
  913. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  914. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  915. }
  916. public function GetBasicFilterOperators()
  917. {
  918. return array(
  919. "!="=>"differs from",
  920. "="=>"equals",
  921. ">"=>"greater (strict) than",
  922. ">="=>"greater than",
  923. "<"=>"less (strict) than",
  924. "<="=>"less than",
  925. "in"=>"in"
  926. );
  927. }
  928. public function GetBasicFilterLooseOperator()
  929. {
  930. // Unless we implement an "equals approximately..." or "same order of magnitude"
  931. return "=";
  932. }
  933. public function GetBasicFilterSQLExpr($sOpCode, $value)
  934. {
  935. $sQValue = CMDBSource::Quote($value);
  936. switch ($sOpCode)
  937. {
  938. case '!=':
  939. return $this->GetSQLExpr()." != $sQValue";
  940. break;
  941. case '>':
  942. return $this->GetSQLExpr()." > $sQValue";
  943. break;
  944. case '>=':
  945. return $this->GetSQLExpr()." >= $sQValue";
  946. break;
  947. case '<':
  948. return $this->GetSQLExpr()." < $sQValue";
  949. break;
  950. case '<=':
  951. return $this->GetSQLExpr()." <= $sQValue";
  952. break;
  953. case 'in':
  954. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  955. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  956. break;
  957. case '=':
  958. default:
  959. return $this->GetSQLExpr()." = \"$value\"";
  960. }
  961. }
  962. public function GetNullValue()
  963. {
  964. return null;
  965. }
  966. public function IsNull($proposedValue)
  967. {
  968. return is_null($proposedValue);
  969. }
  970. public function MakeRealValue($proposedValue, $oHostObj)
  971. {
  972. if (is_null($proposedValue)) return null;
  973. if ($proposedValue == '') return null;
  974. return (string)$proposedValue;
  975. }
  976. public function ScalarToSQL($value)
  977. {
  978. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  979. return (string)$value; // treated as a string
  980. }
  981. }
  982. /**
  983. * Map a boolean column to an attribute
  984. *
  985. * @package iTopORM
  986. */
  987. class AttributeBoolean extends AttributeInteger
  988. {
  989. static protected function ListExpectedParams()
  990. {
  991. return parent::ListExpectedParams();
  992. //return array_merge(parent::ListExpectedParams(), array());
  993. }
  994. public function GetEditClass() {return "Integer";}
  995. protected function GetSQLCol() {return "TINYINT(1)";}
  996. public function MakeRealValue($proposedValue, $oHostObj)
  997. {
  998. if (is_null($proposedValue)) return null;
  999. if ($proposedValue === '') return null;
  1000. if ((int)$proposedValue) return true;
  1001. return false;
  1002. }
  1003. public function ScalarToSQL($value)
  1004. {
  1005. if ($value) return 1;
  1006. return 0;
  1007. }
  1008. }
  1009. /**
  1010. * Map a varchar column (size < ?) to an attribute
  1011. *
  1012. * @package iTopORM
  1013. */
  1014. class AttributeString extends AttributeDBField
  1015. {
  1016. static protected function ListExpectedParams()
  1017. {
  1018. return parent::ListExpectedParams();
  1019. //return array_merge(parent::ListExpectedParams(), array());
  1020. }
  1021. public function GetEditClass() {return "String";}
  1022. protected function GetSQLCol() {return "VARCHAR(255)";}
  1023. public function GetValidationPattern()
  1024. {
  1025. $sPattern = $this->GetOptional('validation_pattern', '');
  1026. if (empty($sPattern))
  1027. {
  1028. return parent::GetValidationPattern();
  1029. }
  1030. else
  1031. {
  1032. return $sPattern;
  1033. }
  1034. }
  1035. public function CheckFormat($value)
  1036. {
  1037. $sRegExp = $this->GetValidationPattern();
  1038. if (empty($sRegExp))
  1039. {
  1040. return true;
  1041. }
  1042. else
  1043. {
  1044. $sRegExp = str_replace('/', '\\/', $sRegExp);
  1045. return preg_match("/$sRegExp/", $value);
  1046. }
  1047. }
  1048. public function GetMaxSize()
  1049. {
  1050. return 255;
  1051. }
  1052. public function GetBasicFilterOperators()
  1053. {
  1054. return array(
  1055. "="=>"equals",
  1056. "!="=>"differs from",
  1057. "Like"=>"equals (no case)",
  1058. "NotLike"=>"differs from (no case)",
  1059. "Contains"=>"contains",
  1060. "Begins with"=>"begins with",
  1061. "Finishes with"=>"finishes with"
  1062. );
  1063. }
  1064. public function GetBasicFilterLooseOperator()
  1065. {
  1066. return "Contains";
  1067. }
  1068. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1069. {
  1070. $sQValue = CMDBSource::Quote($value);
  1071. switch ($sOpCode)
  1072. {
  1073. case '=':
  1074. case '!=':
  1075. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1076. case 'Begins with':
  1077. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  1078. case 'Finishes with':
  1079. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  1080. case 'Contains':
  1081. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  1082. case 'NotLike':
  1083. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  1084. case 'Like':
  1085. default:
  1086. return $this->GetSQLExpr()." LIKE $sQValue";
  1087. }
  1088. }
  1089. public function GetNullValue()
  1090. {
  1091. return '';
  1092. }
  1093. public function IsNull($proposedValue)
  1094. {
  1095. return ($proposedValue == '');
  1096. }
  1097. public function MakeRealValue($proposedValue, $oHostObj)
  1098. {
  1099. if (is_null($proposedValue)) return '';
  1100. return (string)$proposedValue;
  1101. }
  1102. public function ScalarToSQL($value)
  1103. {
  1104. if (!is_string($value) && !is_null($value))
  1105. {
  1106. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1107. }
  1108. return $value;
  1109. }
  1110. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1111. {
  1112. $sFrom = array("\r\n", $sTextQualifier);
  1113. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1114. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1115. return $sTextQualifier.$sEscaped.$sTextQualifier;
  1116. }
  1117. public function GetDisplayStyle()
  1118. {
  1119. return $this->GetOptional('display_style', 'select');
  1120. }
  1121. }
  1122. /**
  1123. * An attibute that matches an object class
  1124. *
  1125. * @package iTopORM
  1126. */
  1127. class AttributeClass extends AttributeString
  1128. {
  1129. static protected function ListExpectedParams()
  1130. {
  1131. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  1132. }
  1133. public function __construct($sCode, $aParams)
  1134. {
  1135. $this->m_sCode = $sCode;
  1136. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  1137. parent::__construct($sCode, $aParams);
  1138. }
  1139. public function GetDefaultValue()
  1140. {
  1141. $sDefault = parent::GetDefaultValue();
  1142. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  1143. {
  1144. // For this kind of attribute specifying null as default value
  1145. // is authorized even if null is not allowed
  1146. // Pick the first one...
  1147. $aClasses = $this->GetAllowedValues();
  1148. $sDefault = key($aClasses);
  1149. }
  1150. return $sDefault;
  1151. }
  1152. public function GetAsHTML($sValue, $oHostObject = null)
  1153. {
  1154. if (empty($sValue)) return '';
  1155. return MetaModel::GetName($sValue);
  1156. }
  1157. public function RequiresIndex()
  1158. {
  1159. return true;
  1160. }
  1161. public function GetBasicFilterLooseOperator()
  1162. {
  1163. return '=';
  1164. }
  1165. }
  1166. /**
  1167. * An attibute that matches one of the language codes availables in the dictionnary
  1168. *
  1169. * @package iTopORM
  1170. */
  1171. class AttributeApplicationLanguage extends AttributeString
  1172. {
  1173. static protected function ListExpectedParams()
  1174. {
  1175. return parent::ListExpectedParams();
  1176. }
  1177. public function __construct($sCode, $aParams)
  1178. {
  1179. $this->m_sCode = $sCode;
  1180. $aAvailableLanguages = Dict::GetLanguages();
  1181. $aLanguageCodes = array();
  1182. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1183. {
  1184. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1185. }
  1186. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1187. parent::__construct($sCode, $aParams);
  1188. }
  1189. public function RequiresIndex()
  1190. {
  1191. return true;
  1192. }
  1193. public function GetBasicFilterLooseOperator()
  1194. {
  1195. return '=';
  1196. }
  1197. }
  1198. /**
  1199. * The attribute dedicated to the finalclass automatic attribute
  1200. *
  1201. * @package iTopORM
  1202. */
  1203. class AttributeFinalClass extends AttributeString
  1204. {
  1205. public function __construct($sCode, $aParams)
  1206. {
  1207. $this->m_sCode = $sCode;
  1208. $aParams["allowed_values"] = null;
  1209. parent::__construct($sCode, $aParams);
  1210. $this->m_sValue = $this->Get("default_value");
  1211. }
  1212. public function IsWritable()
  1213. {
  1214. return false;
  1215. }
  1216. public function RequiresIndex()
  1217. {
  1218. return true;
  1219. }
  1220. public function SetFixedValue($sValue)
  1221. {
  1222. $this->m_sValue = $sValue;
  1223. }
  1224. public function GetDefaultValue()
  1225. {
  1226. return $this->m_sValue;
  1227. }
  1228. public function GetAsHTML($sValue, $oHostObject = null)
  1229. {
  1230. if (empty($sValue)) return '';
  1231. return MetaModel::GetName($sValue);
  1232. }
  1233. public function GetBasicFilterLooseOperator()
  1234. {
  1235. return '=';
  1236. }
  1237. public function GetValueLabel($sValue)
  1238. {
  1239. if (empty($sValue)) return '';
  1240. return MetaModel::GetName($sValue);
  1241. }
  1242. }
  1243. /**
  1244. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1245. *
  1246. * @package iTopORM
  1247. */
  1248. class AttributePassword extends AttributeString
  1249. {
  1250. static protected function ListExpectedParams()
  1251. {
  1252. return parent::ListExpectedParams();
  1253. //return array_merge(parent::ListExpectedParams(), array());
  1254. }
  1255. public function GetEditClass() {return "Password";}
  1256. protected function GetSQLCol() {return "VARCHAR(64)";}
  1257. public function GetMaxSize()
  1258. {
  1259. return 64;
  1260. }
  1261. public function GetFilterDefinitions()
  1262. {
  1263. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1264. // not allowed to search on passwords!
  1265. return array();
  1266. }
  1267. public function GetAsHTML($sValue, $oHostObject = null)
  1268. {
  1269. if (strlen($sValue) == 0)
  1270. {
  1271. return '';
  1272. }
  1273. else
  1274. {
  1275. return '******';
  1276. }
  1277. }
  1278. }
  1279. /**
  1280. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1281. * The encryption is based on a key set per iTop instance. Thus if you export your
  1282. * database (in SQL) to someone else without providing the key at the same time
  1283. * the encrypted fields will remain encrypted
  1284. *
  1285. * @package iTopORM
  1286. */
  1287. class AttributeEncryptedString extends AttributeString
  1288. {
  1289. static $sKey = null; // Encryption key used for all encrypted fields
  1290. public function __construct($sCode, $aParams)
  1291. {
  1292. parent::__construct($sCode, $aParams);
  1293. if (self::$sKey == null)
  1294. {
  1295. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1296. }
  1297. }
  1298. protected function GetSQLCol() {return "TINYBLOB";}
  1299. public function GetMaxSize()
  1300. {
  1301. return 255;
  1302. }
  1303. public function GetFilterDefinitions()
  1304. {
  1305. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1306. // not allowed to search on encrypted fields !
  1307. return array();
  1308. }
  1309. public function MakeRealValue($proposedValue, $oHostObj)
  1310. {
  1311. if (is_null($proposedValue)) return null;
  1312. return (string)$proposedValue;
  1313. }
  1314. /**
  1315. * Decrypt the value when reading from the database
  1316. */
  1317. public function FromSQLToValue($aCols, $sPrefix = '')
  1318. {
  1319. $oSimpleCrypt = new SimpleCrypt();
  1320. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1321. return $sValue;
  1322. }
  1323. /**
  1324. * Encrypt the value before storing it in the database
  1325. */
  1326. public function GetSQLValues($value)
  1327. {
  1328. $oSimpleCrypt = new SimpleCrypt();
  1329. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1330. $aValues = array();
  1331. $aValues[$this->Get("sql")] = $encryptedValue;
  1332. return $aValues;
  1333. }
  1334. }
  1335. // Wiki formatting - experimental
  1336. //
  1337. // [[<objClass>:<objName>]]
  1338. // Example: [[Server:db1.tnut.com]]
  1339. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1340. // <url>
  1341. // Example: http://romain:trustno1@127.0.0.1:8888/iTop-trunk/modules/itop-caches/itop-caches.php?agument=machin%20#monAncre
  1342. define('WIKI_URL', "/(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?([a-z0-9-.]{3,})(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?/i");
  1343. // SHEME............. USER.................... PASSWORD...................... HOST/IP......... PORT.......... PATH...................... GET................................... ANCHOR....................
  1344. // Origin of this regexp: http://www.php.net/manual/fr/function.preg-match.php#93824
  1345. /**
  1346. * Map a text column (size > ?) to an attribute
  1347. *
  1348. * @package iTopORM
  1349. */
  1350. class AttributeText extends AttributeString
  1351. {
  1352. public function GetEditClass() {return "Text";}
  1353. protected function GetSQLCol() {return "TEXT";}
  1354. public function GetMaxSize()
  1355. {
  1356. // Is there a way to know the current limitation for mysql?
  1357. // See mysql_field_len()
  1358. return 65535;
  1359. }
  1360. static public function RenderWikiHtml($sText)
  1361. {
  1362. if (preg_match_all(WIKI_URL, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  1363. {
  1364. $aUrls = array();
  1365. $i = count($aAllMatches);
  1366. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  1367. // Let's do it backwards so that the initial positions are not modified by the replacement
  1368. // This works if the matches are captured: in the order they occur in the string AND
  1369. // with their offset (i.e. position) inside the string
  1370. while($i > 0)
  1371. {
  1372. $i--;
  1373. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  1374. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  1375. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  1376. }
  1377. }
  1378. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1379. {
  1380. foreach($aAllMatches as $iPos => $aMatches)
  1381. {
  1382. $sClass = $aMatches[1];
  1383. $sName = $aMatches[2];
  1384. if (MetaModel::IsValidClass($sClass))
  1385. {
  1386. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1387. if (is_object($oObj))
  1388. {
  1389. // Propose a std link to the object
  1390. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1391. }
  1392. else
  1393. {
  1394. // Propose a std link to the object
  1395. $sClassLabel = MetaModel::GetName($sClass);
  1396. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1397. // Later: propose a link to create a new object
  1398. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1399. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1400. }
  1401. }
  1402. }
  1403. }
  1404. return $sText;
  1405. }
  1406. public function GetAsHTML($sValue, $oHostObject = null)
  1407. {
  1408. $sValue = parent::GetAsHTML($sValue);
  1409. $sValue = self::RenderWikiHtml($sValue);
  1410. $aStyles = array();
  1411. if ($this->GetWidth() != '')
  1412. {
  1413. $aStyles[] = 'width:'.$this->GetWidth();
  1414. }
  1415. if ($this->GetHeight() != '')
  1416. {
  1417. $aStyles[] = 'height:'.$this->GetHeight();
  1418. }
  1419. $sStyle = '';
  1420. if (count($aStyles) > 0)
  1421. {
  1422. $aStyles[] = 'overflow:auto';
  1423. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1424. }
  1425. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  1426. }
  1427. public function GetEditValue($sValue, $oHostObj = null)
  1428. {
  1429. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1430. {
  1431. foreach($aAllMatches as $iPos => $aMatches)
  1432. {
  1433. $sClass = $aMatches[1];
  1434. $sName = $aMatches[2];
  1435. if (MetaModel::IsValidClass($sClass))
  1436. {
  1437. $sClassLabel = MetaModel::GetName($sClass);
  1438. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1439. }
  1440. }
  1441. }
  1442. return $sValue;
  1443. }
  1444. public function MakeRealValue($proposedValue, $oHostObj)
  1445. {
  1446. $sValue = $proposedValue;
  1447. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1448. {
  1449. foreach($aAllMatches as $iPos => $aMatches)
  1450. {
  1451. $sClassLabel = $aMatches[1];
  1452. $sName = $aMatches[2];
  1453. if (!MetaModel::IsValidClass($sClassLabel))
  1454. {
  1455. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1456. if ($sClass)
  1457. {
  1458. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1459. }
  1460. }
  1461. }
  1462. }
  1463. return $sValue;
  1464. }
  1465. public function GetAsXML($value, $oHostObject = null)
  1466. {
  1467. return Str::pure2xml($value);
  1468. }
  1469. public function GetWidth()
  1470. {
  1471. return $this->GetOptional('width', '');
  1472. }
  1473. public function GetHeight()
  1474. {
  1475. return $this->GetOptional('height', '');
  1476. }
  1477. }
  1478. /**
  1479. * Map a log to an attribute
  1480. *
  1481. * @package iTopORM
  1482. */
  1483. class AttributeLongText extends AttributeText
  1484. {
  1485. protected function GetSQLCol() {return "LONGTEXT";}
  1486. public function GetMaxSize()
  1487. {
  1488. // Is there a way to know the current limitation for mysql?
  1489. // See mysql_field_len()
  1490. return 65535*1024; // Limited... still 64 Mb!
  1491. }
  1492. }
  1493. /**
  1494. * An attibute that stores a case log (i.e journal)
  1495. *
  1496. * @package iTopORM
  1497. */
  1498. class AttributeCaseLog extends AttributeLongText
  1499. {
  1500. public function GetNullValue()
  1501. {
  1502. return '';
  1503. }
  1504. public function IsNull($proposedValue)
  1505. {
  1506. if (!($proposedValue instanceof ormCaseLog))
  1507. {
  1508. return ($proposedValue == '');
  1509. }
  1510. return ($proposedValue->GetText() == '');
  1511. }
  1512. public function ScalarToSQL($value)
  1513. {
  1514. if (!is_string($value) && !is_null($value))
  1515. {
  1516. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1517. }
  1518. return $value;
  1519. }
  1520. public function GetEditClass() {return "CaseLog";}
  1521. public function GetEditValue($sValue, $oHostObj = null) { return ''; } // New 'edit' value is always blank since it will be appended to the existing log
  1522. public function GetDefaultValue() {return new ormCaseLog();}
  1523. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  1524. // Facilitate things: allow the user to Set the value from a string
  1525. public function MakeRealValue($proposedValue, $oHostObj)
  1526. {
  1527. if (!($proposedValue instanceof ormCaseLog))
  1528. {
  1529. // Append the new value if an instance of the object is supplied
  1530. //
  1531. $oPreviousLog = null;
  1532. if ($oHostObj != null)
  1533. {
  1534. $oPreviousLog = $oHostObj->Get($this->GetCode());
  1535. if (!is_object($oPreviousLog))
  1536. {
  1537. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  1538. }
  1539. }
  1540. if (is_object($oPreviousLog))
  1541. {
  1542. $oCaseLog = clone($oPreviousLog);
  1543. }
  1544. else
  1545. {
  1546. $oCaseLog = new ormCaseLog();
  1547. }
  1548. if (strlen($proposedValue) > 0)
  1549. {
  1550. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  1551. }
  1552. return $oCaseLog;
  1553. }
  1554. return $proposedValue;
  1555. }
  1556. public function GetSQLExpressions($sPrefix = '')
  1557. {
  1558. if ($sPrefix == '')
  1559. {
  1560. $sPrefix = $this->GetCode();
  1561. }
  1562. $aColumns = array();
  1563. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1564. $aColumns[''] = $sPrefix;
  1565. $aColumns['_index'] = $sPrefix.'_index';
  1566. return $aColumns;
  1567. }
  1568. public function FromSQLToValue($aCols, $sPrefix = '')
  1569. {
  1570. if (!isset($aCols[$sPrefix]))
  1571. {
  1572. $sAvailable = implode(', ', array_keys($aCols));
  1573. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1574. }
  1575. $sLog = $aCols[$sPrefix];
  1576. if (isset($aCols[$sPrefix.'_index']))
  1577. {
  1578. $sIndex = $aCols[$sPrefix.'_index'];
  1579. }
  1580. else
  1581. {
  1582. // For backward compatibility, allow the current state to be: 1 log, no index
  1583. $sIndex = '';
  1584. }
  1585. if (strlen($sIndex) > 0)
  1586. {
  1587. $aIndex = unserialize($sIndex);
  1588. $value = new ormCaseLog($sLog, $aIndex);
  1589. }
  1590. else
  1591. {
  1592. $value = new ormCaseLog($sLog);
  1593. }
  1594. return $value;
  1595. }
  1596. public function GetSQLValues($value)
  1597. {
  1598. if (!($value instanceOf ormCaseLog))
  1599. {
  1600. $value = new ormCaseLog('');
  1601. }
  1602. $aValues = array();
  1603. $aValues[$this->GetCode()] = $value->GetText();
  1604. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  1605. return $aValues;
  1606. }
  1607. public function GetSQLColumns()
  1608. {
  1609. $aColumns = array();
  1610. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  1611. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  1612. return $aColumns;
  1613. }
  1614. public function GetAsHTML($value, $oHostObject = null)
  1615. {
  1616. if ($value instanceOf ormCaseLog)
  1617. {
  1618. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  1619. }
  1620. else
  1621. {
  1622. $sContent = '';
  1623. }
  1624. $aStyles = array();
  1625. if ($this->GetWidth() != '')
  1626. {
  1627. $aStyles[] = 'width:'.$this->GetWidth();
  1628. }
  1629. if ($this->GetHeight() != '')
  1630. {
  1631. $aStyles[] = 'height:'.$this->GetHeight();
  1632. }
  1633. $sStyle = '';
  1634. if (count($aStyles) > 0)
  1635. {
  1636. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1637. }
  1638. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  1639. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1640. {
  1641. if ($value instanceOf ormCaseLog)
  1642. {
  1643. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject);
  1644. }
  1645. else
  1646. {
  1647. return '';
  1648. }
  1649. }
  1650. public function GetAsXML($value, $oHostObject = null)
  1651. {
  1652. if ($value instanceOf ormCaseLog)
  1653. {
  1654. return parent::GetAsXML($value->GetText(), $oHostObject);
  1655. }
  1656. else
  1657. {
  1658. return '';
  1659. }
  1660. }
  1661. }
  1662. /**
  1663. * Map a text column (size > ?), containing HTML code, to an attribute
  1664. *
  1665. * @package iTopORM
  1666. */
  1667. class AttributeHTML extends AttributeText
  1668. {
  1669. public function GetEditClass() {return "HTML";}
  1670. public function GetAsHTML($sValue, $oHostObject = null)
  1671. {
  1672. return $sValue;
  1673. }
  1674. }
  1675. /**
  1676. * Specialization of a string: email
  1677. *
  1678. * @package iTopORM
  1679. */
  1680. class AttributeEmailAddress extends AttributeString
  1681. {
  1682. public function GetValidationPattern()
  1683. {
  1684. // return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  1685. return "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
  1686. }
  1687. public function GetAsHTML($sValue, $oHostObject = null)
  1688. {
  1689. if (empty($sValue)) return '';
  1690. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  1691. }
  1692. }
  1693. /**
  1694. * Specialization of a string: IP address
  1695. *
  1696. * @package iTopORM
  1697. */
  1698. class AttributeIPAddress extends AttributeString
  1699. {
  1700. public function GetValidationPattern()
  1701. {
  1702. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  1703. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  1704. }
  1705. public function GetOrderBySQLExpressions($sClassAlias)
  1706. {
  1707. // Note: This is the responsibility of this function to place backticks around column aliases
  1708. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  1709. }
  1710. }
  1711. /**
  1712. * Specialization of a string: OQL expression
  1713. *
  1714. * @package iTopORM
  1715. */
  1716. class AttributeOQL extends AttributeText
  1717. {
  1718. public function GetEditClass() {return "OQLExpression";}
  1719. }
  1720. /**
  1721. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1722. *
  1723. * @package iTopORM
  1724. */
  1725. class AttributeTemplateString extends AttributeString
  1726. {
  1727. }
  1728. /**
  1729. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1730. *
  1731. * @package iTopORM
  1732. */
  1733. class AttributeTemplateText extends AttributeText
  1734. {
  1735. }
  1736. /**
  1737. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1738. *
  1739. * @package iTopORM
  1740. */
  1741. class AttributeTemplateHTML extends AttributeText
  1742. {
  1743. public function GetEditClass() {return "HTML";}
  1744. public function GetAsHTML($sValue, $oHostObject = null)
  1745. {
  1746. return $sValue;
  1747. }
  1748. }
  1749. /**
  1750. * Map a enum column to an attribute
  1751. *
  1752. * @package iTopORM
  1753. */
  1754. class AttributeEnum extends AttributeString
  1755. {
  1756. static protected function ListExpectedParams()
  1757. {
  1758. return parent::ListExpectedParams();
  1759. //return array_merge(parent::ListExpectedParams(), array());
  1760. }
  1761. public function GetEditClass() {return "String";}
  1762. protected function GetSQLCol()
  1763. {
  1764. $oValDef = $this->GetValuesDef();
  1765. if ($oValDef)
  1766. {
  1767. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1768. }
  1769. else
  1770. {
  1771. $aValues = array();
  1772. }
  1773. if (count($aValues) > 0)
  1774. {
  1775. // The syntax used here do matters
  1776. // In particular, I had to remove unnecessary spaces to
  1777. // make sure that this string will match the field type returned by the DB
  1778. // (used to perform a comparison between the current DB format and the data model)
  1779. return "ENUM(".implode(",", $aValues).")";
  1780. }
  1781. else
  1782. {
  1783. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1784. }
  1785. }
  1786. public function ScalarToSQL($value)
  1787. {
  1788. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1789. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1790. // that's why a null value must be forced to a real null
  1791. $value = parent::ScalarToSQL($value);
  1792. if ($this->IsNull($value))
  1793. {
  1794. return null;
  1795. }
  1796. else
  1797. {
  1798. return $value;
  1799. }
  1800. }
  1801. public function RequiresIndex()
  1802. {
  1803. return false;
  1804. }
  1805. public function GetBasicFilterOperators()
  1806. {
  1807. return parent::GetBasicFilterOperators();
  1808. }
  1809. public function GetBasicFilterLooseOperator()
  1810. {
  1811. return '=';
  1812. }
  1813. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1814. {
  1815. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1816. }
  1817. public function GetValueLabel($sValue)
  1818. {
  1819. if (is_null($sValue))
  1820. {
  1821. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1822. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1823. }
  1824. else
  1825. {
  1826. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, '');
  1827. if (strlen($sLabel) == 0)
  1828. {
  1829. $sLabel = $sValue;
  1830. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  1831. if ($sParentClass)
  1832. {
  1833. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  1834. {
  1835. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  1836. $sLabel = $oAttDef->GetValueLabel($sValue);
  1837. }
  1838. }
  1839. }
  1840. }
  1841. return $sLabel;
  1842. }
  1843. public function GetValueDescription($sValue)
  1844. {
  1845. if (is_null($sValue))
  1846. {
  1847. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1848. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  1849. }
  1850. else
  1851. {
  1852. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '');
  1853. if (strlen($sDescription) == 0)
  1854. {
  1855. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  1856. if ($sParentClass)
  1857. {
  1858. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  1859. {
  1860. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  1861. $sDescription = $oAttDef->GetValueDescription($sValue);
  1862. }
  1863. }
  1864. }
  1865. }
  1866. return $sDescription;
  1867. }
  1868. public function GetAsHTML($sValue, $oHostObject = null)
  1869. {
  1870. $sLabel = $this->GetValueLabel($sValue);
  1871. $sDescription = $this->GetValueDescription($sValue);
  1872. // later, we could imagine a detailed description in the title
  1873. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1874. }
  1875. public function GetEditValue($sValue, $oHostObj = null)
  1876. {
  1877. return $this->GetValueLabel($sValue);
  1878. }
  1879. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1880. {
  1881. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  1882. if (is_null($aRawValues)) return null;
  1883. $aLocalizedValues = array();
  1884. foreach ($aRawValues as $sKey => $sValue)
  1885. {
  1886. $aLocalizedValues[$sKey] = $this->GetValueLabel($sKey);
  1887. }
  1888. return $aLocalizedValues;
  1889. }
  1890. /**
  1891. * Processes the input value to align it with the values supported
  1892. * by this type of attribute. In this case: turns empty strings into nulls
  1893. * @param mixed $proposedValue The value to be set for the attribute
  1894. * @return mixed The actual value that will be set
  1895. */
  1896. public function MakeRealValue($proposedValue, $oHostObj)
  1897. {
  1898. if ($proposedValue == '') return null;
  1899. return parent::MakeRealValue($proposedValue, $oHostObj);
  1900. }
  1901. }
  1902. /**
  1903. * Map a date+time column to an attribute
  1904. *
  1905. * @package iTopORM
  1906. */
  1907. class AttributeDateTime extends AttributeDBField
  1908. {
  1909. static protected function GetDateFormat()
  1910. {
  1911. return "Y-m-d H:i:s";
  1912. }
  1913. static protected function ListExpectedParams()
  1914. {
  1915. return parent::ListExpectedParams();
  1916. //return array_merge(parent::ListExpectedParams(), array());
  1917. }
  1918. public function GetEditClass() {return "DateTime";}
  1919. protected function GetSQLCol() {return "TIMESTAMP";}
  1920. public static function GetAsUnixSeconds($value)
  1921. {
  1922. $oDeadlineDateTime = new DateTime($value);
  1923. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1924. return $iUnixSeconds;
  1925. }
  1926. // #@# THIS HAS TO REVISED
  1927. // Having null not allowed was interpreted by mySQL
  1928. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1929. // Then, on each update of the record, the field was modified.
  1930. // We will have to specify the default value if we want to restore this option
  1931. // In fact, we could also have more verbs dedicated to the DB:
  1932. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1933. public function IsNullAllowed() {return true;}
  1934. public function GetDefaultValue()
  1935. {
  1936. $default = parent::GetDefaultValue();
  1937. if (!parent::IsNullAllowed())
  1938. {
  1939. if (empty($default))
  1940. {
  1941. $default = date($this->GetDateFormat());
  1942. }
  1943. }
  1944. return $default;
  1945. }
  1946. // END OF THE WORKAROUND
  1947. ///////////////////////////////////////////////////////////////
  1948. public function GetValidationPattern()
  1949. {
  1950. 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$";
  1951. }
  1952. public function GetBasicFilterOperators()
  1953. {
  1954. return array(
  1955. "="=>"equals",
  1956. "!="=>"differs from",
  1957. "<"=>"before",
  1958. "<="=>"before",
  1959. ">"=>"after (strictly)",
  1960. ">="=>"after",
  1961. "SameDay"=>"same day (strip time)",
  1962. "SameMonth"=>"same year/month",
  1963. "SameYear"=>"same year",
  1964. "Today"=>"today",
  1965. ">|"=>"after today + N days",
  1966. "<|"=>"before today + N days",
  1967. "=|"=>"equals today + N days",
  1968. );
  1969. }
  1970. public function GetBasicFilterLooseOperator()
  1971. {
  1972. // Unless we implement a "same xxx, depending on given precision" !
  1973. return "=";
  1974. }
  1975. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1976. {
  1977. $sQValue = CMDBSource::Quote($value);
  1978. switch ($sOpCode)
  1979. {
  1980. case '=':
  1981. case '!=':
  1982. case '<':
  1983. case '<=':
  1984. case '>':
  1985. case '>=':
  1986. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1987. case 'SameDay':
  1988. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1989. case 'SameMonth':
  1990. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1991. case 'SameYear':
  1992. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1993. case 'Today':
  1994. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1995. case '>|':
  1996. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1997. case '<|':
  1998. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1999. case '=|':
  2000. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2001. default:
  2002. return $this->GetSQLExpr()." = $sQValue";
  2003. }
  2004. }
  2005. public function MakeRealValue($proposedValue, $oHostObj)
  2006. {
  2007. if (is_null($proposedValue))
  2008. {
  2009. return null;
  2010. }
  2011. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  2012. {
  2013. return null;
  2014. }
  2015. if (!is_numeric($proposedValue))
  2016. {
  2017. return $proposedValue;
  2018. }
  2019. return date(self::GetDateFormat(), $proposedValue);
  2020. }
  2021. public function ScalarToSQL($value)
  2022. {
  2023. if (is_null($value))
  2024. {
  2025. return null;
  2026. }
  2027. elseif (empty($value))
  2028. {
  2029. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  2030. return '0000-00-00 00:00:00';
  2031. }
  2032. return $value;
  2033. }
  2034. public function GetAsHTML($value, $oHostObject = null)
  2035. {
  2036. return Str::pure2html($value);
  2037. }
  2038. public function GetAsXML($value, $oHostObject = null)
  2039. {
  2040. return Str::pure2xml($value);
  2041. }
  2042. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2043. {
  2044. $sFrom = array("\r\n", $sTextQualifier);
  2045. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2046. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2047. return '"'.$sEscaped.'"';
  2048. }
  2049. /**
  2050. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  2051. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  2052. * does nothing special, and just calls the default (loose) operator
  2053. * @param string $sSearchText The search string to analyze for smart patterns
  2054. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  2055. * @param Hash $aParams Values of the query parameters
  2056. * @return Expression The search condition to be added (AND) to the current search
  2057. */
  2058. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  2059. {
  2060. // Possible smart patterns
  2061. $aPatterns = array(
  2062. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  2063. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  2064. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  2065. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  2066. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  2067. );
  2068. $sPatternFound = '';
  2069. $aMatches = array();
  2070. foreach($aPatterns as $sPatName => $sPattern)
  2071. {
  2072. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  2073. {
  2074. $sPatternFound = $sPatName;
  2075. break;
  2076. }
  2077. }
  2078. switch($sPatternFound)
  2079. {
  2080. case 'between':
  2081. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  2082. $oRightExpr = new VariableExpression($sParamName1);
  2083. $aParams[$sParamName1] = $aMatches[1];
  2084. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  2085. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  2086. $oRightExpr = new VariableExpression($sParamName2);
  2087. $sOperator = $this->GetBasicFilterLooseOperator();
  2088. $aParams[$sParamName2] = $aMatches[2];
  2089. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  2090. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  2091. break;
  2092. case 'greater than':
  2093. case 'greater than or equal':
  2094. case 'less than':
  2095. case 'less than or equal':
  2096. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  2097. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  2098. $oRightExpr = new VariableExpression($sParamName);
  2099. $aParams[$sParamName] = $aMatches[1];
  2100. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  2101. break;
  2102. default:
  2103. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  2104. }
  2105. return $oNewCondition;
  2106. }
  2107. }
  2108. /**
  2109. * Store a duration as a number of seconds
  2110. *
  2111. * @package iTopORM
  2112. */
  2113. class AttributeDuration extends AttributeInteger
  2114. {
  2115. public function GetEditClass() {return "Duration";}
  2116. protected function GetSQLCol() {return "INT(11) UNSIGNED";}
  2117. public function GetNullValue() {return '0';}
  2118. public function GetDefaultValue()
  2119. {
  2120. return 0;
  2121. }
  2122. public function MakeRealValue($proposedValue, $oHostObj)
  2123. {
  2124. if (is_null($proposedValue)) return null;
  2125. if (!is_numeric($proposedValue)) return null;
  2126. if ( ((int)$proposedValue) < 0) return null;
  2127. return (int)$proposedValue;
  2128. }
  2129. public function ScalarToSQL($value)
  2130. {
  2131. if (is_null($value))
  2132. {
  2133. return null;
  2134. }
  2135. return $value;
  2136. }
  2137. public function GetAsHTML($value, $oHostObject = null)
  2138. {
  2139. return Str::pure2html(self::FormatDuration($value));
  2140. }
  2141. static function FormatDuration($duration)
  2142. {
  2143. $aDuration = self::SplitDuration($duration);
  2144. $sResult = '';
  2145. if ($duration < 60)
  2146. {
  2147. // Less than 1 min
  2148. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  2149. }
  2150. else if ($duration < 3600)
  2151. {
  2152. // less than 1 hour, display it in minutes/seconds
  2153. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  2154. }
  2155. else if ($duration < 86400)
  2156. {
  2157. // Less than 1 day, display it in hours/minutes/seconds
  2158. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2159. }
  2160. else
  2161. {
  2162. // more than 1 day, display it in days/hours/minutes/seconds
  2163. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2164. }
  2165. return $sResult;
  2166. }
  2167. static function SplitDuration($duration)
  2168. {
  2169. $duration = (int) $duration;
  2170. $days = floor($duration / 86400);
  2171. $hours = floor(($duration - (86400*$days)) / 3600);
  2172. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2173. $seconds = ($duration % 60); // modulo
  2174. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  2175. }
  2176. }
  2177. /**
  2178. * Map a date+time column to an attribute
  2179. *
  2180. * @package iTopORM
  2181. */
  2182. class AttributeDate extends AttributeDateTime
  2183. {
  2184. const MYDATEFORMAT = "Y-m-d";
  2185. static protected function GetDateFormat()
  2186. {
  2187. return "Y-m-d";
  2188. }
  2189. static protected function ListExpectedParams()
  2190. {
  2191. return parent::ListExpectedParams();
  2192. //return array_merge(parent::ListExpectedParams(), array());
  2193. }
  2194. public function GetEditClass() {return "Date";}
  2195. protected function GetSQLCol() {return "DATE";}
  2196. public function GetValidationPattern()
  2197. {
  2198. 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)))$";
  2199. }
  2200. }
  2201. /**
  2202. * A dead line stored as a date & time
  2203. * The only difference with the DateTime attribute is the display:
  2204. * relative to the current time
  2205. */
  2206. class AttributeDeadline extends AttributeDateTime
  2207. {
  2208. public function GetAsHTML($value, $oHostObject = null)
  2209. {
  2210. $sResult = '';
  2211. if ($value !== null)
  2212. {
  2213. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  2214. $sDate = parent::GetAsHTML($value, $oHostObject);
  2215. $difference = $iValue - time();
  2216. if ($difference >= 0)
  2217. {
  2218. $sDifference = self::FormatDuration($difference);
  2219. }
  2220. else
  2221. {
  2222. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  2223. }
  2224. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  2225. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  2226. }
  2227. return $sResult;
  2228. }
  2229. static function FormatDuration($duration)
  2230. {
  2231. $days = floor($duration / 86400);
  2232. $hours = floor(($duration - (86400*$days)) / 3600);
  2233. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2234. $sResult = '';
  2235. if ($duration < 60)
  2236. {
  2237. // Less than 1 min
  2238. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  2239. }
  2240. else if ($duration < 3600)
  2241. {
  2242. // less than 1 hour, display it in minutes
  2243. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  2244. }
  2245. else if ($duration < 86400)
  2246. {
  2247. // Less that 1 day, display it in hours/minutes
  2248. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  2249. }
  2250. else
  2251. {
  2252. // Less that 1 day, display it in hours/minutes
  2253. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  2254. }
  2255. return $sResult;
  2256. }
  2257. }
  2258. /**
  2259. * Map a foreign key to an attribute
  2260. * AttributeExternalKey and AttributeExternalField may be an external key
  2261. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  2262. * where an AttributeExternalField corresponds to a column into another table (class)
  2263. *
  2264. * @package iTopORM
  2265. */
  2266. class AttributeExternalKey extends AttributeDBFieldVoid
  2267. {
  2268. static protected function ListExpectedParams()
  2269. {
  2270. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  2271. }
  2272. public function GetEditClass() {return "ExtKey";}
  2273. protected function GetSQLCol() {return "INT(11)";}
  2274. public function RequiresIndex()
  2275. {
  2276. return true;
  2277. }
  2278. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  2279. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  2280. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2281. public function GetKeyAttCode() {return $this->GetCode();}
  2282. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  2283. public function GetDefaultValue() {return 0;}
  2284. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  2285. public function GetBasicFilterOperators()
  2286. {
  2287. return parent::GetBasicFilterOperators();
  2288. }
  2289. public function GetBasicFilterLooseOperator()
  2290. {
  2291. return parent::GetBasicFilterLooseOperator();
  2292. }
  2293. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2294. {
  2295. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2296. }
  2297. // overloaded here so that an ext key always have the answer to
  2298. // "what are your possible values?"
  2299. public function GetValuesDef()
  2300. {
  2301. $oValSetDef = $this->Get("allowed_values");
  2302. if (!$oValSetDef)
  2303. {
  2304. // Let's propose every existing value
  2305. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2306. }
  2307. return $oValSetDef;
  2308. }
  2309. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2310. {
  2311. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  2312. try
  2313. {
  2314. return parent::GetAllowedValues($aArgs, $sContains);
  2315. }
  2316. catch (MissingQueryArgument $e)
  2317. {
  2318. // Some required arguments could not be found, enlarge to any existing value
  2319. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2320. return $oValSetDef->GetValues($aArgs, $sContains);
  2321. }
  2322. }
  2323. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2324. {
  2325. $oValSetDef = $this->GetValuesDef();
  2326. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2327. return $oSet;
  2328. }
  2329. public function GetDeletionPropagationOption()
  2330. {
  2331. return $this->Get("on_target_delete");
  2332. }
  2333. public function GetNullValue()
  2334. {
  2335. return 0;
  2336. }
  2337. public function IsNull($proposedValue)
  2338. {
  2339. return ($proposedValue == 0);
  2340. }
  2341. public function MakeRealValue($proposedValue, $oHostObj)
  2342. {
  2343. if (is_null($proposedValue)) return 0;
  2344. if ($proposedValue === '') return 0;
  2345. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  2346. return (int)$proposedValue;
  2347. }
  2348. public function GetMaximumComboLength()
  2349. {
  2350. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  2351. }
  2352. public function GetMinAutoCompleteChars()
  2353. {
  2354. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  2355. }
  2356. public function AllowTargetCreation()
  2357. {
  2358. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  2359. }
  2360. }
  2361. /**
  2362. * Special kind of External Key to manage a hierarchy of objects
  2363. */
  2364. class AttributeHierarchicalKey extends AttributeExternalKey
  2365. {
  2366. protected $m_sTargetClass;
  2367. static protected function ListExpectedParams()
  2368. {
  2369. $aParams = parent::ListExpectedParams();
  2370. $idx = array_search('targetclass', $aParams);
  2371. unset($aParams[$idx]);
  2372. $idx = array_search('jointype', $aParams);
  2373. unset($aParams[$idx]);
  2374. return $aParams; // TODO: mettre les bons parametres ici !!
  2375. }
  2376. public function GetEditClass() {return "ExtKey";}
  2377. public function RequiresIndex()
  2378. {
  2379. return true;
  2380. }
  2381. /*
  2382. * The target class is the class for which the attribute has been defined first
  2383. */
  2384. public function SetHostClass($sHostClass)
  2385. {
  2386. if (!isset($this->m_sTargetClass))
  2387. {
  2388. $this->m_sTargetClass = $sHostClass;
  2389. }
  2390. parent::SetHostClass($sHostClass);
  2391. }
  2392. public function IsHierarchicalKey() {return true;}
  2393. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  2394. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2395. public function GetKeyAttCode() {return $this->GetCode();}
  2396. public function GetBasicFilterOperators()
  2397. {
  2398. return parent::GetBasicFilterOperators();
  2399. }
  2400. public function GetBasicFilterLooseOperator()
  2401. {
  2402. return parent::GetBasicFilterLooseOperator();
  2403. }
  2404. public function GetSQLColumns()
  2405. {
  2406. $aColumns = array();
  2407. $aColumns[$this->GetCode()] = 'INT(11)';
  2408. $aColumns[$this->GetSQLLeft()] = 'INT(11)';
  2409. $aColumns[$this->GetSQLRight()] = 'INT(11)';
  2410. return $aColumns;
  2411. }
  2412. public function GetSQLRight()
  2413. {
  2414. return $this->GetCode().'_right';
  2415. }
  2416. public function GetSQLLeft()
  2417. {
  2418. return $this->GetCode().'_left';
  2419. }
  2420. public function GetSQLValues($value)
  2421. {
  2422. if (!is_array($value))
  2423. {
  2424. $aValues[$this->GetCode()] = $value;
  2425. }
  2426. else
  2427. {
  2428. $aValues = array();
  2429. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  2430. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  2431. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  2432. }
  2433. return $aValues;
  2434. }
  2435. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2436. {
  2437. if (array_key_exists('this', $aArgs))
  2438. {
  2439. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2440. // "under" themselves
  2441. $iRootId = $aArgs['this']->GetKey();
  2442. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2443. {
  2444. $oValSetDef = $this->GetValuesDef();
  2445. $sClass = $this->m_sTargetClass;
  2446. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2447. $oValSetDef->AddCondition($oFilter);
  2448. }
  2449. }
  2450. else
  2451. {
  2452. return parent::GetAllowedValues($aArgs, $sContains);
  2453. }
  2454. }
  2455. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2456. {
  2457. $oValSetDef = $this->GetValuesDef();
  2458. if (array_key_exists('this', $aArgs))
  2459. {
  2460. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2461. // "under" themselves
  2462. $iRootId = $aArgs['this']->GetKey();
  2463. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2464. {
  2465. $aValuesSetDef = $this->GetValuesDef();
  2466. $sClass = $this->m_sTargetClass;
  2467. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2468. $oValSetDef->AddCondition($oFilter);
  2469. }
  2470. }
  2471. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2472. return $oSet;
  2473. }
  2474. }
  2475. /**
  2476. * An attribute which corresponds to an external key (direct or indirect)
  2477. *
  2478. * @package iTopORM
  2479. */
  2480. class AttributeExternalField extends AttributeDefinition
  2481. {
  2482. static protected function ListExpectedParams()
  2483. {
  2484. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  2485. }
  2486. public function GetEditClass() {return "ExtField";}
  2487. public function GetFinalAttDef()
  2488. {
  2489. $oExtAttDef = $this->GetExtAttDef();
  2490. return $oExtAttDef->GetFinalAttDef();
  2491. }
  2492. protected function GetSQLCol()
  2493. {
  2494. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  2495. $oExtAttDef = $this->GetExtAttDef();
  2496. return $oExtAttDef->GetSQLCol();
  2497. }
  2498. public function GetSQLExpressions($sPrefix = '')
  2499. {
  2500. if ($sPrefix == '')
  2501. {
  2502. return array('' => $this->GetCode());
  2503. }
  2504. else
  2505. {
  2506. return $sPrefix;
  2507. }
  2508. }
  2509. public function GetLabel($sDefault = null)
  2510. {
  2511. $sLabel = parent::GetLabel('');
  2512. if (strlen($sLabel) == 0)
  2513. {
  2514. $oRemoteAtt = $this->GetExtAttDef();
  2515. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  2516. }
  2517. return $sLabel;
  2518. }
  2519. public function GetDescription($sDefault = null)
  2520. {
  2521. $sLabel = parent::GetDescription('');
  2522. if (strlen($sLabel) == 0)
  2523. {
  2524. $oRemoteAtt = $this->GetExtAttDef();
  2525. $sLabel = $oRemoteAtt->GetDescription('');
  2526. }
  2527. return $sLabel;
  2528. }
  2529. public function GetHelpOnEdition($sDefault = null)
  2530. {
  2531. $sLabel = parent::GetHelpOnEdition('');
  2532. if (strlen($sLabel) == 0)
  2533. {
  2534. $oRemoteAtt = $this->GetExtAttDef();
  2535. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  2536. }
  2537. return $sLabel;
  2538. }
  2539. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  2540. {
  2541. switch($iType)
  2542. {
  2543. case EXTKEY_ABSOLUTE:
  2544. // see further
  2545. $oRemoteAtt = $this->GetExtAttDef();
  2546. return $oRemoteAtt->IsExternalKey($iType);
  2547. case EXTKEY_RELATIVE:
  2548. return false;
  2549. default:
  2550. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2551. }
  2552. }
  2553. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  2554. {
  2555. return $this->GetKeyAttDef($iType)->GetTargetClass();
  2556. }
  2557. public function IsExternalField() {return true;}
  2558. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2559. public function GetExtAttCode() {return $this->Get("target_attcode");}
  2560. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  2561. {
  2562. switch($iType)
  2563. {
  2564. case EXTKEY_ABSOLUTE:
  2565. // see further
  2566. $oRemoteAtt = $this->GetExtAttDef();
  2567. if ($oRemoteAtt->IsExternalField())
  2568. {
  2569. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  2570. }
  2571. else if ($oRemoteAtt->IsExternalKey())
  2572. {
  2573. return $oRemoteAtt;
  2574. }
  2575. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  2576. case EXTKEY_RELATIVE:
  2577. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  2578. default:
  2579. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2580. }
  2581. }
  2582. public function GetExtAttDef()
  2583. {
  2584. $oKeyAttDef = $this->GetKeyAttDef();
  2585. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  2586. if (!is_object($oExtAttDef)) throw new CoreException("Invalid external field ".$this->GetCode()." in class ".$this->GetHostClass().". The class ".$oKeyAttDef->GetTargetClass()." has no attribute ".$this->Get("target_attcode"));
  2587. return $oExtAttDef;
  2588. }
  2589. public function GetSQLExpr()
  2590. {
  2591. $oExtAttDef = $this->GetExtAttDef();
  2592. return $oExtAttDef->GetSQLExpr();
  2593. }
  2594. public function GetDefaultValue()
  2595. {
  2596. $oExtAttDef = $this->GetExtAttDef();
  2597. return $oExtAttDef->GetDefaultValue();
  2598. }
  2599. public function IsNullAllowed()
  2600. {
  2601. $oExtAttDef = $this->GetExtAttDef();
  2602. return $oExtAttDef->IsNullAllowed();
  2603. }
  2604. public function IsScalar()
  2605. {
  2606. $oExtAttDef = $this->GetExtAttDef();
  2607. return $oExtAttDef->IsScalar();
  2608. }
  2609. public function GetFilterDefinitions()
  2610. {
  2611. return array($this->GetCode() => new FilterFromAttribute($this));
  2612. }
  2613. public function GetBasicFilterOperators()
  2614. {
  2615. $oExtAttDef = $this->GetExtAttDef();
  2616. return $oExtAttDef->GetBasicFilterOperators();
  2617. }
  2618. public function GetBasicFilterLooseOperator()
  2619. {
  2620. $oExtAttDef = $this->GetExtAttDef();
  2621. return $oExtAttDef->GetBasicFilterLooseOperator();
  2622. }
  2623. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2624. {
  2625. $oExtAttDef = $this->GetExtAttDef();
  2626. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  2627. }
  2628. public function GetNullValue()
  2629. {
  2630. $oExtAttDef = $this->GetExtAttDef();
  2631. return $oExtAttDef->GetNullValue();
  2632. }
  2633. public function IsNull($proposedValue)
  2634. {
  2635. $oExtAttDef = $this->GetExtAttDef();
  2636. return $oExtAttDef->IsNull($proposedValue);
  2637. }
  2638. public function MakeRealValue($proposedValue, $oHostObj)
  2639. {
  2640. $oExtAttDef = $this->GetExtAttDef();
  2641. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  2642. }
  2643. public function ScalarToSQL($value)
  2644. {
  2645. // This one could be used in case of filtering only
  2646. $oExtAttDef = $this->GetExtAttDef();
  2647. return $oExtAttDef->ScalarToSQL($value);
  2648. }
  2649. // Do not overload GetSQLExpression here because this is handled in the joins
  2650. //public function GetSQLExpressions($sPrefix = '') {return array();}
  2651. // Here, we get the data...
  2652. public function FromSQLToValue($aCols, $sPrefix = '')
  2653. {
  2654. $oExtAttDef = $this->GetExtAttDef();
  2655. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  2656. }
  2657. public function GetAsHTML($value, $oHostObject = null)
  2658. {
  2659. $oExtAttDef = $this->GetExtAttDef();
  2660. return $oExtAttDef->GetAsHTML($value);
  2661. }
  2662. public function GetAsXML($value, $oHostObject = null)
  2663. {
  2664. $oExtAttDef = $this->GetExtAttDef();
  2665. return $oExtAttDef->GetAsXML($value);
  2666. }
  2667. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null)
  2668. {
  2669. $oExtAttDef = $this->GetExtAttDef();
  2670. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  2671. }
  2672. }
  2673. /**
  2674. * Map a varchar column to an URL (formats the ouput in HMTL)
  2675. *
  2676. * @package iTopORM
  2677. */
  2678. class AttributeURL extends AttributeString
  2679. {
  2680. static protected function ListExpectedParams()
  2681. {
  2682. //return parent::ListExpectedParams();
  2683. return array_merge(parent::ListExpectedParams(), array("target"));
  2684. }
  2685. public function GetEditClass() {return "String";}
  2686. public function GetAsHTML($sValue, $oHostObject = null)
  2687. {
  2688. $sTarget = $this->Get("target");
  2689. if (empty($sTarget)) $sTarget = "_blank";
  2690. $sLabel = Str::pure2html($sValue);
  2691. if (strlen($sLabel) > 40)
  2692. {
  2693. // Truncate the length to about 40 characters, by removing the middle
  2694. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  2695. }
  2696. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  2697. }
  2698. public function GetValidationPattern()
  2699. {
  2700. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  2701. }
  2702. }
  2703. /**
  2704. * A blob is an ormDocument, it is stored as several columns in the database
  2705. *
  2706. * @package iTopORM
  2707. */
  2708. class AttributeBlob extends AttributeDefinition
  2709. {
  2710. static protected function ListExpectedParams()
  2711. {
  2712. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2713. }
  2714. public function GetEditClass() {return "Document";}
  2715. public function IsDirectField() {return true;}
  2716. public function IsScalar() {return true;}
  2717. public function IsWritable() {return true;}
  2718. public function GetDefaultValue() {return "";}
  2719. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2720. // Facilitate things: allow the user to Set the value from a string
  2721. public function MakeRealValue($proposedValue, $oHostObj)
  2722. {
  2723. if (!is_object($proposedValue))
  2724. {
  2725. return new ormDocument($proposedValue, 'text/plain');
  2726. }
  2727. return $proposedValue;
  2728. }
  2729. public function GetSQLExpressions($sPrefix = '')
  2730. {
  2731. if ($sPrefix == '')
  2732. {
  2733. $sPrefix = $this->GetCode();
  2734. }
  2735. $aColumns = array();
  2736. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2737. $aColumns[''] = $sPrefix.'_mimetype';
  2738. $aColumns['_data'] = $sPrefix.'_data';
  2739. $aColumns['_filename'] = $sPrefix.'_filename';
  2740. return $aColumns;
  2741. }
  2742. public function FromSQLToValue($aCols, $sPrefix = '')
  2743. {
  2744. if (!isset($aCols[$sPrefix]))
  2745. {
  2746. $sAvailable = implode(', ', array_keys($aCols));
  2747. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2748. }
  2749. $sMimeType = $aCols[$sPrefix];
  2750. if (!isset($aCols[$sPrefix.'_data']))
  2751. {
  2752. $sAvailable = implode(', ', array_keys($aCols));
  2753. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  2754. }
  2755. $data = $aCols[$sPrefix.'_data'];
  2756. if (!isset($aCols[$sPrefix.'_filename']))
  2757. {
  2758. $sAvailable = implode(', ', array_keys($aCols));
  2759. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  2760. }
  2761. $sFileName = $aCols[$sPrefix.'_filename'];
  2762. $value = new ormDocument($data, $sMimeType, $sFileName);
  2763. return $value;
  2764. }
  2765. public function GetSQLValues($value)
  2766. {
  2767. // #@# Optimization: do not load blobs anytime
  2768. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2769. // using memory in case a temporary table has to be created
  2770. // (temporary tables created on disk)
  2771. // We will have to remove the blobs from the list of attributes when doing the select
  2772. // then the use of Get() should finalize the load
  2773. if ($value instanceOf ormDocument)
  2774. {
  2775. $aValues = array();
  2776. $aValues[$this->GetCode().'_data'] = $value->GetData();
  2777. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  2778. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  2779. }
  2780. else
  2781. {
  2782. $aValues = array();
  2783. $aValues[$this->GetCode().'_data'] = '';
  2784. $aValues[$this->GetCode().'_mimetype'] = '';
  2785. $aValues[$this->GetCode().'_filename'] = '';
  2786. }
  2787. return $aValues;
  2788. }
  2789. public function GetSQLColumns()
  2790. {
  2791. $aColumns = array();
  2792. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  2793. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  2794. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  2795. return $aColumns;
  2796. }
  2797. public function GetFilterDefinitions()
  2798. {
  2799. return array();
  2800. // still not working... see later...
  2801. return array(
  2802. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  2803. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  2804. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  2805. );
  2806. }
  2807. public function GetBasicFilterOperators()
  2808. {
  2809. return array();
  2810. }
  2811. public function GetBasicFilterLooseOperator()
  2812. {
  2813. return '=';
  2814. }
  2815. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2816. {
  2817. return 'true';
  2818. }
  2819. public function GetAsHTML($value, $oHostObject = null)
  2820. {
  2821. if (is_object($value))
  2822. {
  2823. return $value->GetAsHTML();
  2824. }
  2825. }
  2826. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2827. {
  2828. return ''; // Not exportable in CSV !
  2829. }
  2830. public function GetAsXML($value, $oHostObject = null)
  2831. {
  2832. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  2833. }
  2834. }
  2835. /**
  2836. * One way encrypted (hashed) password
  2837. */
  2838. class AttributeOneWayPassword extends AttributeDefinition
  2839. {
  2840. static protected function ListExpectedParams()
  2841. {
  2842. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2843. }
  2844. public function GetEditClass() {return "One Way Password";}
  2845. public function IsDirectField() {return true;}
  2846. public function IsScalar() {return true;}
  2847. public function IsWritable() {return true;}
  2848. public function GetDefaultValue() {return "";}
  2849. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2850. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  2851. public function MakeRealValue($proposedValue, $oHostObj)
  2852. {
  2853. $oPassword = $proposedValue;
  2854. if (!is_object($oPassword))
  2855. {
  2856. $oPassword = new ormPassword('', '');
  2857. $oPassword->SetPassword($proposedValue);
  2858. }
  2859. return $oPassword;
  2860. }
  2861. public function GetSQLExpressions($sPrefix = '')
  2862. {
  2863. if ($sPrefix == '')
  2864. {
  2865. $sPrefix = $this->GetCode();
  2866. }
  2867. $aColumns = array();
  2868. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2869. $aColumns[''] = $sPrefix.'_hash';
  2870. $aColumns['_salt'] = $sPrefix.'_salt';
  2871. return $aColumns;
  2872. }
  2873. public function FromSQLToValue($aCols, $sPrefix = '')
  2874. {
  2875. if (!isset($aCols[$sPrefix]))
  2876. {
  2877. $sAvailable = implode(', ', array_keys($aCols));
  2878. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2879. }
  2880. $hashed = $aCols[$sPrefix];
  2881. if (!isset($aCols[$sPrefix.'_salt']))
  2882. {
  2883. $sAvailable = implode(', ', array_keys($aCols));
  2884. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  2885. }
  2886. $sSalt = $aCols[$sPrefix.'_salt'];
  2887. $value = new ormPassword($hashed, $sSalt);
  2888. return $value;
  2889. }
  2890. public function GetSQLValues($value)
  2891. {
  2892. // #@# Optimization: do not load blobs anytime
  2893. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2894. // using memory in case a temporary table has to be created
  2895. // (temporary tables created on disk)
  2896. // We will have to remove the blobs from the list of attributes when doing the select
  2897. // then the use of Get() should finalize the load
  2898. if ($value instanceOf ormPassword)
  2899. {
  2900. $aValues = array();
  2901. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  2902. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  2903. }
  2904. else
  2905. {
  2906. $aValues = array();
  2907. $aValues[$this->GetCode().'_hash'] = '';
  2908. $aValues[$this->GetCode().'_salt'] = '';
  2909. }
  2910. return $aValues;
  2911. }
  2912. public function GetSQLColumns()
  2913. {
  2914. $aColumns = array();
  2915. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  2916. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  2917. return $aColumns;
  2918. }
  2919. public function GetImportColumns()
  2920. {
  2921. $aColumns = array();
  2922. $aColumns[$this->GetCode()] = 'TINYTEXT';
  2923. return $aColumns;
  2924. }
  2925. public function FromImportToValue($aCols, $sPrefix = '')
  2926. {
  2927. if (!isset($aCols[$sPrefix]))
  2928. {
  2929. $sAvailable = implode(', ', array_keys($aCols));
  2930. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2931. }
  2932. $sClearPwd = $aCols[$sPrefix];
  2933. $oPassword = new ormPassword('', '');
  2934. $oPassword->SetPassword($sClearPwd);
  2935. return $oPassword;
  2936. }
  2937. public function GetFilterDefinitions()
  2938. {
  2939. return array();
  2940. // still not working... see later...
  2941. }
  2942. public function GetBasicFilterOperators()
  2943. {
  2944. return array();
  2945. }
  2946. public function GetBasicFilterLooseOperator()
  2947. {
  2948. return '=';
  2949. }
  2950. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2951. {
  2952. return 'true';
  2953. }
  2954. public function GetAsHTML($value, $oHostObject = null)
  2955. {
  2956. if (is_object($value))
  2957. {
  2958. return $value->GetAsHTML();
  2959. }
  2960. }
  2961. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2962. {
  2963. return ''; // Not exportable in CSV
  2964. }
  2965. public function GetAsXML($value, $oHostObject = null)
  2966. {
  2967. return ''; // Not exportable in XML
  2968. }
  2969. }
  2970. // Indexed array having two dimensions
  2971. class AttributeTable extends AttributeText
  2972. {
  2973. public function GetEditClass() {return "Text";}
  2974. protected function GetSQLCol() {return "TEXT";}
  2975. public function GetMaxSize()
  2976. {
  2977. return null;
  2978. }
  2979. // Facilitate things: allow the user to Set the value from a string
  2980. public function MakeRealValue($proposedValue, $oHostObj)
  2981. {
  2982. if (!is_array($proposedValue))
  2983. {
  2984. return array(0 => array(0 => $proposedValue));
  2985. }
  2986. return $proposedValue;
  2987. }
  2988. public function FromSQLToValue($aCols, $sPrefix = '')
  2989. {
  2990. try
  2991. {
  2992. $value = @unserialize($aCols[$sPrefix.'']);
  2993. if ($value === false)
  2994. {
  2995. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  2996. }
  2997. }
  2998. catch(Exception $e)
  2999. {
  3000. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  3001. }
  3002. return $value;
  3003. }
  3004. public function GetSQLValues($value)
  3005. {
  3006. $aValues = array();
  3007. $aValues[$this->Get("sql")] = serialize($value);
  3008. return $aValues;
  3009. }
  3010. public function GetAsHTML($value, $oHostObject = null)
  3011. {
  3012. if (!is_array($value))
  3013. {
  3014. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  3015. }
  3016. if (count($value) == 0)
  3017. {
  3018. return "";
  3019. }
  3020. $sRes = "<TABLE class=\"listResults\">";
  3021. $sRes .= "<TBODY>";
  3022. foreach($value as $iRow => $aRawData)
  3023. {
  3024. $sRes .= "<TR>";
  3025. foreach ($aRawData as $iCol => $cell)
  3026. {
  3027. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  3028. $sRes .= "<TD>$sCell</TD>";
  3029. }
  3030. $sRes .= "</TR>";
  3031. }
  3032. $sRes .= "</TBODY>";
  3033. $sRes .= "</TABLE>";
  3034. return $sRes;
  3035. }
  3036. }
  3037. // The PHP value is a hash array, it is stored as a TEXT column
  3038. class AttributePropertySet extends AttributeTable
  3039. {
  3040. public function GetEditClass() {return "Text";}
  3041. protected function GetSQLCol() {return "TEXT";}
  3042. // Facilitate things: allow the user to Set the value from a string
  3043. public function MakeRealValue($proposedValue, $oHostObj)
  3044. {
  3045. if (!is_array($proposedValue))
  3046. {
  3047. return array('?' => (string)$proposedValue);
  3048. }
  3049. return $proposedValue;
  3050. }
  3051. public function GetAsHTML($value, $oHostObject = null)
  3052. {
  3053. if (!is_array($value))
  3054. {
  3055. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  3056. }
  3057. if (count($value) == 0)
  3058. {
  3059. return "";
  3060. }
  3061. $sRes = "<TABLE class=\"listResults\">";
  3062. $sRes .= "<TBODY>";
  3063. foreach($value as $sProperty => $sValue)
  3064. {
  3065. $sRes .= "<TR>";
  3066. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  3067. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  3068. $sRes .= "</TR>";
  3069. }
  3070. $sRes .= "</TBODY>";
  3071. $sRes .= "</TABLE>";
  3072. return $sRes;
  3073. }
  3074. }
  3075. /**
  3076. * The attribute dedicated to the friendly name automatic attribute (not written)
  3077. *
  3078. * @package iTopORM
  3079. */
  3080. class AttributeComputedFieldVoid extends AttributeDefinition
  3081. {
  3082. static protected function ListExpectedParams()
  3083. {
  3084. return array_merge(parent::ListExpectedParams(), array());
  3085. }
  3086. public function GetEditClass() {return "";}
  3087. public function GetValuesDef() {return null;}
  3088. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  3089. public function IsDirectField() {return true;}
  3090. public function IsScalar() {return true;}
  3091. public function IsWritable() {return false;}
  3092. public function GetSQLExpr() {return null;}
  3093. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  3094. public function IsNullAllowed() {return false;}
  3095. //
  3096. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  3097. public function GetSQLExpressions($sPrefix = '')
  3098. {
  3099. if ($sPrefix == '')
  3100. {
  3101. $sPrefix = $this->GetCode();
  3102. }
  3103. return array('' => $sPrefix);
  3104. }
  3105. public function FromSQLToValue($aCols, $sPrefix = '')
  3106. {
  3107. return null;
  3108. }
  3109. public function GetSQLValues($value)
  3110. {
  3111. return array();
  3112. }
  3113. public function GetSQLColumns()
  3114. {
  3115. return array();
  3116. }
  3117. public function GetFilterDefinitions()
  3118. {
  3119. return array($this->GetCode() => new FilterFromAttribute($this));
  3120. }
  3121. public function GetBasicFilterOperators()
  3122. {
  3123. return array();
  3124. }
  3125. public function GetBasicFilterLooseOperator()
  3126. {
  3127. return "=";
  3128. }
  3129. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3130. {
  3131. $sQValue = CMDBSource::Quote($value);
  3132. switch ($sOpCode)
  3133. {
  3134. case '!=':
  3135. return $this->GetSQLExpr()." != $sQValue";
  3136. break;
  3137. case '=':
  3138. default:
  3139. return $this->GetSQLExpr()." = $sQValue";
  3140. }
  3141. }
  3142. }
  3143. /**
  3144. * The attribute dedicated to the friendly name automatic attribute (not written)
  3145. *
  3146. * @package iTopORM
  3147. */
  3148. class AttributeFriendlyName extends AttributeComputedFieldVoid
  3149. {
  3150. public function __construct($sCode, $sExtKeyAttCode)
  3151. {
  3152. $this->m_sCode = $sCode;
  3153. $aParams = array();
  3154. // $aParams["is_null_allowed"] = false,
  3155. $aParams["default_value"] = '';
  3156. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  3157. parent::__construct($sCode, $aParams);
  3158. $this->m_sValue = $this->Get("default_value");
  3159. }
  3160. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  3161. public function GetExtAttCode() {return 'friendlyname';}
  3162. public function GetLabel($sDefault = null)
  3163. {
  3164. $sLabel = parent::GetLabel('');
  3165. if (strlen($sLabel) == 0)
  3166. {
  3167. $sKeyAttCode = $this->Get("extkey_attcode");
  3168. if ($sKeyAttCode == 'id')
  3169. {
  3170. return Dict::S('Core:FriendlyName-Label');
  3171. }
  3172. else
  3173. {
  3174. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  3175. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  3176. }
  3177. }
  3178. return $sLabel;
  3179. }
  3180. public function GetDescription($sDefault = null)
  3181. {
  3182. $sLabel = parent::GetDescription('');
  3183. if (strlen($sLabel) == 0)
  3184. {
  3185. $sKeyAttCode = $this->Get("extkey_attcode");
  3186. if ($sKeyAttCode == 'id')
  3187. {
  3188. return Dict::S('Core:FriendlyName-Description');
  3189. }
  3190. else
  3191. {
  3192. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  3193. $sLabel = $oExtKeyAttDef->GetDescription('');
  3194. }
  3195. }
  3196. return $sLabel;
  3197. }
  3198. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  3199. protected function GetSQLCol() {return "";}
  3200. public function FromSQLToValue($aCols, $sPrefix = '')
  3201. {
  3202. $sValue = $aCols[$sPrefix];
  3203. return $sValue;
  3204. }
  3205. /**
  3206. * Encrypt the value before storing it in the database
  3207. */
  3208. public function GetSQLValues($value)
  3209. {
  3210. return array();
  3211. }
  3212. public function IsWritable()
  3213. {
  3214. return false;
  3215. }
  3216. public function IsDirectField()
  3217. {
  3218. return false;
  3219. }
  3220. public function SetFixedValue($sValue)
  3221. {
  3222. $this->m_sValue = $sValue;
  3223. }
  3224. public function GetDefaultValue()
  3225. {
  3226. return $this->m_sValue;
  3227. }
  3228. public function GetAsHTML($sValue, $oHostObject = null)
  3229. {
  3230. return Str::pure2html((string)$sValue);
  3231. }
  3232. }
  3233. ?>