attributedef.class.inc.php 108 KB

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