attributedef.class.inc.php 99 KB

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