dbobject.class.php 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * All objects to be displayed in the application (either as a list or as details)
  20. * must implement this interface.
  21. */
  22. interface iDisplay
  23. {
  24. /**
  25. * Maps the given context parameter name to the appropriate filter/search code for this class
  26. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  27. * @return string Filter code, i.e. 'customer_id'
  28. */
  29. public static function MapContextParam($sContextParam);
  30. /**
  31. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  32. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  33. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  34. * To Be overridden by derived classes
  35. * @param void
  36. * @return String The desired higlight class for the object/row
  37. */
  38. public function GetHilightClass();
  39. /**
  40. * Returns the relative path to the page that handles the display of the object
  41. * @return string
  42. */
  43. public static function GetUIPage();
  44. /**
  45. * Displays the details of the object
  46. */
  47. public function DisplayDetails(WebPage $oPage, $bEditMode = false);
  48. }
  49. /**
  50. * Class dbObject: the root of persistent classes
  51. *
  52. * @copyright Copyright (C) 2010-2016 Combodo SARL
  53. * @license http://opensource.org/licenses/AGPL-3.0
  54. */
  55. require_once('metamodel.class.php');
  56. require_once('deletionplan.class.inc.php');
  57. require_once('mutex.class.inc.php');
  58. /**
  59. * A persistent object, as defined by the metamodel
  60. *
  61. * @package iTopORM
  62. */
  63. abstract class DBObject implements iDisplay
  64. {
  65. private static $m_aMemoryObjectsByClass = array();
  66. private static $m_aBulkInsertItems = array(); // class => array of ('table' => array of (array of <sql_value>))
  67. private static $m_aBulkInsertCols = array(); // class => array of ('table' => array of <sql_column>)
  68. private static $m_bBulkInsert = false;
  69. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  70. private $m_iKey = null;
  71. private $m_aCurrValues = array();
  72. protected $m_aOrigValues = array();
  73. protected $m_aExtendedData = null;
  74. private $m_bDirty = false; // Means: "a modification is ongoing"
  75. // The object may have incorrect external keys, then any attempt of reload must be avoided
  76. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  77. // if null, then the check has to be performed again to know the status
  78. protected $m_bSecurityIssue = null;
  79. protected $m_aCheckIssues = null;
  80. protected $m_aDeleteIssues = null;
  81. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  82. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  83. protected $m_aTouchedAtt = array(); // list of (potentially) modified sAttCodes
  84. protected $m_aModifiedAtt = array(); // real modification status: for each attCode can be: unset => don't know, true => modified, false => not modified (the same value as the original value was set)
  85. protected $m_aSynchroData = null; // Set of Synch data related to this object
  86. protected $m_sHighlightCode = null;
  87. protected $m_aCallbacks = array();
  88. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  89. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  90. {
  91. if (!empty($aRow))
  92. {
  93. $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  94. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  95. $this->m_aTouchedAtt = array();
  96. $this->m_aModifiedAtt = array();
  97. return;
  98. }
  99. // Creation of a brand new object
  100. //
  101. $this->m_iKey = self::GetNextTempId(get_class($this));
  102. // set default values
  103. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  104. {
  105. $this->m_aCurrValues[$sAttCode] = $this->GetDefaultValue($sAttCode);
  106. $this->m_aOrigValues[$sAttCode] = null;
  107. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  108. {
  109. // This field has to be read from the DB
  110. // Leave the flag unset (optimization)
  111. }
  112. else
  113. {
  114. // No need to trigger a reload for that attribute
  115. // Let's consider it as being already fully loaded
  116. $this->m_aLoadedAtt[$sAttCode] = true;
  117. }
  118. }
  119. }
  120. // Read-only <=> Written once (archive)
  121. public function RegisterAsDirty()
  122. {
  123. // While the object may be written to the DB, it is NOT possible to reload it
  124. // or at least not possible to reload it the same way
  125. $this->m_bDirty = true;
  126. }
  127. public function IsNew()
  128. {
  129. return (!$this->m_bIsInDB);
  130. }
  131. // Returns an Id for memory objects
  132. static protected function GetNextTempId($sClass)
  133. {
  134. $sRootClass = MetaModel::GetRootClass($sClass);
  135. if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
  136. {
  137. self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
  138. }
  139. self::$m_aMemoryObjectsByClass[$sRootClass]++;
  140. return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
  141. }
  142. public function __toString()
  143. {
  144. $sRet = '';
  145. $sClass = get_class($this);
  146. $sRootClass = MetaModel::GetRootClass($sClass);
  147. $iPKey = $this->GetKey();
  148. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  149. $sRet .= "<ul class=\"treeview\">\n";
  150. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  151. {
  152. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  153. }
  154. $sRet .= "</ul>";
  155. return $sRet;
  156. }
  157. // Restore initial values... mmmm, to be discussed
  158. public function DBRevert()
  159. {
  160. $this->Reload();
  161. }
  162. protected function IsFullyLoaded()
  163. {
  164. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  165. {
  166. if (!$oAttDef->LoadInObject()) continue;
  167. if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
  168. {
  169. return false;
  170. }
  171. }
  172. return true;
  173. }
  174. /**
  175. * @param bool $bAllowAllData DEPRECATED: the reload must never fail!
  176. * @throws CoreException
  177. */
  178. public function Reload($bAllowAllData = false)
  179. {
  180. assert($this->m_bIsInDB);
  181. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false /* must be found */, true /* AllowAllData */);
  182. if (empty($aRow))
  183. {
  184. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  185. }
  186. $this->FromRow($aRow);
  187. // Process linked set attributes
  188. //
  189. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  190. {
  191. if (!$oAttDef->IsLinkSet()) continue;
  192. // Load the link information
  193. $sLinkClass = $oAttDef->GetLinkedClass();
  194. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  195. // The class to target is not the current class, because if this is a derived class,
  196. // it may differ from the target class, then things start to become confusing
  197. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  198. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  199. $oMyselfSearch = new DBObjectSearch($sMyClass);
  200. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  201. $oLinkSearch = new DBObjectSearch($sLinkClass);
  202. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  203. if ($oAttDef->IsIndirect())
  204. {
  205. // Join the remote class so that the archive flag will be taken into account
  206. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  207. $oExtKeyToRemote = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToRemote);
  208. $sRemoteClass = $oExtKeyToRemote->GetTargetClass();
  209. if (MetaModel::IsArchivable($sRemoteClass))
  210. {
  211. $oRemoteSearch = new DBObjectSearch($sRemoteClass);
  212. $oLinkSearch->AddCondition_PointingTo($oRemoteSearch, $oAttDef->GetExtKeyToRemote());
  213. }
  214. }
  215. $oLinks = new DBObjectSet($oLinkSearch);
  216. $this->m_aCurrValues[$sAttCode] = $oLinks;
  217. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  218. $this->m_aLoadedAtt[$sAttCode] = true;
  219. }
  220. $this->m_bFullyLoaded = true;
  221. $this->m_aTouchedAtt = array();
  222. $this->m_aModifiedAtt = array();
  223. }
  224. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  225. {
  226. if (strlen($sClassAlias) == 0)
  227. {
  228. // Default to the current class
  229. $sClassAlias = get_class($this);
  230. }
  231. $this->m_iKey = null;
  232. $this->m_bIsInDB = true;
  233. $this->m_aCurrValues = array();
  234. $this->m_aOrigValues = array();
  235. $this->m_aLoadedAtt = array();
  236. $this->m_bCheckStatus = true;
  237. // Get the key
  238. //
  239. $sKeyField = $sClassAlias."id";
  240. if (!array_key_exists($sKeyField, $aRow))
  241. {
  242. // #@# Bug ?
  243. throw new CoreException("Missing key for class '".get_class($this)."'");
  244. }
  245. $iPKey = $aRow[$sKeyField];
  246. if (!self::IsValidPKey($iPKey))
  247. {
  248. if (is_null($iPKey))
  249. {
  250. throw new CoreException("Missing object id in query result (found null)");
  251. }
  252. else
  253. {
  254. throw new CoreException("An object id must be an integer value ($iPKey)");
  255. }
  256. }
  257. $this->m_iKey = $iPKey;
  258. // Build the object from an array of "attCode"=>"value")
  259. //
  260. $bFullyLoaded = true; // ... set to false if any attribute is not found
  261. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  262. {
  263. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  264. }
  265. else
  266. {
  267. $aAttList = $aAttToLoad[$sClassAlias];
  268. }
  269. foreach($aAttList as $sAttCode=>$oAttDef)
  270. {
  271. // Skip links (could not be loaded by the mean of this query)
  272. if ($oAttDef->IsLinkSet()) continue;
  273. if (!$oAttDef->LoadInObject()) continue;
  274. unset($value);
  275. $bIsDefined = false;
  276. if ($oAttDef->LoadFromDB())
  277. {
  278. // Note: we assume that, for a given attribute, if it can be loaded,
  279. // then one column will be found with an empty suffix, the others have a suffix
  280. // Take care: the function isset will return false in case the value is null,
  281. // which is something that could happen on open joins
  282. $sAttRef = $sClassAlias.$sAttCode;
  283. if (array_key_exists($sAttRef, $aRow))
  284. {
  285. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  286. $bIsDefined = true;
  287. }
  288. }
  289. else
  290. {
  291. $value = $oAttDef->ReadValue($this);
  292. $bIsDefined = true;
  293. }
  294. if ($bIsDefined)
  295. {
  296. $this->m_aCurrValues[$sAttCode] = $value;
  297. if (is_object($value))
  298. {
  299. $this->m_aOrigValues[$sAttCode] = clone $value;
  300. }
  301. else
  302. {
  303. $this->m_aOrigValues[$sAttCode] = $value;
  304. }
  305. $this->m_aLoadedAtt[$sAttCode] = true;
  306. }
  307. else
  308. {
  309. // This attribute was expected and not found in the query columns
  310. $bFullyLoaded = false;
  311. }
  312. }
  313. // Load extended data
  314. if ($aExtendedDataSpec != null)
  315. {
  316. $aExtendedDataSpec['table'];
  317. foreach($aExtendedDataSpec['fields'] as $sColumn)
  318. {
  319. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  320. if (array_key_exists($sColRef, $aRow))
  321. {
  322. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  323. }
  324. }
  325. }
  326. return $bFullyLoaded;
  327. }
  328. protected function _Set($sAttCode, $value)
  329. {
  330. $this->m_aCurrValues[$sAttCode] = $value;
  331. $this->m_aTouchedAtt[$sAttCode] = true;
  332. unset($this->m_aModifiedAtt[$sAttCode]);
  333. }
  334. public function Set($sAttCode, $value)
  335. {
  336. if ($sAttCode == 'finalclass')
  337. {
  338. // Ignore it - this attribute is set upon object creation and that's it
  339. return false;
  340. }
  341. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  342. if (!$oAttDef->IsWritable())
  343. {
  344. $sClass = get_class($this);
  345. throw new Exception("Attempting to set the value on the read-only attribute $sClass::$sAttCode");
  346. }
  347. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  348. {
  349. // First time Set is called... ensure that the object gets fully loaded
  350. // Otherwise we would lose the values on a further Reload
  351. // + consistency does not make sense !
  352. $this->Reload();
  353. }
  354. if ($oAttDef->IsExternalKey())
  355. {
  356. if (is_object($value))
  357. {
  358. // Setting an external key with a whole object (instead of just an ID)
  359. // let's initialize also the external fields that depend on it
  360. // (useful when building objects in memory and not from a query)
  361. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  362. {
  363. throw new CoreUnexpectedValue("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
  364. }
  365. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  366. {
  367. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  368. {
  369. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  370. $this->m_aLoadedAtt[$sCode] = true;
  371. }
  372. }
  373. }
  374. else if ($this->m_aCurrValues[$sAttCode] != $value)
  375. {
  376. // Setting an external key, but no any other information is available...
  377. // Invalidate the corresponding fields so that they get reloaded in case they are needed (See Get())
  378. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  379. {
  380. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  381. {
  382. $this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode);
  383. unset($this->m_aLoadedAtt[$sCode]);
  384. }
  385. }
  386. }
  387. }
  388. if($oAttDef->IsLinkSet())
  389. {
  390. if (is_null($value))
  391. {
  392. // Normalize
  393. $value = DBObjectSet::FromScratch($oAttDef->GetLinkedClass());
  394. }
  395. else
  396. {
  397. if ((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  398. {
  399. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  400. }
  401. }
  402. $oObjectSet = $value;
  403. $sSetClass = $oObjectSet->GetClass();
  404. $sLinkClass = $oAttDef->GetLinkedClass();
  405. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  406. if ($sSetClass != $sLinkClass)
  407. {
  408. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  409. }
  410. }
  411. $realvalue = $oAttDef->MakeRealValue($value, $this);
  412. $this->_Set($sAttCode, $realvalue);
  413. foreach (MetaModel::ListMetaAttributes(get_class($this), $sAttCode) as $sMetaAttCode => $oMetaAttDef)
  414. {
  415. $this->_Set($sMetaAttCode, $oMetaAttDef->MapValue($this));
  416. }
  417. // The object has changed, reset caches
  418. $this->m_bCheckStatus = null;
  419. // Make sure we do not reload it anymore... before saving it
  420. $this->RegisterAsDirty();
  421. // This function is eligible as a lifecycle action: returning true upon success is a must
  422. return true;
  423. }
  424. public function SetTrim($sAttCode, $sValue)
  425. {
  426. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  427. $iMaxSize = $oAttDef->GetMaxSize();
  428. if ($iMaxSize && (strlen($sValue) > $iMaxSize))
  429. {
  430. $sValue = substr($sValue, 0, $iMaxSize);
  431. }
  432. $this->Set($sAttCode, $sValue);
  433. }
  434. public function GetLabel($sAttCode)
  435. {
  436. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  437. return $oAttDef->GetLabel();
  438. }
  439. public function Get($sAttCode)
  440. {
  441. if (($iPos = strpos($sAttCode, '->')) === false)
  442. {
  443. return $this->GetStrict($sAttCode);
  444. }
  445. else
  446. {
  447. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  448. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  449. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  450. {
  451. throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
  452. }
  453. $oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode);
  454. if (!is_null($oExtFieldAtt))
  455. {
  456. return $this->GetStrict($oExtFieldAtt->GetCode());
  457. }
  458. else
  459. {
  460. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  461. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  462. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  463. if (is_null($oRemoteObj))
  464. {
  465. return '';
  466. }
  467. else
  468. {
  469. return $oRemoteObj->Get($sRemoteAttCode);
  470. }
  471. }
  472. }
  473. }
  474. public function GetStrict($sAttCode)
  475. {
  476. if ($sAttCode == 'id')
  477. {
  478. return $this->m_iKey;
  479. }
  480. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  481. if (!$oAttDef->LoadInObject())
  482. {
  483. $value = $oAttDef->GetValue($this);
  484. }
  485. else
  486. {
  487. if (isset($this->m_aLoadedAtt[$sAttCode]))
  488. {
  489. // Standard case... we have the information directly
  490. }
  491. elseif ($this->m_bIsInDB && !$this->m_bDirty)
  492. {
  493. // Lazy load (polymorphism): complete by reloading the entire object
  494. // #@# non-scalar attributes.... handle that differently?
  495. $oKPI = new ExecutionKPI();
  496. $this->Reload();
  497. $oKPI->ComputeStats('Reload', get_class($this).'/'.$sAttCode);
  498. }
  499. elseif ($sAttCode == 'friendlyname')
  500. {
  501. // The friendly name is not computed and the object is dirty
  502. // Todo: implement the computation of the friendly name based on sprintf()
  503. //
  504. $this->m_aCurrValues[$sAttCode] = '';
  505. }
  506. else
  507. {
  508. // Not loaded... is it related to an external key?
  509. if ($oAttDef->IsExternalField())
  510. {
  511. // Let's get the object and compute all of the corresponding attributes
  512. // (i.e not only the requested attribute)
  513. //
  514. $sExtKeyAttCode = $oAttDef->GetKeyAttCode();
  515. if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
  516. {
  517. $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  518. // Note: "allow all data" must be enabled because the external fields are always visible
  519. // to the current user even if this is not the case for the remote object
  520. // This is consistent with the behavior of the lists
  521. $oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
  522. }
  523. else
  524. {
  525. $oRemote = null;
  526. }
  527. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  528. {
  529. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sExtKeyAttCode))
  530. {
  531. if ($oRemote)
  532. {
  533. $this->m_aCurrValues[$sCode] = $oRemote->Get($oDef->GetExtAttCode());
  534. }
  535. else
  536. {
  537. $this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode);
  538. }
  539. $this->m_aLoadedAtt[$sCode] = true;
  540. }
  541. }
  542. }
  543. }
  544. $value = $this->m_aCurrValues[$sAttCode];
  545. }
  546. if ($value instanceof DBObjectSet)
  547. {
  548. $value->Rewind();
  549. }
  550. return $value;
  551. }
  552. public function GetOriginal($sAttCode)
  553. {
  554. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  555. {
  556. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  557. }
  558. return $this->m_aOrigValues[$sAttCode];
  559. }
  560. /**
  561. * Returns the default value of the $sAttCode. By default, returns the default value of the AttributeDefinition.
  562. * Overridable.
  563. *
  564. * @param $sAttCode
  565. * @return mixed
  566. */
  567. public function GetDefaultValue($sAttCode)
  568. {
  569. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  570. return $oAttDef->GetDefaultValue($this);
  571. }
  572. /**
  573. * Returns data loaded by the mean of a dynamic and explicit JOIN
  574. */
  575. public function GetExtendedData()
  576. {
  577. return $this->m_aExtendedData;
  578. }
  579. /**
  580. * Set the HighlightCode if the given code has a greater rank than the current HilightCode
  581. * @param string $sCode
  582. * @return void
  583. */
  584. protected function SetHighlightCode($sCode)
  585. {
  586. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  587. $fCurrentRank = 0.0;
  588. if (($this->m_sHighlightCode !== null) && array_key_exists($this->m_sHighlightCode, $aHighlightScale))
  589. {
  590. $fCurrentRank = $aHighlightScale[$this->m_sHighlightCode]['rank'];
  591. }
  592. if (array_key_exists($sCode, $aHighlightScale))
  593. {
  594. $fRank = $aHighlightScale[$sCode]['rank'];
  595. if ($fRank > $fCurrentRank)
  596. {
  597. $this->m_sHighlightCode = $sCode;
  598. }
  599. }
  600. }
  601. /**
  602. * Get the current HighlightCode
  603. * @return string The Hightlight code (null if none set, meaning rank = 0)
  604. */
  605. protected function GetHighlightCode()
  606. {
  607. return $this->m_sHighlightCode;
  608. }
  609. protected function ComputeHighlightCode()
  610. {
  611. // First if the state defines a HiglightCode, apply it
  612. $sState = $this->GetState();
  613. if ($sState != '')
  614. {
  615. $sCode = MetaModel::GetHighlightCode(get_class($this), $sState);
  616. $this->SetHighlightCode($sCode);
  617. }
  618. // The check for each StopWatch if a HighlightCode is effective
  619. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  620. {
  621. if ($oAttDef instanceof AttributeStopWatch)
  622. {
  623. $oStopWatch = $this->Get($sAttCode);
  624. $sCode = $oStopWatch->GetHighlightCode();
  625. if ($sCode !== '')
  626. {
  627. $this->SetHighlightCode($sCode);
  628. }
  629. }
  630. }
  631. return $this->GetHighlightCode();
  632. }
  633. /**
  634. * Updates the value of an external field by (re)loading the object
  635. * corresponding to the external key and getting the value from it
  636. *
  637. * UNUSED ?
  638. *
  639. * @param string $sAttCode Attribute code of the external field to update
  640. * @return void
  641. */
  642. protected function UpdateExternalField($sAttCode)
  643. {
  644. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  645. if ($oAttDef->IsExternalField())
  646. {
  647. $sTargetClass = $oAttDef->GetTargetClass();
  648. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  649. // Note: "allow all data" must be enabled because the external fields are always visible
  650. // to the current user even if this is not the case for the remote object
  651. // This is consistent with the behavior of the lists
  652. $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
  653. if (is_object($oObj))
  654. {
  655. $value = $oObj->Get($oAttDef->GetExtAttCode());
  656. $this->Set($sAttCode, $value);
  657. }
  658. }
  659. }
  660. public function ComputeValues()
  661. {
  662. }
  663. // Compute scalar attributes that depend on any other type of attribute
  664. final public function DoComputeValues()
  665. {
  666. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  667. // First check that we are not currently computing the fields
  668. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  669. foreach (debug_backtrace() as $aCallInfo)
  670. {
  671. if (!array_key_exists("class", $aCallInfo)) continue;
  672. if ($aCallInfo["class"] != get_class($this)) continue;
  673. if ($aCallInfo["function"] != "ComputeValues") continue;
  674. return; //skip!
  675. }
  676. // Set the "null-not-allowed" datetimes (and dates) whose value is not initialized
  677. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  678. {
  679. // AttributeDate is derived from AttributeDateTime
  680. if (($oAttDef instanceof AttributeDateTime) && (!$oAttDef->IsNullAllowed()) && ($this->Get($sAttCode) == $oAttDef->GetNullValue()))
  681. {
  682. $this->Set($sAttCode, date($oAttDef->GetInternalFormat()));
  683. }
  684. }
  685. $this->ComputeValues();
  686. }
  687. public function GetAsHTML($sAttCode, $bLocalize = true)
  688. {
  689. $sClass = get_class($this);
  690. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  691. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  692. {
  693. //return $this->Get($sAttCode.'_friendlyname');
  694. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  695. $iTargetKey = $this->Get($sAttCode);
  696. if ($iTargetKey < 0)
  697. {
  698. // the key points to an object that exists only in memory... no hyperlink points to it yet
  699. return '';
  700. }
  701. else
  702. {
  703. $sHtmlLabel = htmlentities($this->Get($sAttCode.'_friendlyname'), ENT_QUOTES, 'UTF-8');
  704. $bArchived = $this->IsArchived($sAttCode);
  705. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sHtmlLabel, null, true, $bArchived);
  706. }
  707. }
  708. // That's a standard attribute (might be an ext field or a direct field, etc.)
  709. return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
  710. }
  711. public function GetEditValue($sAttCode)
  712. {
  713. $sClass = get_class($this);
  714. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  715. if ($oAtt->IsExternalKey())
  716. {
  717. $sTargetClass = $oAtt->GetTargetClass();
  718. if ($this->IsNew())
  719. {
  720. // The current object exists only in memory, don't try to query it in the DB !
  721. // instead let's query for the object pointed by the external key, and get its name
  722. $targetObjId = $this->Get($sAttCode);
  723. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  724. if (is_object($oTargetObj))
  725. {
  726. $sEditValue = $oTargetObj->GetName();
  727. }
  728. else
  729. {
  730. $sEditValue = 0;
  731. }
  732. }
  733. else
  734. {
  735. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  736. }
  737. }
  738. else
  739. {
  740. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
  741. }
  742. return $sEditValue;
  743. }
  744. public function GetAsXML($sAttCode, $bLocalize = true)
  745. {
  746. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  747. return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
  748. }
  749. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false)
  750. {
  751. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  752. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText);
  753. }
  754. public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
  755. {
  756. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  757. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
  758. }
  759. public function GetOriginalAsXML($sAttCode, $bLocalize = true)
  760. {
  761. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  762. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
  763. }
  764. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false)
  765. {
  766. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  767. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText);
  768. }
  769. /**
  770. * @param $sObjClass
  771. * @param $sObjKey
  772. * @param string $sHtmlLabel Label with HTML entities escaped (< escaped as &lt;)
  773. * @param null $sUrlMakerClass
  774. * @param bool|true $bWithNavigationContext
  775. * @param bool|false $bArchived
  776. * @return string
  777. * @throws DictExceptionMissingString
  778. */
  779. public static function MakeHyperLink($sObjClass, $sObjKey, $sHtmlLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true, $bArchived = false)
  780. {
  781. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  782. // Safety net
  783. //
  784. if (empty($sHtmlLabel))
  785. {
  786. // If the object if not issued from a query but constructed programmatically
  787. // the label may be empty. In this case run a query to get the object's friendly name
  788. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
  789. if (is_object($oTmpObj))
  790. {
  791. $sHtmlLabel = $oTmpObj->GetName();
  792. }
  793. else
  794. {
  795. // May happen in case the target object is not in the list of allowed values for this attribute
  796. $sHtmlLabel = "<em>$sObjClass::$sObjKey</em>";
  797. }
  798. }
  799. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  800. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  801. $bClickable = !$bArchived || utils::IsArchiveMode();
  802. if ($bArchived)
  803. {
  804. $sSpanClass = 'archived';
  805. $sFA = 'fa-archive object-archived';
  806. $sHint = Dict::S('ObjectRef:Archived');
  807. }
  808. else
  809. {
  810. $sSpanClass = '';
  811. $sFA = '';
  812. }
  813. if ($sFA == '')
  814. {
  815. $sIcon = '';
  816. }
  817. else
  818. {
  819. if ($bClickable)
  820. {
  821. $sIcon = "<span class=\"object-ref-icon fa $sFA fa-1x fa-fw\"></span>";
  822. }
  823. else
  824. {
  825. $sIcon = "<span class=\"object-ref-icon-disabled fa $sFA fa-1x fa-fw\"></span>";
  826. }
  827. }
  828. if ($bClickable && (strlen($sUrl) > 0))
  829. {
  830. $sHLink = "<a class=\"object-ref-link\" href=\"$sUrl\">$sIcon$sHtmlLabel</a>";
  831. }
  832. else
  833. {
  834. $sHLink = $sIcon.$sHtmlLabel;
  835. }
  836. $sRet = "<span class=\"object-ref $sSpanClass\" title=\"$sHint\">$sHLink</span>";
  837. return $sRet;
  838. }
  839. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  840. {
  841. $bArchived = $this->IsArchived();
  842. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext, $bArchived);
  843. }
  844. public static function ComputeStandardUIPage($sClass)
  845. {
  846. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  847. if (!isset($aUIPagesCache[$sClass]))
  848. {
  849. $UIPage = false;
  850. if (is_callable("$sClass::GetUIPage"))
  851. {
  852. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  853. }
  854. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  855. }
  856. $sPage = $aUIPagesCache[$sClass];
  857. return $sPage;
  858. }
  859. public static function GetUIPage()
  860. {
  861. return 'UI.php';
  862. }
  863. // could be in the metamodel ?
  864. public static function IsValidPKey($value)
  865. {
  866. return ((string)$value === (string)(int)$value);
  867. }
  868. public function GetKey()
  869. {
  870. return $this->m_iKey;
  871. }
  872. public function SetKey($iNewKey)
  873. {
  874. if (!self::IsValidPKey($iNewKey))
  875. {
  876. throw new CoreException("An object id must be an integer value ($iNewKey)");
  877. }
  878. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  879. {
  880. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  881. }
  882. $this->m_iKey = $iNewKey;
  883. }
  884. /**
  885. * Get the icon representing this object
  886. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  887. * @return string Either the full IMG tag ($bImgTag == true) or just the URL to the icon file
  888. */
  889. public function GetIcon($bImgTag = true)
  890. {
  891. $sCode = $this->ComputeHighlightCode();
  892. if($sCode != '')
  893. {
  894. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  895. if (array_key_exists($sCode, $aHighlightScale))
  896. {
  897. $sIconUrl = $aHighlightScale[$sCode]['icon'];
  898. if($bImgTag)
  899. {
  900. return "<img src=\"$sIconUrl\" style=\"vertical-align:middle\"/>";
  901. }
  902. else
  903. {
  904. return $sIconUrl;
  905. }
  906. }
  907. }
  908. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  909. }
  910. /**
  911. * Gets the name of an object in a safe manner for displaying inside a web page
  912. * @return string
  913. */
  914. public function GetName()
  915. {
  916. return htmlentities($this->GetRawName(), ENT_QUOTES, 'UTF-8');
  917. }
  918. /**
  919. * Gets the raw name of an object, this is not safe for displaying inside a web page
  920. * since the " < > characters are not escaped and the name may contain some XSS script
  921. * instructions.
  922. * Use this function only for internal computations or for an output to a non-HTML destination
  923. * @return string
  924. */
  925. public function GetRawName()
  926. {
  927. return $this->Get('friendlyname');
  928. }
  929. public function GetState()
  930. {
  931. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  932. if (empty($sStateAttCode))
  933. {
  934. return '';
  935. }
  936. else
  937. {
  938. return $this->Get($sStateAttCode);
  939. }
  940. }
  941. public function GetStateLabel()
  942. {
  943. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  944. if (empty($sStateAttCode))
  945. {
  946. return '';
  947. }
  948. else
  949. {
  950. $sStateValue = $this->Get($sStateAttCode);
  951. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  952. }
  953. }
  954. public function GetStateDescription()
  955. {
  956. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  957. if (empty($sStateAttCode))
  958. {
  959. return '';
  960. }
  961. else
  962. {
  963. $sStateValue = $this->Get($sStateAttCode);
  964. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  965. }
  966. }
  967. /**
  968. * Overridable - Define attributes read-only from the end-user perspective
  969. *
  970. * @return array List of attcodes
  971. */
  972. public static function GetReadOnlyAttributes()
  973. {
  974. return null;
  975. }
  976. /**
  977. * Overridable - Get predefined objects (could be hardcoded)
  978. * The predefined objects will be synchronized with the DB at each install/upgrade
  979. * As soon as a class has predefined objects, then nobody can create nor delete objects
  980. * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
  981. */
  982. public static function GetPredefinedObjects()
  983. {
  984. return null;
  985. }
  986. /**
  987. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  988. * for the given attribute in the current state of the object
  989. * @param $sAttCode string $sAttCode The code of the attribute
  990. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  991. * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
  992. * @return integer Flags: the binary combination of the flags applicable to this attribute
  993. */
  994. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  995. {
  996. $iFlags = 0; // By default (if no life cycle) no flag at all
  997. $aReadOnlyAtts = $this->GetReadOnlyAttributes();
  998. if ($aReadOnlyAtts != null)
  999. {
  1000. if (in_array($sAttCode, $aReadOnlyAtts))
  1001. {
  1002. return OPT_ATT_READONLY;
  1003. }
  1004. }
  1005. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1006. if (!empty($sStateAttCode))
  1007. {
  1008. if ($sTargetState != '')
  1009. {
  1010. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  1011. }
  1012. else
  1013. {
  1014. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  1015. }
  1016. }
  1017. $aReasons = array();
  1018. $iSynchroFlags = 0;
  1019. if ($this->InSyncScope())
  1020. {
  1021. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  1022. }
  1023. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  1024. }
  1025. /**
  1026. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  1027. * for the given attribute in a transition
  1028. * @param $sAttCode string $sAttCode The code of the attribute
  1029. * @param $sStimulus string The stimulus code to apply
  1030. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  1031. * @param $sOriginState string The state from which to apply $sStimulus, if empty current state will be used
  1032. * @return integer Flags: the binary combination of the flags applicable to this attribute
  1033. */
  1034. public function GetTransitionFlags($sAttCode, $sStimulus, &$aReasons = array(), $sOriginState = '')
  1035. {
  1036. $iFlags = 0; // By default (if no lifecycle) no flag at all
  1037. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1038. // If no state attribute, there is no lifecycle
  1039. if (empty($sStateAttCode))
  1040. {
  1041. return $iFlags;
  1042. }
  1043. // Retrieving current state if necessary
  1044. if ($sOriginState === '')
  1045. {
  1046. $sOriginState = $this->Get($sStateAttCode);
  1047. }
  1048. // Retrieving attribute flags
  1049. $iAttributeFlags = $this->GetAttributeFlags($sAttCode, $aReasons, $sOriginState);
  1050. // Retrieving transition flags
  1051. $iTransitionFlags = MetaModel::GetTransitionFlags(get_class($this), $sOriginState, $sStimulus, $sAttCode);
  1052. // Merging transition flags with attribute flags
  1053. $iFlags = $iTransitionFlags | $iAttributeFlags;
  1054. return $iFlags;
  1055. }
  1056. /**
  1057. * Returns an array of attribute codes (with their flags) when $sStimulus is applied on the object in the $sOriginState state.
  1058. * Note: Attributes (and flags) from the target state and the transition are combined.
  1059. *
  1060. * @param $sStimulus string
  1061. * @param $sOriginState string Default is current state
  1062. * @return array
  1063. */
  1064. public function GetTransitionAttributes($sStimulus, $sOriginState = null)
  1065. {
  1066. $sObjClass = get_class($this);
  1067. // Defining current state as origin state if not specified
  1068. if($sOriginState === null)
  1069. {
  1070. $sOriginState = $this->GetState();
  1071. }
  1072. $aAttributes = MetaModel::GetTransitionAttributes($sObjClass, $sStimulus, $sOriginState);
  1073. return $aAttributes;
  1074. }
  1075. /**
  1076. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  1077. * for the given attribute for the current state of the object considered as an INITIAL state
  1078. * @param string $sAttCode The code of the attribute
  1079. * @return integer Flags: the binary combination of the flags applicable to this attribute
  1080. */
  1081. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  1082. {
  1083. $iFlags = 0;
  1084. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1085. if (!empty($sStateAttCode))
  1086. {
  1087. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  1088. }
  1089. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  1090. }
  1091. // check if the given (or current) value is suitable for the attribute
  1092. // return true if successfull
  1093. // return the error desciption otherwise
  1094. public function CheckValue($sAttCode, $value = null)
  1095. {
  1096. if (!is_null($value))
  1097. {
  1098. $toCheck = $value;
  1099. }
  1100. else
  1101. {
  1102. $toCheck = $this->Get($sAttCode);
  1103. }
  1104. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1105. if (!$oAtt->IsWritable())
  1106. {
  1107. return true;
  1108. }
  1109. elseif ($oAtt->IsNull($toCheck))
  1110. {
  1111. if ($oAtt->IsNullAllowed())
  1112. {
  1113. return true;
  1114. }
  1115. else
  1116. {
  1117. return "Null not allowed";
  1118. }
  1119. }
  1120. elseif ($oAtt->IsExternalKey())
  1121. {
  1122. if (!MetaModel::SkipCheckExtKeys())
  1123. {
  1124. $sTargetClass = $oAtt->GetTargetClass();
  1125. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  1126. if (is_null($oTargetObj))
  1127. {
  1128. return "Target object not found ($sTargetClass::$toCheck)";
  1129. }
  1130. }
  1131. if ($oAtt->IsHierarchicalKey())
  1132. {
  1133. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  1134. if ($toCheck == $this->GetKey())
  1135. {
  1136. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  1137. }
  1138. }
  1139. }
  1140. elseif ($oAtt->IsScalar())
  1141. {
  1142. $aValues = $oAtt->GetAllowedValues($this->ToArgsForQuery());
  1143. if (count($aValues) > 0)
  1144. {
  1145. if (!array_key_exists($toCheck, $aValues))
  1146. {
  1147. return "Value not allowed [$toCheck]";
  1148. }
  1149. }
  1150. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  1151. {
  1152. $iLen = strlen($toCheck);
  1153. if ($iLen > $iMaxSize)
  1154. {
  1155. return "String too long (found $iLen, limited to $iMaxSize)";
  1156. }
  1157. }
  1158. if (!$oAtt->CheckFormat($toCheck))
  1159. {
  1160. return "Wrong format [$toCheck]";
  1161. }
  1162. }
  1163. else
  1164. {
  1165. return $oAtt->CheckValue($this, $toCheck);
  1166. }
  1167. return true;
  1168. }
  1169. // check attributes together
  1170. public function CheckConsistency()
  1171. {
  1172. return true;
  1173. }
  1174. // check integrity rules (before inserting or updating the object)
  1175. // a displayable error is returned
  1176. public function DoCheckToWrite()
  1177. {
  1178. $this->DoComputeValues();
  1179. $aChanges = $this->ListChanges();
  1180. foreach($aChanges as $sAttCode => $value)
  1181. {
  1182. $res = $this->CheckValue($sAttCode);
  1183. if ($res !== true)
  1184. {
  1185. // $res contains the error description
  1186. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  1187. }
  1188. }
  1189. if (count($this->m_aCheckIssues) > 0)
  1190. {
  1191. // No need to check consistency between attributes if any of them has
  1192. // an unexpected value
  1193. return;
  1194. }
  1195. $res = $this->CheckConsistency();
  1196. if ($res !== true)
  1197. {
  1198. // $res contains the error description
  1199. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  1200. }
  1201. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  1202. //
  1203. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  1204. {
  1205. foreach($aChanges as $sAttCode => $value)
  1206. {
  1207. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  1208. if ($iFlags & OPT_ATT_SLAVE)
  1209. {
  1210. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  1211. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1212. $sAttLabel = $oAttDef->GetLabel();
  1213. foreach($aReasons as $aReasonInfo)
  1214. {
  1215. // Todo: associate the attribute code with the error
  1216. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. final public function CheckToWrite()
  1223. {
  1224. if (MetaModel::SkipCheckToWrite())
  1225. {
  1226. return array(true, array());
  1227. }
  1228. if (is_null($this->m_bCheckStatus))
  1229. {
  1230. $this->m_aCheckIssues = array();
  1231. $oKPI = new ExecutionKPI();
  1232. $this->DoCheckToWrite();
  1233. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  1234. if (count($this->m_aCheckIssues) == 0)
  1235. {
  1236. $this->m_bCheckStatus = true;
  1237. }
  1238. else
  1239. {
  1240. $this->m_bCheckStatus = false;
  1241. }
  1242. }
  1243. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  1244. }
  1245. // check if it is allowed to delete the existing object from the database
  1246. // a displayable error is returned
  1247. protected function DoCheckToDelete(&$oDeletionPlan)
  1248. {
  1249. $this->m_aDeleteIssues = array(); // Ok
  1250. if ($this->InSyncScope())
  1251. {
  1252. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  1253. {
  1254. foreach ($aSourceData['replica'] as $oReplica)
  1255. {
  1256. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  1257. }
  1258. $oDataSource = $aSourceData['source'];
  1259. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  1260. {
  1261. // The current task has the right to delete the object
  1262. continue;
  1263. }
  1264. $oReplica = reset($aSourceData['replica']); // Take the first one
  1265. if ($oReplica->Get('status_dest_creator') != 1)
  1266. {
  1267. // The object is not owned by the task
  1268. continue;
  1269. }
  1270. $sLink = $oDataSource->GetName();
  1271. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  1272. switch($sUserDeletePolicy)
  1273. {
  1274. case 'nobody':
  1275. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1276. break;
  1277. case 'administrators':
  1278. if (!UserRights::IsAdministrator())
  1279. {
  1280. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1281. }
  1282. break;
  1283. case 'everybody':
  1284. default:
  1285. // Ok
  1286. break;
  1287. }
  1288. }
  1289. }
  1290. }
  1291. public function CheckToDelete(&$oDeletionPlan)
  1292. {
  1293. $this->MakeDeletionPlan($oDeletionPlan);
  1294. $oDeletionPlan->ComputeResults();
  1295. return (!$oDeletionPlan->FoundStopper());
  1296. }
  1297. protected function ListChangedValues(array $aProposal)
  1298. {
  1299. $aDelta = array();
  1300. foreach ($aProposal as $sAtt => $proposedValue)
  1301. {
  1302. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1303. {
  1304. // The value was not set
  1305. $aDelta[$sAtt] = $proposedValue;
  1306. }
  1307. elseif(!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false))
  1308. {
  1309. // This attCode was never set, cannot be modified
  1310. // or the same value - as the original value - was set, and has been verified as equivalent to the original value
  1311. continue;
  1312. }
  1313. else if (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true)
  1314. {
  1315. // We already know that the value is really modified
  1316. $aDelta[$sAtt] = $proposedValue;
  1317. }
  1318. elseif(is_object($proposedValue))
  1319. {
  1320. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1321. // The value is an object, the comparison is not strict
  1322. if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue))
  1323. {
  1324. $aDelta[$sAtt] = $proposedValue;
  1325. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1326. }
  1327. else
  1328. {
  1329. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1330. }
  1331. }
  1332. else
  1333. {
  1334. // The value is a scalar, the comparison must be 100% strict
  1335. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1336. {
  1337. //echo "$sAtt:<pre>\n";
  1338. //var_dump($this->m_aOrigValues[$sAtt]);
  1339. //var_dump($proposedValue);
  1340. //echo "</pre>\n";
  1341. $aDelta[$sAtt] = $proposedValue;
  1342. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1343. }
  1344. else
  1345. {
  1346. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1347. }
  1348. }
  1349. }
  1350. return $aDelta;
  1351. }
  1352. // List the attributes that have been changed
  1353. // Returns an array of attname => currentvalue
  1354. public function ListChanges()
  1355. {
  1356. if ($this->m_bIsInDB)
  1357. {
  1358. return $this->ListChangedValues($this->m_aCurrValues);
  1359. }
  1360. else
  1361. {
  1362. return $this->m_aCurrValues;
  1363. }
  1364. }
  1365. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1366. public function IsModified()
  1367. {
  1368. $aChanges = $this->ListChanges();
  1369. return (count($aChanges) != 0);
  1370. }
  1371. public function Equals($oSibling)
  1372. {
  1373. if (get_class($oSibling) != get_class($this))
  1374. {
  1375. return false;
  1376. }
  1377. if ($this->GetKey() != $oSibling->GetKey())
  1378. {
  1379. return false;
  1380. }
  1381. if ($this->m_bIsInDB)
  1382. {
  1383. // If one has changed, then consider them as being different
  1384. if ($this->IsModified() || $oSibling->IsModified())
  1385. {
  1386. return false;
  1387. }
  1388. }
  1389. else
  1390. {
  1391. // Todo - implement this case (loop on every attribute)
  1392. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1393. //{
  1394. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1395. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1396. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1397. //{
  1398. //return false;
  1399. //}
  1400. //}
  1401. return false;
  1402. }
  1403. return true;
  1404. }
  1405. // used only by insert
  1406. protected function OnObjectKeyReady()
  1407. {
  1408. // Meant to be overloaded
  1409. }
  1410. // used both by insert/update
  1411. private function DBWriteLinks()
  1412. {
  1413. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1414. {
  1415. if (!$oAttDef->IsLinkSet()) continue;
  1416. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1417. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1418. // Note: any change to this algorithm must be reproduced into the implementation of AttributeLinkSet::Equals()
  1419. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1420. $sAdditionalKey = null;
  1421. if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
  1422. {
  1423. $sAdditionalKey = $oAttDef->GetExtKeyToRemote();
  1424. }
  1425. $oComparator = new DBObjectSetComparator($this->m_aOrigValues[$sAttCode], $this->Get($sAttCode), array($sExtKeyToMe), $sAdditionalKey);
  1426. $aChanges = $oComparator->GetDifferences();
  1427. foreach($aChanges['added'] as $oLink)
  1428. {
  1429. // Make sure that the objects in the set point to "this"
  1430. $oLink->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1431. $id = $oLink->DBWrite();
  1432. }
  1433. foreach($aChanges['modified'] as $oLink)
  1434. {
  1435. // Objects in the set either remain attached or have been detached -> leave the link as is
  1436. $oLink->DBWrite();
  1437. }
  1438. foreach($aChanges['removed'] as $oLink)
  1439. {
  1440. $oLink->DBDelete();
  1441. }
  1442. }
  1443. }
  1444. // used both by insert/update
  1445. private function WriteExternalAttributes()
  1446. {
  1447. foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1448. {
  1449. if (!$oAttDef->LoadInObject()) continue;
  1450. if ($oAttDef->LoadFromDB()) continue;
  1451. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1452. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1453. $oAttDef->WriteValue($this, $this->m_aCurrValues[$sAttCode]);
  1454. }
  1455. }
  1456. // Note: this is experimental - it was designed to speed up the setup of iTop
  1457. // Known limitations:
  1458. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1459. // - the id of the object is not updated
  1460. static public final function BulkInsertStart()
  1461. {
  1462. self::$m_bBulkInsert = true;
  1463. }
  1464. static public final function BulkInsertFlush()
  1465. {
  1466. if (!self::$m_bBulkInsert) return;
  1467. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1468. {
  1469. foreach ($aTables as $sTable => $sColumns)
  1470. {
  1471. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1472. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1473. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1474. }
  1475. }
  1476. // Reset
  1477. self::$m_aBulkInsertItems = array();
  1478. self::$m_aBulkInsertCols = array();
  1479. self::$m_bBulkInsert = false;
  1480. }
  1481. private function DBInsertSingleTable($sTableClass)
  1482. {
  1483. $sTable = MetaModel::DBGetTable($sTableClass);
  1484. // Abstract classes or classes having no specific attribute do not have an associated table
  1485. if ($sTable == '') return;
  1486. $sClass = get_class($this);
  1487. // fields in first array, values in the second
  1488. $aFieldsToWrite = array();
  1489. $aValuesToWrite = array();
  1490. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1491. {
  1492. // Add it to the list of fields to write
  1493. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1494. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1495. }
  1496. $aHierarchicalKeys = array();
  1497. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1498. {
  1499. // Skip this attribute if not defined in this table
  1500. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1501. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1502. foreach($aAttColumns as $sColumn => $sValue)
  1503. {
  1504. $aFieldsToWrite[] = "`$sColumn`";
  1505. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1506. }
  1507. if ($oAttDef->IsHierarchicalKey())
  1508. {
  1509. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1510. }
  1511. }
  1512. if (count($aValuesToWrite) == 0) return false;
  1513. if (MetaModel::DBIsReadOnly())
  1514. {
  1515. $iNewKey = -1;
  1516. }
  1517. else
  1518. {
  1519. if (self::$m_bBulkInsert)
  1520. {
  1521. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1522. {
  1523. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1524. }
  1525. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1526. $iNewKey = 999999; // TODO - compute next id....
  1527. }
  1528. else
  1529. {
  1530. if (count($aHierarchicalKeys) > 0)
  1531. {
  1532. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1533. {
  1534. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1535. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1536. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1537. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1538. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1539. }
  1540. }
  1541. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1542. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1543. }
  1544. }
  1545. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1546. if (empty($this->m_iKey))
  1547. {
  1548. // Take the autonumber
  1549. $this->m_iKey = $iNewKey;
  1550. }
  1551. return $this->m_iKey;
  1552. }
  1553. // Insert of record for the new object into the database
  1554. // Returns the key of the newly created object
  1555. public function DBInsertNoReload()
  1556. {
  1557. if ($this->m_bIsInDB)
  1558. {
  1559. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1560. }
  1561. $sClass = get_class($this);
  1562. $sRootClass = MetaModel::GetRootClass($sClass);
  1563. // Ensure the update of the values (we are accessing the data directly)
  1564. $this->DoComputeValues();
  1565. $this->OnInsert();
  1566. if ($this->m_iKey < 0)
  1567. {
  1568. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1569. $this->m_iKey = null;
  1570. }
  1571. // If not automatically computed, then check that the key is given by the caller
  1572. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1573. {
  1574. if (empty($this->m_iKey))
  1575. {
  1576. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber", array('class' => $sRootClass));
  1577. }
  1578. }
  1579. // Ultimate check - ensure DB integrity
  1580. list($bRes, $aIssues) = $this->CheckToWrite();
  1581. if (!$bRes)
  1582. {
  1583. $sIssues = implode(', ', $aIssues);
  1584. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1585. }
  1586. // Stop watches
  1587. $sState = $this->GetState();
  1588. if ($sState != '')
  1589. {
  1590. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1591. {
  1592. if ($oAttDef instanceof AttributeStopWatch)
  1593. {
  1594. if (in_array($sState, $oAttDef->GetStates()))
  1595. {
  1596. // Start the stop watch and compute the deadlines
  1597. $oSW = $this->Get($sAttCode);
  1598. $oSW->Start($this, $oAttDef);
  1599. $oSW->ComputeDeadlines($this, $oAttDef);
  1600. $this->Set($sAttCode, $oSW);
  1601. }
  1602. }
  1603. }
  1604. }
  1605. // First query built upon on the root class, because the ID must be created first
  1606. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1607. // Then do the leaf class, if different from the root class
  1608. if ($sClass != $sRootClass)
  1609. {
  1610. $this->DBInsertSingleTable($sClass);
  1611. }
  1612. // Then do the other classes
  1613. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1614. {
  1615. if ($sParentClass == $sRootClass) continue;
  1616. $this->DBInsertSingleTable($sParentClass);
  1617. }
  1618. $this->OnObjectKeyReady();
  1619. $this->DBWriteLinks();
  1620. $this->WriteExternalAttributes();
  1621. $this->m_bIsInDB = true;
  1622. $this->m_bDirty = false;
  1623. $this->AfterInsert();
  1624. // Activate any existing trigger
  1625. $sClass = get_class($this);
  1626. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1627. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1628. while ($oTrigger = $oSet->Fetch())
  1629. {
  1630. $oTrigger->DoActivate($this->ToArgs('this'));
  1631. }
  1632. // Callbacks registered with RegisterCallback
  1633. if (isset($this->m_aCallbacks[self::CALLBACK_AFTERINSERT]))
  1634. {
  1635. foreach ($this->m_aCallbacks[self::CALLBACK_AFTERINSERT] as $aCallBackData)
  1636. {
  1637. call_user_func_array($aCallBackData['callback'], $aCallBackData['params']);
  1638. }
  1639. }
  1640. $this->RecordObjCreation();
  1641. return $this->m_iKey;
  1642. }
  1643. protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
  1644. {
  1645. $sTable = MetaModel::DBGetTable($sTableClass);
  1646. // Abstract classes or classes having no specific attribute do not have an associated table
  1647. if ($sTable == '') return;
  1648. $sClass = get_class($this);
  1649. // fields in first array, values in the second
  1650. $aFieldsToWrite = array();
  1651. $aValuesToWrite = array();
  1652. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1653. {
  1654. // Add it to the list of fields to write
  1655. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1656. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1657. }
  1658. $aHierarchicalKeys = array();
  1659. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1660. {
  1661. // Skip this attribute if not defined in this table
  1662. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1663. // Skip link set that can still be undefined though the object is 100% loaded
  1664. if ($oAttDef->IsLinkSet()) continue;
  1665. $value = $this->m_aCurrValues[$sAttCode];
  1666. if ($oAttDef->IsExternalKey())
  1667. {
  1668. $sTargetClass = $oAttDef->GetTargetClass();
  1669. if (is_array($aAuthorizedExtKeys))
  1670. {
  1671. if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
  1672. {
  1673. $value = 0;
  1674. }
  1675. }
  1676. }
  1677. $aAttColumns = $oAttDef->GetSQLValues($value);
  1678. foreach($aAttColumns as $sColumn => $sValue)
  1679. {
  1680. $aFieldsToWrite[] = "`$sColumn`";
  1681. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1682. }
  1683. if ($oAttDef->IsHierarchicalKey())
  1684. {
  1685. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1686. }
  1687. }
  1688. if (count($aValuesToWrite) == 0) return false;
  1689. if (count($aHierarchicalKeys) > 0)
  1690. {
  1691. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1692. {
  1693. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1694. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1695. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1696. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1697. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1698. }
  1699. }
  1700. $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
  1701. }
  1702. public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
  1703. {
  1704. $sClass = get_class($this);
  1705. $sRootClass = MetaModel::GetRootClass($sClass);
  1706. // First query built upon on the root class, because the ID must be created first
  1707. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
  1708. // Then do the leaf class, if different from the root class
  1709. if ($sClass != $sRootClass)
  1710. {
  1711. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
  1712. }
  1713. // Then do the other classes
  1714. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1715. {
  1716. if ($sParentClass == $sRootClass) continue;
  1717. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
  1718. }
  1719. }
  1720. public function DBInsert()
  1721. {
  1722. $this->DBInsertNoReload();
  1723. $this->Reload();
  1724. return $this->m_iKey;
  1725. }
  1726. public function DBInsertTracked(CMDBChange $oChange)
  1727. {
  1728. CMDBObject::SetCurrentChange($oChange);
  1729. return $this->DBInsert();
  1730. }
  1731. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1732. {
  1733. CMDBObject::SetCurrentChange($oChange);
  1734. return $this->DBInsertNoReload();
  1735. }
  1736. // Creates a copy of the current object into the database
  1737. // Returns the id of the newly created object
  1738. public function DBClone($iNewKey = null)
  1739. {
  1740. $this->m_bIsInDB = false;
  1741. $this->m_iKey = $iNewKey;
  1742. $ret = $this->DBInsert();
  1743. $this->RecordObjCreation();
  1744. return $ret;
  1745. }
  1746. /**
  1747. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1748. * The purpose of this method is to reset the appropriate attributes of the object in
  1749. * order to make sure that the newly cloned object is really distinct from its clone
  1750. */
  1751. public function __clone()
  1752. {
  1753. $this->m_bIsInDB = false;
  1754. $this->m_bDirty = true;
  1755. $this->m_iKey = self::GetNextTempId(get_class($this));
  1756. }
  1757. // Update a record
  1758. public function DBUpdate()
  1759. {
  1760. if (!$this->m_bIsInDB)
  1761. {
  1762. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1763. }
  1764. // Protect against reentrance (e.g. cascading the update of ticket logs)
  1765. static $aUpdateReentrance = array();
  1766. $sKey = get_class($this).'::'.$this->GetKey();
  1767. if (array_key_exists($sKey, $aUpdateReentrance))
  1768. {
  1769. return;
  1770. }
  1771. $aUpdateReentrance[$sKey] = true;
  1772. try
  1773. {
  1774. // Stop watches
  1775. $sState = $this->GetState();
  1776. if ($sState != '')
  1777. {
  1778. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1779. {
  1780. if ($oAttDef instanceof AttributeStopWatch)
  1781. {
  1782. if (in_array($sState, $oAttDef->GetStates()))
  1783. {
  1784. // Compute or recompute the deadlines
  1785. $oSW = $this->Get($sAttCode);
  1786. $oSW->ComputeDeadlines($this, $oAttDef);
  1787. $this->Set($sAttCode, $oSW);
  1788. }
  1789. }
  1790. }
  1791. }
  1792. $this->DoComputeValues();
  1793. $this->OnUpdate();
  1794. $aChanges = $this->ListChanges();
  1795. if (count($aChanges) == 0)
  1796. {
  1797. // Attempting to update an unchanged object
  1798. unset($aUpdateReentrance[$sKey]);
  1799. return $this->m_iKey;
  1800. }
  1801. // Ultimate check - ensure DB integrity
  1802. list($bRes, $aIssues) = $this->CheckToWrite();
  1803. if (!$bRes)
  1804. {
  1805. $sIssues = implode(', ', $aIssues);
  1806. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1807. }
  1808. // Save the original values (will be reset to the new values when the object get written to the DB)
  1809. $aOriginalValues = $this->m_aOrigValues;
  1810. $bHasANewExternalKeyValue = false;
  1811. $aHierarchicalKeys = array();
  1812. $aDBChanges = array();
  1813. foreach($aChanges as $sAttCode => $valuecurr)
  1814. {
  1815. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1816. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1817. if ($oAttDef->IsBasedOnDBColumns())
  1818. {
  1819. $aDBChanges[$sAttCode] = $aChanges[$sAttCode];
  1820. }
  1821. if ($oAttDef->IsHierarchicalKey())
  1822. {
  1823. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1824. }
  1825. }
  1826. if (!MetaModel::DBIsReadOnly())
  1827. {
  1828. // Update the left & right indexes for each hierarchical key
  1829. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1830. {
  1831. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1832. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1833. $aRes = CMDBSource::QueryToArray($sSQL);
  1834. $iMyLeft = $aRes[0]['left'];
  1835. $iMyRight = $aRes[0]['right'];
  1836. $iDelta =$iMyRight - $iMyLeft + 1;
  1837. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1838. if ($aDBChanges[$sAttCode] == 0)
  1839. {
  1840. // No new parent, insert completely at the right of the tree
  1841. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1842. $aRes = CMDBSource::QueryToArray($sSQL);
  1843. if (count($aRes) == 0)
  1844. {
  1845. $iNewLeft = 1;
  1846. }
  1847. else
  1848. {
  1849. $iNewLeft = $aRes[0]['max']+1;
  1850. }
  1851. }
  1852. else
  1853. {
  1854. // Insert at the right of the specified parent
  1855. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aDBChanges[$sAttCode]);
  1856. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1857. }
  1858. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1859. $aHKChanges = array();
  1860. $aHKChanges[$sAttCode] = $aDBChanges[$sAttCode];
  1861. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1862. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1863. $aDBChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1864. }
  1865. // Update scalar attributes
  1866. if (count($aDBChanges) != 0)
  1867. {
  1868. $oFilter = new DBObjectSearch(get_class($this));
  1869. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1870. $oFilter->AllowAllData();
  1871. $sSQL = $oFilter->MakeUpdateQuery($aDBChanges);
  1872. CMDBSource::Query($sSQL);
  1873. }
  1874. }
  1875. $this->DBWriteLinks();
  1876. $this->WriteExternalAttributes();
  1877. $this->m_bDirty = false;
  1878. $this->m_aTouchedAtt = array();
  1879. $this->m_aModifiedAtt = array();
  1880. $this->AfterUpdate();
  1881. // Reload to get the external attributes
  1882. if ($bHasANewExternalKeyValue)
  1883. {
  1884. $this->Reload(true /* AllowAllData */);
  1885. }
  1886. else
  1887. {
  1888. // Reset original values although the object has not been reloaded
  1889. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1890. {
  1891. if ($bLoaded)
  1892. {
  1893. $value = $this->m_aCurrValues[$sAttCode];
  1894. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1895. }
  1896. }
  1897. }
  1898. if (count($aChanges) != 0)
  1899. {
  1900. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1901. }
  1902. }
  1903. catch (Exception $e)
  1904. {
  1905. unset($aUpdateReentrance[$sKey]);
  1906. throw $e;
  1907. }
  1908. unset($aUpdateReentrance[$sKey]);
  1909. return $this->m_iKey;
  1910. }
  1911. public function DBUpdateTracked(CMDBChange $oChange)
  1912. {
  1913. CMDBObject::SetCurrentChange($oChange);
  1914. return $this->DBUpdate();
  1915. }
  1916. // Make the current changes persistent - clever wrapper for Insert or Update
  1917. public function DBWrite()
  1918. {
  1919. if ($this->m_bIsInDB)
  1920. {
  1921. return $this->DBUpdate();
  1922. }
  1923. else
  1924. {
  1925. return $this->DBInsert();
  1926. }
  1927. }
  1928. private function DBDeleteSingleTable($sTableClass)
  1929. {
  1930. $sTable = MetaModel::DBGetTable($sTableClass);
  1931. // Abstract classes or classes having no specific attribute do not have an associated table
  1932. if ($sTable == '') return;
  1933. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1934. $sKey = CMDBSource::Quote($this->m_iKey);
  1935. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1936. CMDBSource::DeleteFrom($sDeleteSQL);
  1937. }
  1938. protected function DBDeleteSingleObject()
  1939. {
  1940. if (!MetaModel::DBIsReadOnly())
  1941. {
  1942. $this->OnDelete();
  1943. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1944. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1945. {
  1946. if ($oAttDef->IsHierarchicalKey())
  1947. {
  1948. // Update the left & right indexes for each hierarchical key
  1949. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1950. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1951. $aRes = CMDBSource::QueryToArray($sSQL);
  1952. $iMyLeft = $aRes[0]['left'];
  1953. $iMyRight = $aRes[0]['right'];
  1954. $iDelta =$iMyRight - $iMyLeft + 1;
  1955. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1956. // No new parent for now, insert completely at the right of the tree
  1957. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1958. $aRes = CMDBSource::QueryToArray($sSQL);
  1959. if (count($aRes) == 0)
  1960. {
  1961. $iNewLeft = 1;
  1962. }
  1963. else
  1964. {
  1965. $iNewLeft = $aRes[0]['max']+1;
  1966. }
  1967. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1968. }
  1969. elseif (!$oAttDef->LoadFromDB())
  1970. {
  1971. $oAttDef->DeleteValue($this);
  1972. }
  1973. }
  1974. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1975. {
  1976. $this->DBDeleteSingleTable($sParentClass);
  1977. }
  1978. $this->AfterDelete();
  1979. $this->m_bIsInDB = false;
  1980. // Fix for #926: do NOT reset m_iKey as it can be used to have it for reporting purposes (see the REST service to delete objects, reported as bug #926)
  1981. // Thought the key is not reset, using DBInsert or DBWrite will create an object having the same characteristics and a new ID. DBUpdate is protected
  1982. }
  1983. }
  1984. // Delete an object... and guarantee data integrity
  1985. //
  1986. public function DBDelete(&$oDeletionPlan = null)
  1987. {
  1988. static $iLoopTimeLimit = null;
  1989. if ($iLoopTimeLimit == null)
  1990. {
  1991. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  1992. }
  1993. if (is_null($oDeletionPlan))
  1994. {
  1995. $oDeletionPlan = new DeletionPlan();
  1996. }
  1997. $this->MakeDeletionPlan($oDeletionPlan);
  1998. $oDeletionPlan->ComputeResults();
  1999. if ($oDeletionPlan->FoundStopper())
  2000. {
  2001. $aIssues = $oDeletionPlan->GetIssues();
  2002. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  2003. }
  2004. else
  2005. {
  2006. // Getting and setting time limit are not symetric:
  2007. // www.php.net/manual/fr/function.set-time-limit.php#72305
  2008. $iPreviousTimeLimit = ini_get('max_execution_time');
  2009. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  2010. {
  2011. foreach ($aToDelete as $iId => $aData)
  2012. {
  2013. $oToDelete = $aData['to_delete'];
  2014. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  2015. // because for each object we would try to update all the preceding ones... that are already deleted
  2016. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  2017. // As a temporary fix: delete only the objects that are still to be deleted...
  2018. if ($oToDelete->m_bIsInDB)
  2019. {
  2020. set_time_limit($iLoopTimeLimit);
  2021. $oToDelete->DBDeleteSingleObject();
  2022. }
  2023. }
  2024. }
  2025. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  2026. {
  2027. foreach ($aToUpdate as $iId => $aData)
  2028. {
  2029. $oToUpdate = $aData['to_reset'];
  2030. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  2031. {
  2032. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  2033. set_time_limit($iLoopTimeLimit);
  2034. $oToUpdate->DBUpdate();
  2035. }
  2036. }
  2037. }
  2038. set_time_limit($iPreviousTimeLimit);
  2039. }
  2040. return $oDeletionPlan;
  2041. }
  2042. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  2043. {
  2044. CMDBObject::SetCurrentChange($oChange);
  2045. $this->DBDelete($oDeletionPlan);
  2046. }
  2047. public function EnumTransitions()
  2048. {
  2049. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  2050. if (empty($sStateAttCode)) return array();
  2051. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  2052. return MetaModel::EnumTransitions(get_class($this), $sState);
  2053. }
  2054. /**
  2055. * Designed as an action to be called when a stop watch threshold times out
  2056. * or from within the framework
  2057. * @param $sStimulusCode
  2058. * @param bool|false $bDoNotWrite
  2059. * @return bool
  2060. * @throws CoreException
  2061. * @throws CoreUnexpectedValue
  2062. */
  2063. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  2064. {
  2065. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  2066. if (empty($sStateAttCode))
  2067. {
  2068. throw new CoreException('No lifecycle for the class '.get_class($this));
  2069. }
  2070. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  2071. $aStateTransitions = $this->EnumTransitions();
  2072. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  2073. {
  2074. // This simulus has no effect in the current state... do nothing
  2075. return true;
  2076. }
  2077. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  2078. // Change the state before proceeding to the actions, this is necessary because an action might
  2079. // trigger another stimuli (alternative: push the stimuli into a queue)
  2080. $sPreviousState = $this->Get($sStateAttCode);
  2081. $sNewState = $aTransitionDef['target_state'];
  2082. $this->Set($sStateAttCode, $sNewState);
  2083. // $aTransitionDef is an
  2084. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  2085. $bSuccess = true;
  2086. foreach ($aTransitionDef['actions'] as $actionHandler)
  2087. {
  2088. if (is_string($actionHandler))
  2089. {
  2090. // Old (pre-2.1.0 modules) action definition without any parameter
  2091. $aActionCallSpec = array($this, $actionHandler);
  2092. $sActionDesc = get_class($this).'::'.$actionHandler;
  2093. if (!is_callable($aActionCallSpec))
  2094. {
  2095. throw new CoreException("Unable to call action: ".get_class($this)."::$actionHandler");
  2096. }
  2097. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  2098. }
  2099. else // if (is_array($actionHandler))
  2100. {
  2101. // New syntax: 'verb' and typed parameters
  2102. $sAction = $actionHandler['verb'];
  2103. $sActionDesc = get_class($this).'::'.$sAction;
  2104. $aParams = array();
  2105. foreach($actionHandler['params'] as $aDefinition)
  2106. {
  2107. $sParamType = array_key_exists('type', $aDefinition) ? $aDefinition['type'] : 'string';
  2108. switch($sParamType)
  2109. {
  2110. case 'int':
  2111. $value = (int)$aDefinition['value'];
  2112. break;
  2113. case 'float':
  2114. $value = (float)$aDefinition['value'];
  2115. break;
  2116. case 'bool':
  2117. $value = (bool)$aDefinition['value'];
  2118. break;
  2119. case 'reference':
  2120. $value = ${$aDefinition['value']};
  2121. break;
  2122. case 'string':
  2123. default:
  2124. $value = (string)$aDefinition['value'];
  2125. }
  2126. $aParams[] = $value;
  2127. }
  2128. $aCallSpec = array($this, $sAction);
  2129. $bRet = call_user_func_array($aCallSpec, $aParams);
  2130. }
  2131. // if one call fails, the whole is considered as failed
  2132. // (in case there is no returned value, null is obtained and means "ok")
  2133. if ($bRet === false)
  2134. {
  2135. IssueLog::Info("Lifecycle action $sActionDesc returned false on object #".$this->GetKey());
  2136. $bSuccess = false;
  2137. }
  2138. }
  2139. if ($bSuccess)
  2140. {
  2141. $sClass = get_class($this);
  2142. // Stop watches
  2143. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2144. {
  2145. if ($oAttDef instanceof AttributeStopWatch)
  2146. {
  2147. $oSW = $this->Get($sAttCode);
  2148. if (in_array($sNewState, $oAttDef->GetStates()))
  2149. {
  2150. $oSW->Start($this, $oAttDef);
  2151. }
  2152. else
  2153. {
  2154. $oSW->Stop($this, $oAttDef);
  2155. }
  2156. $this->Set($sAttCode, $oSW);
  2157. }
  2158. }
  2159. if (!$bDoNotWrite)
  2160. {
  2161. $this->DBWrite();
  2162. }
  2163. // Change state triggers...
  2164. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  2165. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  2166. while ($oTrigger = $oSet->Fetch())
  2167. {
  2168. $oTrigger->DoActivate($this->ToArgs('this'));
  2169. }
  2170. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  2171. while ($oTrigger = $oSet->Fetch())
  2172. {
  2173. $oTrigger->DoActivate($this->ToArgs('this'));
  2174. }
  2175. }
  2176. return $bSuccess;
  2177. }
  2178. /**
  2179. * Designed as an action to be called when a stop watch threshold times out
  2180. */
  2181. public function ResetStopWatch($sAttCode)
  2182. {
  2183. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2184. if (!$oAttDef instanceof AttributeStopWatch)
  2185. {
  2186. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  2187. }
  2188. $oSW = $this->Get($sAttCode);
  2189. $oSW->Reset($this, $oAttDef);
  2190. $this->Set($sAttCode, $oSW);
  2191. return true;
  2192. }
  2193. /**
  2194. * Lifecycle action: Recover the default value (aka when an object is being created)
  2195. */
  2196. public function Reset($sAttCode)
  2197. {
  2198. $this->Set($sAttCode, $this->GetDefaultValue($sAttCode));
  2199. return true;
  2200. }
  2201. /**
  2202. * Lifecycle action: Copy an attribute to another
  2203. */
  2204. public function Copy($sDestAttCode, $sSourceAttCode)
  2205. {
  2206. $this->Set($sDestAttCode, $this->Get($sSourceAttCode));
  2207. return true;
  2208. }
  2209. /**
  2210. * Lifecycle action: Set the current date/time for the given attribute
  2211. */
  2212. public function SetCurrentDate($sAttCode)
  2213. {
  2214. $this->Set($sAttCode, time());
  2215. return true;
  2216. }
  2217. /**
  2218. * Lifecycle action: Set the current logged in user for the given attribute
  2219. */
  2220. public function SetCurrentUser($sAttCode)
  2221. {
  2222. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2223. if ($oAttDef instanceof AttributeString)
  2224. {
  2225. // Note: the user friendly name is the contact friendly name if a contact is attached to the logged in user
  2226. $this->Set($sAttCode, UserRights::GetUserFriendlyName());
  2227. }
  2228. else
  2229. {
  2230. if ($oAttDef->IsExternalKey())
  2231. {
  2232. if ($oAttDef->GetTargetClass() != 'User')
  2233. {
  2234. throw new Exception("SetCurrentUser: the attribute $sAttCode must be an external key to 'User', found '".$oAttDef->GetTargetClass()."'");
  2235. }
  2236. }
  2237. $this->Set($sAttCode, UserRights::GetUserId());
  2238. }
  2239. return true;
  2240. }
  2241. /**
  2242. * Lifecycle action: Set the current logged in CONTACT for the given attribute
  2243. */
  2244. public function SetCurrentPerson($sAttCode)
  2245. {
  2246. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2247. if ($oAttDef instanceof AttributeString)
  2248. {
  2249. $iPerson = UserRights::GetContactId();
  2250. if ($iPerson == 0)
  2251. {
  2252. $this->Set($sAttCode, '');
  2253. }
  2254. else
  2255. {
  2256. $oPerson = MetaModel::GetObject('Person', $iPerson);
  2257. $this->Set($sAttCode, $oPerson->Get('friendlyname'));
  2258. }
  2259. }
  2260. else
  2261. {
  2262. if ($oAttDef->IsExternalKey())
  2263. {
  2264. if (!MetaModel::IsParentClass($oAttDef->GetTargetClass(), 'Person'))
  2265. {
  2266. throw new Exception("SetCurrentContact: the attribute $sAttCode must be an external key to 'Person' or any other class above 'Person', found '".$oAttDef->GetTargetClass()."'");
  2267. }
  2268. }
  2269. $this->Set($sAttCode, UserRights::GetContactId());
  2270. }
  2271. return true;
  2272. }
  2273. /**
  2274. * Lifecycle action: Set the time elapsed since a reference point
  2275. */
  2276. public function SetElapsedTime($sAttCode, $sRefAttCode, $sWorkingTimeComputer = null)
  2277. {
  2278. if (is_null($sWorkingTimeComputer))
  2279. {
  2280. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  2281. }
  2282. $oComputer = new $sWorkingTimeComputer();
  2283. $aCallSpec = array($oComputer, 'GetOpenDuration');
  2284. if (!is_callable($aCallSpec))
  2285. {
  2286. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  2287. }
  2288. $iStartTime = AttributeDateTime::GetAsUnixSeconds($this->Get($sRefAttCode));
  2289. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  2290. $oEndDate = new DateTime(); // now
  2291. if (class_exists('WorkingTimeRecorder'))
  2292. {
  2293. $sClass = get_class($this);
  2294. WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', array("Class:$sClass/Attribute:$sAttCode"));
  2295. }
  2296. $iElapsed = call_user_func($aCallSpec, $this, $oStartDate, $oEndDate);
  2297. if (class_exists('WorkingTimeRecorder'))
  2298. {
  2299. WorkingTimeRecorder::End();
  2300. }
  2301. $this->Set($sAttCode, $iElapsed);
  2302. return true;
  2303. }
  2304. /**
  2305. * Create query parameters (SELECT ... WHERE service = :this->service_id)
  2306. * to be used with the APIs DBObjectSearch/DBObjectSet
  2307. *
  2308. * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
  2309. * in VariableExpression::Render()
  2310. */
  2311. public function ToArgsForQuery($sArgName = 'this')
  2312. {
  2313. return array($sArgName.'->object()' => $this);
  2314. }
  2315. /**
  2316. * Create template placeholders: now equivalent to ToArgsForQuery since the actual
  2317. * template placeholders are computed on demand.
  2318. */
  2319. public function ToArgs($sArgName = 'this')
  2320. {
  2321. return $this->ToArgsForQuery($sArgName);
  2322. }
  2323. public function GetForTemplate($sPlaceholderAttCode)
  2324. {
  2325. $ret = null;
  2326. if (preg_match('/^([^-]+)-(>|&gt;)(.+)$/', $sPlaceholderAttCode, $aMatches)) // Support both syntaxes: this->xxx or this-&gt;xxx for HTML compatibility
  2327. {
  2328. $sExtKeyAttCode = $aMatches[1];
  2329. $sRemoteAttCode = $aMatches[3];
  2330. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  2331. {
  2332. throw new CoreException("Unknown attribute '$sExtKeyAttCode' for the class ".get_class($this));
  2333. }
  2334. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  2335. if (!$oKeyAttDef instanceof AttributeExternalKey)
  2336. {
  2337. throw new CoreException("'$sExtKeyAttCode' is not an external key of the class ".get_class($this));
  2338. }
  2339. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  2340. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  2341. if (is_null($oRemoteObj))
  2342. {
  2343. $ret = Dict::S('UI:UndefinedObject');
  2344. }
  2345. else
  2346. {
  2347. // Recurse
  2348. $ret = $oRemoteObj->GetForTemplate($sRemoteAttCode);
  2349. }
  2350. }
  2351. else
  2352. {
  2353. switch($sPlaceholderAttCode)
  2354. {
  2355. case 'id':
  2356. $ret = $this->GetKey();
  2357. break;
  2358. case 'name()':
  2359. $ret = $this->GetName();
  2360. break;
  2361. default:
  2362. if (preg_match('/^([^(]+)\\((.*)\\)$/', $sPlaceholderAttCode, $aMatches))
  2363. {
  2364. $sVerb = $aMatches[1];
  2365. $sAttCode = $aMatches[2];
  2366. }
  2367. else
  2368. {
  2369. $sVerb = '';
  2370. $sAttCode = $sPlaceholderAttCode;
  2371. }
  2372. if ($sVerb == 'hyperlink')
  2373. {
  2374. $sPortalId = ($sAttCode === '') ? 'console' : $sAttCode;
  2375. if (!array_key_exists($sPortalId, self::$aPortalToURLMaker))
  2376. {
  2377. throw new Exception("Unknown portal id '$sPortalId' in placeholder '$sPlaceholderAttCode''");
  2378. }
  2379. $ret = $this->GetHyperlink(self::$aPortalToURLMaker[$sPortalId], false);
  2380. }
  2381. else
  2382. {
  2383. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2384. $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this);
  2385. }
  2386. }
  2387. if ($ret === null)
  2388. {
  2389. $ret = '';
  2390. }
  2391. }
  2392. return $ret;
  2393. }
  2394. static protected $aPortalToURLMaker = array('console' => 'iTopStandardURLMaker', 'portal' => 'PortalURLMaker');
  2395. /**
  2396. * Associate a portal to a class that implements iDBObjectURLMaker,
  2397. * and which will be invoked with placeholders like $this->org_id->hyperlink(portal)$
  2398. *
  2399. * @param $sPortalId Identifies the portal. Conventions: the main portal is 'console', The user requests portal is 'portal'.
  2400. * @param $sUrlMakerClass
  2401. */
  2402. static public function RegisterURLMakerClass($sPortalId, $sUrlMakerClass)
  2403. {
  2404. self::$aPortalToURLMaker[$sPortalId] = $sUrlMakerClass;
  2405. }
  2406. // To be optionaly overloaded
  2407. protected function OnInsert()
  2408. {
  2409. }
  2410. // To be optionaly overloaded
  2411. protected function AfterInsert()
  2412. {
  2413. }
  2414. // To be optionaly overloaded
  2415. protected function OnUpdate()
  2416. {
  2417. }
  2418. // To be optionaly overloaded
  2419. protected function AfterUpdate()
  2420. {
  2421. }
  2422. // To be optionaly overloaded
  2423. protected function OnDelete()
  2424. {
  2425. }
  2426. // To be optionaly overloaded
  2427. protected function AfterDelete()
  2428. {
  2429. }
  2430. /**
  2431. * Common to the recording of link set changes (add/remove/modify)
  2432. */
  2433. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  2434. {
  2435. if ($iLinkSetOwnerId <= 0)
  2436. {
  2437. return null;
  2438. }
  2439. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  2440. {
  2441. // The link set owner class does not keep track of its history
  2442. return null;
  2443. }
  2444. // Determine the linked item class and id
  2445. //
  2446. if ($oLinkSet->IsIndirect())
  2447. {
  2448. // The "item" is on the other end (N-N links)
  2449. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  2450. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  2451. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  2452. if ($aOriginalValues)
  2453. {
  2454. // Get the value from the original values
  2455. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  2456. }
  2457. else
  2458. {
  2459. $iItemId = $this->Get($sExtKeyToRemote);
  2460. }
  2461. }
  2462. else
  2463. {
  2464. // I am the "item" (1-N links)
  2465. $sItemClass = get_class($this);
  2466. $iItemId = $this->GetKey();
  2467. }
  2468. // Get the remote object, to determine its exact class
  2469. // Possible optimization: implement a tool in MetaModel, to get the final class of an object (not always querying + query reduced to a select on the root table!
  2470. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  2471. if ($oOwner)
  2472. {
  2473. $sLinkSetOwnerClass = get_class($oOwner);
  2474. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  2475. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  2476. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  2477. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  2478. $oMyChangeOp->Set("item_class", $sItemClass);
  2479. $oMyChangeOp->Set("item_id", $iItemId);
  2480. return $oMyChangeOp;
  2481. }
  2482. else
  2483. {
  2484. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  2485. return null;
  2486. }
  2487. }
  2488. /**
  2489. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  2490. */
  2491. private function RecordLinkSetListChange($bAdd = true)
  2492. {
  2493. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2494. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2495. {
  2496. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2497. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2498. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2499. if ($oMyChangeOp)
  2500. {
  2501. if ($bAdd)
  2502. {
  2503. $oMyChangeOp->Set("type", "added");
  2504. }
  2505. else
  2506. {
  2507. $oMyChangeOp->Set("type", "removed");
  2508. }
  2509. $iId = $oMyChangeOp->DBInsertNoReload();
  2510. }
  2511. }
  2512. }
  2513. protected function RecordObjCreation()
  2514. {
  2515. $this->RecordLinkSetListChange(true);
  2516. }
  2517. protected function RecordObjDeletion($objkey)
  2518. {
  2519. $this->RecordLinkSetListChange(false);
  2520. }
  2521. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  2522. {
  2523. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2524. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2525. {
  2526. if (array_key_exists($sExtKeyAttCode, $aValues))
  2527. {
  2528. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2529. // Keep track of link added/removed
  2530. //
  2531. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  2532. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2533. if ($oMyChangeOp)
  2534. {
  2535. $oMyChangeOp->Set("type", "added");
  2536. $oMyChangeOp->DBInsertNoReload();
  2537. }
  2538. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  2539. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  2540. if ($oMyChangeOp)
  2541. {
  2542. $oMyChangeOp->Set("type", "removed");
  2543. $oMyChangeOp->DBInsertNoReload();
  2544. }
  2545. }
  2546. else
  2547. {
  2548. // Keep track of link changes
  2549. //
  2550. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  2551. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2552. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  2553. if ($oMyChangeOp)
  2554. {
  2555. $oMyChangeOp->Set("link_id", $this->GetKey());
  2556. $iId = $oMyChangeOp->DBInsertNoReload();
  2557. }
  2558. }
  2559. }
  2560. }
  2561. // Return an empty set for the parent of all
  2562. // May be overloaded.
  2563. // Anyhow, this way of implementing the relations suffers limitations (not handling the redundancy)
  2564. // and you should consider defining those things in XML.
  2565. public static function GetRelationQueries($sRelCode)
  2566. {
  2567. return array();
  2568. }
  2569. // Reserved: do not overload
  2570. public static function GetRelationQueriesEx($sRelCode)
  2571. {
  2572. return array();
  2573. }
  2574. /**
  2575. * Will be deprecated soon - use GetRelatedObjectsDown/Up instead to take redundancy into account
  2576. */
  2577. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  2578. {
  2579. // Temporary patch: until the impact analysis GUI gets rewritten,
  2580. // let's consider that "depends on" is equivalent to "impacts/up"
  2581. // The current patch has been implemented in DBObject and MetaModel
  2582. $sHackedRelCode = $sRelCode;
  2583. $bDown = true;
  2584. if ($sRelCode == 'depends on')
  2585. {
  2586. $sHackedRelCode = 'impacts';
  2587. $bDown = false;
  2588. }
  2589. foreach (MetaModel::EnumRelationQueries(get_class($this), $sHackedRelCode, $bDown) as $sDummy => $aQueryInfo)
  2590. {
  2591. $sQuery = $bDown ? $aQueryInfo['sQueryDown'] : $aQueryInfo['sQueryUp'];
  2592. //$bPropagate = $aQueryInfo["bPropagate"];
  2593. //$iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  2594. $iDepth = $iMaxDepth - 1;
  2595. // Note: the loop over the result set has been written in an unusual way for error reporting purposes
  2596. // In the case of a wrong query parameter name, the error occurs on the first call to Fetch,
  2597. // thus we need to have this first call into the try/catch, but
  2598. // we do NOT want to nest the try/catch for the error message to be clear
  2599. try
  2600. {
  2601. $oFlt = DBObjectSearch::FromOQL($sQuery);
  2602. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgsForQuery());
  2603. $oObj = $oObjSet->Fetch();
  2604. }
  2605. catch (Exception $e)
  2606. {
  2607. $sClassOfDefinition = $aQueryInfo['_legacy_'] ? get_class($this).'(or a parent)::GetRelationQueries()' : $aQueryInfo['sDefinedInClass'];
  2608. throw new Exception("Wrong query for the relation $sRelCode/$sClassOfDefinition/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
  2609. }
  2610. if ($oObj)
  2611. {
  2612. do
  2613. {
  2614. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  2615. $sObjKey = $oObj->GetKey();
  2616. if (array_key_exists($sRootClass, $aResults))
  2617. {
  2618. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  2619. {
  2620. continue; // already visited, skip
  2621. }
  2622. }
  2623. $aResults[$sRootClass][$sObjKey] = $oObj;
  2624. if ($iDepth > 0)
  2625. {
  2626. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  2627. }
  2628. }
  2629. while ($oObj = $oObjSet->Fetch());
  2630. }
  2631. }
  2632. return $aResults;
  2633. }
  2634. /**
  2635. * Compute the "RelatedObjects" (forward or "down" direction) for the object
  2636. * for the specified relation
  2637. *
  2638. * @param string $sRelCode The code of the relation to use for the computation
  2639. * @param int $iMaxDepth Maximum recursion depth
  2640. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2641. *
  2642. * @return RelationGraph The graph of all the related objects
  2643. */
  2644. public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2645. {
  2646. $oGraph = new RelationGraph();
  2647. $oGraph->AddSourceObject($this);
  2648. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2649. return $oGraph;
  2650. }
  2651. /**
  2652. * Compute the "RelatedObjects" (reverse or "up" direction) for the object
  2653. * for the specified relation
  2654. *
  2655. * @param string $sRelCode The code of the relation to use for the computation
  2656. * @param int $iMaxDepth Maximum recursion depth
  2657. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2658. *
  2659. * @return RelationGraph The graph of all the related objects
  2660. */
  2661. public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2662. {
  2663. $oGraph = new RelationGraph();
  2664. $oGraph->AddSourceObject($this);
  2665. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2666. return $oGraph;
  2667. }
  2668. public function GetReferencingObjects($bAllowAllData = false)
  2669. {
  2670. $aDependentObjects = array();
  2671. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  2672. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  2673. {
  2674. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  2675. {
  2676. // skip if this external key is behind an external field
  2677. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  2678. $oSearch = new DBObjectSearch($sRemoteClass);
  2679. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  2680. if ($bAllowAllData)
  2681. {
  2682. $oSearch->AllowAllData();
  2683. }
  2684. $oSet = new CMDBObjectSet($oSearch);
  2685. if ($oSet->Count() > 0)
  2686. {
  2687. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  2688. 'attribute' => $oExtKeyAttDef,
  2689. 'objects' => $oSet,
  2690. );
  2691. }
  2692. }
  2693. }
  2694. return $aDependentObjects;
  2695. }
  2696. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  2697. {
  2698. static $iLoopTimeLimit = null;
  2699. if ($iLoopTimeLimit == null)
  2700. {
  2701. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2702. }
  2703. $sClass = get_class($this);
  2704. $iThisId = $this->GetKey();
  2705. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  2706. if (array_key_exists($sClass, $aVisited))
  2707. {
  2708. if (in_array($iThisId, $aVisited[$sClass]))
  2709. {
  2710. return;
  2711. }
  2712. }
  2713. $aVisited[$sClass] = $iThisId;
  2714. if ($iDeleteOption == DEL_MANUAL)
  2715. {
  2716. // Stop the recursion here
  2717. return;
  2718. }
  2719. // Check the node itself
  2720. $this->DoCheckToDelete($oDeletionPlan);
  2721. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  2722. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  2723. // Getting and setting time limit are not symetric:
  2724. // www.php.net/manual/fr/function.set-time-limit.php#72305
  2725. $iPreviousTimeLimit = ini_get('max_execution_time');
  2726. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  2727. {
  2728. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  2729. {
  2730. set_time_limit($iLoopTimeLimit);
  2731. $oAttDef = $aData['attribute'];
  2732. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  2733. $oDepSet = $aData['objects'];
  2734. $oDepSet->Rewind();
  2735. while ($oDependentObj = $oDepSet->fetch())
  2736. {
  2737. $iId = $oDependentObj->GetKey();
  2738. if ($oAttDef->IsNullAllowed())
  2739. {
  2740. // Optional external key, list to reset
  2741. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  2742. {
  2743. // Move the child up one level i.e. set the same parent as the current object
  2744. $iParentId = $this->Get($oAttDef->GetCode());
  2745. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  2746. }
  2747. else
  2748. {
  2749. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  2750. }
  2751. }
  2752. else
  2753. {
  2754. // Mandatory external key, list to delete
  2755. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  2756. }
  2757. }
  2758. }
  2759. }
  2760. set_time_limit($iPreviousTimeLimit);
  2761. }
  2762. /**
  2763. * WILL DEPRECATED SOON
  2764. * Caching relying on an object set is not efficient since 2.0.3
  2765. * Use GetSynchroData instead
  2766. *
  2767. * Get all the synchro replica related to this object
  2768. * @param none
  2769. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  2770. */
  2771. public function GetMasterReplica()
  2772. {
  2773. $sOQL = "SELECT replica,datasource FROM SynchroReplica AS replica JOIN SynchroDataSource AS datasource ON replica.sync_source_id=datasource.id WHERE replica.dest_class = :dest_class AND replica.dest_id = :dest_id";
  2774. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2775. return $oReplicaSet;
  2776. }
  2777. /**
  2778. * Get all the synchro data related to this object
  2779. * @param none
  2780. * @return array of data_source_id => array
  2781. * 'source' => $oSource,
  2782. * 'attributes' => array of $oSynchroAttribute
  2783. * 'replica' => array of $oReplica (though only one should exist, misuse of the data sync can have this consequence)
  2784. */
  2785. public function GetSynchroData()
  2786. {
  2787. if (is_null($this->m_aSynchroData))
  2788. {
  2789. $sOQL = "SELECT replica,datasource FROM SynchroReplica AS replica JOIN SynchroDataSource AS datasource ON replica.sync_source_id=datasource.id WHERE replica.dest_class = :dest_class AND replica.dest_id = :dest_id";
  2790. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2791. $this->m_aSynchroData = array();
  2792. while($aData = $oReplicaSet->FetchAssoc())
  2793. {
  2794. $iSourceId = $aData['datasource']->GetKey();
  2795. if (!array_key_exists($iSourceId, $this->m_aSynchroData))
  2796. {
  2797. $aAttributes = array();
  2798. $oAttrSet = $aData['datasource']->Get('attribute_list');
  2799. while($oSyncAttr = $oAttrSet->Fetch())
  2800. {
  2801. $aAttributes[$oSyncAttr->Get('attcode')] = $oSyncAttr;
  2802. }
  2803. $this->m_aSynchroData[$iSourceId] = array(
  2804. 'source' => $aData['datasource'],
  2805. 'attributes' => $aAttributes,
  2806. 'replica' => array()
  2807. );
  2808. }
  2809. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2810. $this->m_aSynchroData[$iSourceId]['replica'][] = $aData['replica'];
  2811. }
  2812. }
  2813. return $this->m_aSynchroData;
  2814. }
  2815. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2816. {
  2817. $iFlags = OPT_ATT_NORMAL;
  2818. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  2819. {
  2820. if ($iSourceId == SynchroExecution::GetCurrentTaskId())
  2821. {
  2822. // Ignore the current task (check to write => ok)
  2823. continue;
  2824. }
  2825. // Assumption: one replica - take the first one!
  2826. $oReplica = reset($aSourceData['replica']);
  2827. $oSource = $aSourceData['source'];
  2828. if (array_key_exists($sAttCode, $aSourceData['attributes']))
  2829. {
  2830. $oSyncAttr = $aSourceData['attributes'][$sAttCode];
  2831. if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2832. {
  2833. $iFlags |= OPT_ATT_SLAVE;
  2834. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2835. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2836. }
  2837. }
  2838. }
  2839. return $iFlags;
  2840. }
  2841. public function InSyncScope()
  2842. {
  2843. //
  2844. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2845. //
  2846. static $aSynchroClasses = null;
  2847. if (is_null($aSynchroClasses))
  2848. {
  2849. $aSynchroClasses = array();
  2850. $sOQL = "SELECT SynchroDataSource AS datasource";
  2851. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2852. while($oSource = $oSourceSet->Fetch())
  2853. {
  2854. $sTarget = $oSource->Get('scope_class');
  2855. $aSynchroClasses[] = $sTarget;
  2856. }
  2857. }
  2858. foreach($aSynchroClasses as $sClass)
  2859. {
  2860. if ($this instanceof $sClass)
  2861. {
  2862. return true;
  2863. }
  2864. }
  2865. return false;
  2866. }
  2867. /////////////////////////////////////////////////////////////////////////
  2868. //
  2869. // Experimental iDisplay implementation
  2870. //
  2871. /////////////////////////////////////////////////////////////////////////
  2872. public static function MapContextParam($sContextParam)
  2873. {
  2874. return null;
  2875. }
  2876. public function GetHilightClass()
  2877. {
  2878. $sCode = $this->ComputeHighlightCode();
  2879. if($sCode != '')
  2880. {
  2881. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  2882. if (array_key_exists($sCode, $aHighlightScale))
  2883. {
  2884. return $aHighlightScale[$sCode]['color'];
  2885. }
  2886. }
  2887. return HILIGHT_CLASS_NONE;
  2888. }
  2889. public function DisplayDetails(WebPage $oPage, $bEditMode = false)
  2890. {
  2891. $oPage->add('<h1>'.MetaModel::GetName(get_class($this)).': '.$this->GetName().'</h1>');
  2892. $aValues = array();
  2893. $aList = MetaModel::FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2894. if (empty($aList))
  2895. {
  2896. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2897. }
  2898. foreach($aList as $sAttCode)
  2899. {
  2900. $aValues[$sAttCode] = array('label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode));
  2901. }
  2902. $oPage->details($aValues);
  2903. }
  2904. const CALLBACK_AFTERINSERT = 0;
  2905. /**
  2906. * Register a call back that will be called when some internal event happens
  2907. *
  2908. * @param $iType string Any of the CALLBACK_x constants
  2909. * @param $callback callable Call specification like a function name, or array('<class>', '<method>') or array($object, '<method>')
  2910. * @param $aParameters Array Values that will be passed to the callback, after $this
  2911. */
  2912. public function RegisterCallback($iType, $callback, $aParameters = array())
  2913. {
  2914. $sCallBackName = '';
  2915. if (!is_callable($callback, false, $sCallBackName))
  2916. {
  2917. throw new Exception('Registering an unknown/protected function or wrong syntax for the call spec: '.$sCallBackName);
  2918. }
  2919. $this->m_aCallbacks[$iType][] = array(
  2920. 'callback' => $callback,
  2921. 'params' => $aParameters
  2922. );
  2923. }
  2924. /**
  2925. * Computes a text-like fingerprint identifying the content of the object
  2926. * but excluding the specified columns
  2927. * @param $aExcludedColumns array The list of columns to exclude
  2928. * @return string
  2929. */
  2930. public function Fingerprint($aExcludedColumns = array())
  2931. {
  2932. $sFingerprint = '';
  2933. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2934. {
  2935. if (!in_array($sAttCode, $aExcludedColumns))
  2936. {
  2937. if ($oAttDef->IsPartOfFingerprint())
  2938. {
  2939. $sFingerprint .= chr(0).$oAttDef->Fingerprint($this->Get($sAttCode));
  2940. }
  2941. }
  2942. }
  2943. return $sFingerprint;
  2944. }
  2945. /**
  2946. * Execute a set of scripted actions onto the current object
  2947. * See ExecAction for the syntax and features of the scripted actions
  2948. *
  2949. * @param $aActions array of statements (e.g. "set(name, Made after $source->name$)")
  2950. * @param $aSourceObjects Array of Alias => Context objects (Convention: some statements require the 'source' element
  2951. * @throws Exception
  2952. */
  2953. public function ExecActions($aActions, $aSourceObjects)
  2954. {
  2955. foreach($aActions as $sAction)
  2956. {
  2957. try
  2958. {
  2959. if (preg_match('/^(\S*)\s*\((.*)\)$/ms', $sAction, $aMatches)) // multiline and newline matched by a dot
  2960. {
  2961. $sVerb = trim($aMatches[1]);
  2962. $sParams = $aMatches[2];
  2963. // the coma is the separator for the parameters
  2964. // comas can be escaped: \,
  2965. $sParams = str_replace(array("\\\\", "\\,"), array("__backslash__", "__coma__"), $sParams);
  2966. $sParams = trim($sParams);
  2967. if (strlen($sParams) == 0)
  2968. {
  2969. $aParams = array();
  2970. }
  2971. else
  2972. {
  2973. $aParams = explode(',', $sParams);
  2974. foreach ($aParams as &$sParam)
  2975. {
  2976. $sParam = str_replace(array("__backslash__", "__coma__"), array("\\", ","), $sParam);
  2977. $sParam = trim($sParam);
  2978. }
  2979. }
  2980. $this->ExecAction($sVerb, $aParams, $aSourceObjects);
  2981. }
  2982. else
  2983. {
  2984. throw new Exception("Invalid syntax");
  2985. }
  2986. }
  2987. catch(Exception $e)
  2988. {
  2989. throw new Exception('Action: '.$sAction.' - '.$e->getMessage());
  2990. }
  2991. }
  2992. }
  2993. /**
  2994. * Helper to copy an attribute between two objects (in memory)
  2995. * Originally designed for ExecAction()
  2996. */
  2997. public function CopyAttribute($oSourceObject, $sSourceAttCode, $sDestAttCode)
  2998. {
  2999. if ($sSourceAttCode == 'id')
  3000. {
  3001. $oSourceAttDef = null;
  3002. }
  3003. else
  3004. {
  3005. if (!MetaModel::IsValidAttCode(get_class($this), $sDestAttCode))
  3006. {
  3007. throw new Exception("Unknown attribute ".get_class($this)."::".$sDestAttCode);
  3008. }
  3009. if (!MetaModel::IsValidAttCode(get_class($oSourceObject), $sSourceAttCode))
  3010. {
  3011. throw new Exception("Unknown attribute ".get_class($oSourceObject)."::".$sSourceAttCode);
  3012. }
  3013. $oSourceAttDef = MetaModel::GetAttributeDef(get_class($oSourceObject), $sSourceAttCode);
  3014. }
  3015. if (is_object($oSourceAttDef) && $oSourceAttDef->IsLinkSet())
  3016. {
  3017. // The copy requires that we create a new object set (the semantic of DBObject::Set is unclear about link sets)
  3018. $oDestSet = DBObjectSet::FromScratch($oSourceAttDef->GetLinkedClass());
  3019. $oSourceSet = $oSourceObject->Get($sSourceAttCode);
  3020. $oSourceSet->Rewind();
  3021. while ($oSourceLink = $oSourceSet->Fetch())
  3022. {
  3023. // Clone the link
  3024. $sLinkClass = get_class($oSourceLink);
  3025. $oLinkClone = MetaModel::NewObject($sLinkClass);
  3026. foreach(MetaModel::ListAttributeDefs($sLinkClass) as $sAttCode => $oAttDef)
  3027. {
  3028. // As of now, ignore other attribute (do not attempt to recurse!)
  3029. if ($oAttDef->IsScalar())
  3030. {
  3031. $oLinkClone->Set($sAttCode, $oSourceLink->Get($sAttCode));
  3032. }
  3033. }
  3034. // Not necessary - this will be handled by DBObject
  3035. // $oLinkClone->Set($oSourceAttDef->GetExtKeyToMe(), 0);
  3036. $oDestSet->AddObject($oLinkClone);
  3037. }
  3038. $this->Set($sDestAttCode, $oDestSet);
  3039. }
  3040. else
  3041. {
  3042. $this->Set($sDestAttCode, $oSourceObject->Get($sSourceAttCode));
  3043. }
  3044. }
  3045. /**
  3046. * Execute a scripted action onto the current object
  3047. * - clone (att1, att2, att3, ...)
  3048. * - clone_scalars ()
  3049. * - copy (source_att, dest_att)
  3050. * - reset (att)
  3051. * - nullify (att)
  3052. * - set (att, value (placeholders $source->att$ or $current_date$, or $current_contact_id$, ...))
  3053. * - append (att, value (placeholders $source->att$ or $current_date$, or $current_contact_id$, ...))
  3054. * - add_to_list (source_key_att, dest_att)
  3055. * - add_to_list (source_key_att, dest_att, lnk_att, lnk_att_value)
  3056. * - apply_stimulus (stimulus)
  3057. * - call_method (method_name)
  3058. *
  3059. * @param $sVerb string Any of the verb listed above (e.g. "set")
  3060. * @param $aParams array of strings (e.g. array('name', 'copied from $source->name$')
  3061. * @param $aSourceObjects Array of Alias => Context objects (Convention: some statements require the 'source' element
  3062. * @throws CoreException
  3063. * @throws CoreUnexpectedValue
  3064. * @throws Exception
  3065. */
  3066. public function ExecAction($sVerb, $aParams, $aSourceObjects)
  3067. {
  3068. switch($sVerb)
  3069. {
  3070. case 'clone':
  3071. if (!array_key_exists('source', $aSourceObjects))
  3072. {
  3073. throw new Exception('Missing conventional "source" object');
  3074. }
  3075. $oObjectToRead = $aSourceObjects['source'];
  3076. foreach($aParams as $sAttCode)
  3077. {
  3078. $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
  3079. }
  3080. break;
  3081. case 'clone_scalars':
  3082. if (!array_key_exists('source', $aSourceObjects))
  3083. {
  3084. throw new Exception('Missing conventional "source" object');
  3085. }
  3086. $oObjectToRead = $aSourceObjects['source'];
  3087. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  3088. {
  3089. if ($oAttDef->IsScalar())
  3090. {
  3091. $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
  3092. }
  3093. }
  3094. break;
  3095. case 'copy':
  3096. if (!array_key_exists('source', $aSourceObjects))
  3097. {
  3098. throw new Exception('Missing conventional "source" object');
  3099. }
  3100. $oObjectToRead = $aSourceObjects['source'];
  3101. if (!array_key_exists(0, $aParams))
  3102. {
  3103. throw new Exception('Missing argument #1: source attribute');
  3104. }
  3105. $sSourceAttCode = $aParams[0];
  3106. if (!array_key_exists(1, $aParams))
  3107. {
  3108. throw new Exception('Missing argument #2: target attribute');
  3109. }
  3110. $sDestAttCode = $aParams[1];
  3111. $this->CopyAttribute($oObjectToRead, $sSourceAttCode, $sDestAttCode);
  3112. break;
  3113. case 'reset':
  3114. if (!array_key_exists(0, $aParams))
  3115. {
  3116. throw new Exception('Missing argument #1: target attribute');
  3117. }
  3118. $sAttCode = $aParams[0];
  3119. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3120. {
  3121. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3122. }
  3123. $this->Set($sAttCode, $this->GetDefaultValue($sAttCode));
  3124. break;
  3125. case 'nullify':
  3126. if (!array_key_exists(0, $aParams))
  3127. {
  3128. throw new Exception('Missing argument #1: target attribute');
  3129. }
  3130. $sAttCode = $aParams[0];
  3131. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3132. {
  3133. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3134. }
  3135. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  3136. $this->Set($sAttCode, $oAttDef->GetNullValue());
  3137. break;
  3138. case 'set':
  3139. if (!array_key_exists(0, $aParams))
  3140. {
  3141. throw new Exception('Missing argument #1: target attribute');
  3142. }
  3143. $sAttCode = $aParams[0];
  3144. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3145. {
  3146. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3147. }
  3148. if (!array_key_exists(1, $aParams))
  3149. {
  3150. throw new Exception('Missing argument #2: value to set');
  3151. }
  3152. $sRawValue = $aParams[1];
  3153. $aContext = array();
  3154. foreach ($aSourceObjects as $sAlias => $oObject)
  3155. {
  3156. $aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
  3157. }
  3158. $aContext['current_contact_id'] = UserRights::GetContactId();
  3159. $aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
  3160. $aContext['current_date'] = date(AttributeDate::GetSQLFormat());
  3161. $aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
  3162. $sValue = MetaModel::ApplyParams($sRawValue, $aContext);
  3163. $this->Set($sAttCode, $sValue);
  3164. break;
  3165. case 'append':
  3166. if (!array_key_exists(0, $aParams))
  3167. {
  3168. throw new Exception('Missing argument #1: target attribute');
  3169. }
  3170. $sAttCode = $aParams[0];
  3171. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3172. {
  3173. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3174. }
  3175. if (!array_key_exists(1, $aParams))
  3176. {
  3177. throw new Exception('Missing argument #2: value to append');
  3178. }
  3179. $sRawAddendum = $aParams[1];
  3180. $aContext = array();
  3181. foreach ($aSourceObjects as $sAlias => $oObject)
  3182. {
  3183. $aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
  3184. }
  3185. $aContext['current_contact_id'] = UserRights::GetContactId();
  3186. $aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
  3187. $aContext['current_date'] = date(AttributeDate::GetSQLFormat());
  3188. $aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
  3189. $sAddendum = MetaModel::ApplyParams($sRawAddendum, $aContext);
  3190. $this->Set($sAttCode, $this->Get($sAttCode).$sAddendum);
  3191. break;
  3192. case 'add_to_list':
  3193. if (!array_key_exists('source', $aSourceObjects))
  3194. {
  3195. throw new Exception('Missing conventional "source" object');
  3196. }
  3197. $oObjectToRead = $aSourceObjects['source'];
  3198. if (!array_key_exists(0, $aParams))
  3199. {
  3200. throw new Exception('Missing argument #1: source attribute');
  3201. }
  3202. $sSourceKeyAttCode = $aParams[0];
  3203. if (($sSourceKeyAttCode != 'id') && !MetaModel::IsValidAttCode(get_class($oObjectToRead), $sSourceKeyAttCode))
  3204. {
  3205. throw new Exception("Unknown attribute ".get_class($oObjectToRead)."::".$sSourceKeyAttCode);
  3206. }
  3207. if (!array_key_exists(1, $aParams))
  3208. {
  3209. throw new Exception('Missing argument #2: target attribute (link set)');
  3210. }
  3211. $sTargetListAttCode = $aParams[1]; // indirect !!!
  3212. if (!MetaModel::IsValidAttCode(get_class($this), $sTargetListAttCode))
  3213. {
  3214. throw new Exception("Unknown attribute ".get_class($this)."::".$sTargetListAttCode);
  3215. }
  3216. if (isset($aParams[2]) && isset($aParams[3]))
  3217. {
  3218. $sRoleAttCode = $aParams[2];
  3219. $sRoleValue = $aParams[3];
  3220. }
  3221. $iObjKey = $oObjectToRead->Get($sSourceKeyAttCode);
  3222. if ($iObjKey > 0)
  3223. {
  3224. $oLinkSet = $this->Get($sTargetListAttCode);
  3225. $oListAttDef = MetaModel::GetAttributeDef(get_class($this), $sTargetListAttCode);
  3226. $oLnk = MetaModel::NewObject($oListAttDef->GetLinkedClass());
  3227. $oLnk->Set($oListAttDef->GetExtKeyToRemote(), $iObjKey);
  3228. if (isset($sRoleAttCode))
  3229. {
  3230. if (!MetaModel::IsValidAttCode(get_class($oLnk), $sRoleAttCode))
  3231. {
  3232. throw new Exception("Unknown attribute ".get_class($oLnk)."::".$sRoleAttCode);
  3233. }
  3234. $oLnk->Set($sRoleAttCode, $sRoleValue);
  3235. }
  3236. $oLinkSet->AddObject($oLnk);
  3237. $this->Set($sTargetListAttCode, $oLinkSet);
  3238. }
  3239. break;
  3240. case 'apply_stimulus':
  3241. if (!array_key_exists(0, $aParams))
  3242. {
  3243. throw new Exception('Missing argument #1: stimulus');
  3244. }
  3245. $sStimulus = $aParams[0];
  3246. if (!in_array($sStimulus, MetaModel::EnumStimuli(get_class($this))))
  3247. {
  3248. throw new Exception("Unknown stimulus ".get_class($this)."::".$sStimulus);
  3249. }
  3250. $this->ApplyStimulus($sStimulus);
  3251. break;
  3252. case 'call_method':
  3253. if (!array_key_exists('source', $aSourceObjects))
  3254. {
  3255. throw new Exception('Missing conventional "source" object');
  3256. }
  3257. $oObjectToRead = $aSourceObjects['source'];
  3258. if (!array_key_exists(0, $aParams))
  3259. {
  3260. throw new Exception('Missing argument #1: method name');
  3261. }
  3262. $sMethod = $aParams[0];
  3263. $aCallSpec = array($this, $sMethod);
  3264. if (!is_callable($aCallSpec))
  3265. {
  3266. throw new Exception("Unknown method ".get_class($this)."::".$sMethod.'()');
  3267. }
  3268. // Note: $oObjectToRead has been preserved when adding $aSourceObjects, so as to remain backward compatible with methods having only 1 parameter ($oObjectToRead�
  3269. call_user_func($aCallSpec, $oObjectToRead, $aSourceObjects);
  3270. break;
  3271. default:
  3272. throw new Exception("Invalid verb");
  3273. }
  3274. }
  3275. public function IsArchived($sKeyAttCode = null)
  3276. {
  3277. $bRet = false;
  3278. $sFlagAttCode = is_null($sKeyAttCode) ? 'archive_flag' : $sKeyAttCode.'_archive_flag';
  3279. if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode))
  3280. {
  3281. $bRet = true;
  3282. }
  3283. return $bRet;
  3284. }
  3285. public function IsObsolete()
  3286. {
  3287. $bRet = false;
  3288. if (MetaModel::IsValidAttCode(get_class($this), 'obsolescence_flag') && $this->Get('obsolescence_flag'))
  3289. {
  3290. $bRet = true;
  3291. }
  3292. return $bRet;
  3293. }
  3294. /**
  3295. * @param $bArchive
  3296. * @throws Exception
  3297. */
  3298. protected function DBWriteArchiveFlag($bArchive)
  3299. {
  3300. if (!MetaModel::IsArchivable(get_class($this)))
  3301. {
  3302. throw new Exception(get_class($this).' is not an archivable class');
  3303. }
  3304. $iFlag = $bArchive ? 1 : 0;
  3305. $sDate = $bArchive ? '"'.date(AttributeDate::GetSQLFormat()).'"' : 'null';
  3306. $sClass = get_class($this);
  3307. $sArchiveRoot = MetaModel::GetAttributeOrigin($sClass, 'archive_flag');
  3308. $sRootTable = MetaModel::DBGetTable($sArchiveRoot);
  3309. $sRootKey = MetaModel::DBGetKey($sArchiveRoot);
  3310. $aJoins = array("`$sRootTable`");
  3311. $aUpdates = array();
  3312. foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  3313. {
  3314. if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) continue;
  3315. $sTable = MetaModel::DBGetTable($sParentClass);
  3316. $aUpdates[] = "`$sTable`.`archive_flag` = $iFlag";
  3317. if ($sParentClass == $sArchiveRoot)
  3318. {
  3319. if (!$bArchive || $this->Get('archive_date') == '')
  3320. {
  3321. // Erase or set the date (do not change it)
  3322. $aUpdates[] = "`$sTable`.`archive_date` = $sDate";
  3323. }
  3324. }
  3325. else
  3326. {
  3327. $sKey = MetaModel::DBGetKey($sParentClass);
  3328. $aJoins[] = "`$sTable` ON `$sTable`.`$sKey` = `$sRootTable`.`$sRootKey`";
  3329. }
  3330. }
  3331. $sJoins = implode(' INNER JOIN ', $aJoins);
  3332. $sValues = implode(', ', $aUpdates);
  3333. $sUpdateQuery = "UPDATE $sJoins SET $sValues WHERE `$sRootTable`.`$sRootKey` = ".$this->GetKey();
  3334. CMDBSource::Query($sUpdateQuery);
  3335. }
  3336. /**
  3337. * Can be called to repair the database (tables consistency)
  3338. * The archive_date will be preserved
  3339. * @throws Exception
  3340. */
  3341. public function DBArchive()
  3342. {
  3343. $this->DBWriteArchiveFlag(true);
  3344. $this->m_aCurrValues['archive_flag'] = true;
  3345. $this->m_aOrigValues['archive_flag'] = true;
  3346. }
  3347. public function DBUnarchive()
  3348. {
  3349. $this->DBWriteArchiveFlag(false);
  3350. $this->m_aCurrValues['archive_flag'] = false;
  3351. $this->m_aOrigValues['archive_flag'] = false;
  3352. $this->m_aCurrValues['archive_date'] = null;
  3353. $this->m_aOrigValues['archive_date'] = null;
  3354. }
  3355. }