dbobject.class.php 112 KB

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