dbobject.class.php 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639
  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. if ($toCheck == $this->GetKey())
  1100. {
  1101. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  1102. }
  1103. }
  1104. }
  1105. elseif ($oAtt->IsScalar())
  1106. {
  1107. $aValues = $oAtt->GetAllowedValues($this->ToArgsForQuery());
  1108. if (count($aValues) > 0)
  1109. {
  1110. if (!array_key_exists($toCheck, $aValues))
  1111. {
  1112. return "Value not allowed [$toCheck]";
  1113. }
  1114. }
  1115. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  1116. {
  1117. $iLen = strlen($toCheck);
  1118. if ($iLen > $iMaxSize)
  1119. {
  1120. return "String too long (found $iLen, limited to $iMaxSize)";
  1121. }
  1122. }
  1123. if (!$oAtt->CheckFormat($toCheck))
  1124. {
  1125. return "Wrong format [$toCheck]";
  1126. }
  1127. }
  1128. else
  1129. {
  1130. return $oAtt->CheckValue($this, $toCheck);
  1131. }
  1132. return true;
  1133. }
  1134. // check attributes together
  1135. public function CheckConsistency()
  1136. {
  1137. return true;
  1138. }
  1139. // check integrity rules (before inserting or updating the object)
  1140. // a displayable error is returned
  1141. public function DoCheckToWrite()
  1142. {
  1143. $this->DoComputeValues();
  1144. $aChanges = $this->ListChanges();
  1145. foreach($aChanges as $sAttCode => $value)
  1146. {
  1147. $res = $this->CheckValue($sAttCode);
  1148. if ($res !== true)
  1149. {
  1150. // $res contains the error description
  1151. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  1152. }
  1153. }
  1154. if (count($this->m_aCheckIssues) > 0)
  1155. {
  1156. // No need to check consistency between attributes if any of them has
  1157. // an unexpected value
  1158. return;
  1159. }
  1160. $res = $this->CheckConsistency();
  1161. if ($res !== true)
  1162. {
  1163. // $res contains the error description
  1164. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  1165. }
  1166. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  1167. //
  1168. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  1169. {
  1170. foreach($aChanges as $sAttCode => $value)
  1171. {
  1172. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  1173. if ($iFlags & OPT_ATT_SLAVE)
  1174. {
  1175. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  1176. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1177. $sAttLabel = $oAttDef->GetLabel();
  1178. foreach($aReasons as $aReasonInfo)
  1179. {
  1180. // Todo: associate the attribute code with the error
  1181. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. final public function CheckToWrite()
  1188. {
  1189. if (MetaModel::SkipCheckToWrite())
  1190. {
  1191. return array(true, array());
  1192. }
  1193. if (is_null($this->m_bCheckStatus))
  1194. {
  1195. $this->m_aCheckIssues = array();
  1196. $oKPI = new ExecutionKPI();
  1197. $this->DoCheckToWrite();
  1198. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  1199. if (count($this->m_aCheckIssues) == 0)
  1200. {
  1201. $this->m_bCheckStatus = true;
  1202. }
  1203. else
  1204. {
  1205. $this->m_bCheckStatus = false;
  1206. }
  1207. }
  1208. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  1209. }
  1210. // check if it is allowed to delete the existing object from the database
  1211. // a displayable error is returned
  1212. protected function DoCheckToDelete(&$oDeletionPlan)
  1213. {
  1214. $this->m_aDeleteIssues = array(); // Ok
  1215. if ($this->InSyncScope())
  1216. {
  1217. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  1218. {
  1219. foreach ($aSourceData['replica'] as $oReplica)
  1220. {
  1221. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  1222. }
  1223. $oDataSource = $aSourceData['source'];
  1224. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  1225. {
  1226. // The current task has the right to delete the object
  1227. continue;
  1228. }
  1229. $oReplica = reset($aSourceData['replica']); // Take the first one
  1230. if ($oReplica->Get('status_dest_creator') != 1)
  1231. {
  1232. // The object is not owned by the task
  1233. continue;
  1234. }
  1235. $sLink = $oDataSource->GetName();
  1236. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  1237. switch($sUserDeletePolicy)
  1238. {
  1239. case 'nobody':
  1240. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1241. break;
  1242. case 'administrators':
  1243. if (!UserRights::IsAdministrator())
  1244. {
  1245. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1246. }
  1247. break;
  1248. case 'everybody':
  1249. default:
  1250. // Ok
  1251. break;
  1252. }
  1253. }
  1254. }
  1255. }
  1256. public function CheckToDelete(&$oDeletionPlan)
  1257. {
  1258. $this->MakeDeletionPlan($oDeletionPlan);
  1259. $oDeletionPlan->ComputeResults();
  1260. return (!$oDeletionPlan->FoundStopper());
  1261. }
  1262. protected function ListChangedValues(array $aProposal)
  1263. {
  1264. $aDelta = array();
  1265. foreach ($aProposal as $sAtt => $proposedValue)
  1266. {
  1267. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1268. {
  1269. // The value was not set
  1270. $aDelta[$sAtt] = $proposedValue;
  1271. }
  1272. elseif(!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false))
  1273. {
  1274. // This attCode was never set, cannot be modified
  1275. // or the same value - as the original value - was set, and has been verified as equivalent to the original value
  1276. continue;
  1277. }
  1278. else if (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true)
  1279. {
  1280. // We already know that the value is really modified
  1281. $aDelta[$sAtt] = $proposedValue;
  1282. }
  1283. elseif(is_object($proposedValue))
  1284. {
  1285. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1286. // The value is an object, the comparison is not strict
  1287. if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue))
  1288. {
  1289. $aDelta[$sAtt] = $proposedValue;
  1290. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1291. }
  1292. else
  1293. {
  1294. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1295. }
  1296. }
  1297. else
  1298. {
  1299. // The value is a scalar, the comparison must be 100% strict
  1300. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1301. {
  1302. //echo "$sAtt:<pre>\n";
  1303. //var_dump($this->m_aOrigValues[$sAtt]);
  1304. //var_dump($proposedValue);
  1305. //echo "</pre>\n";
  1306. $aDelta[$sAtt] = $proposedValue;
  1307. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1308. }
  1309. else
  1310. {
  1311. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1312. }
  1313. }
  1314. }
  1315. return $aDelta;
  1316. }
  1317. // List the attributes that have been changed
  1318. // Returns an array of attname => currentvalue
  1319. public function ListChanges()
  1320. {
  1321. if ($this->m_bIsInDB)
  1322. {
  1323. return $this->ListChangedValues($this->m_aCurrValues);
  1324. }
  1325. else
  1326. {
  1327. return $this->m_aCurrValues;
  1328. }
  1329. }
  1330. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1331. public function IsModified()
  1332. {
  1333. $aChanges = $this->ListChanges();
  1334. return (count($aChanges) != 0);
  1335. }
  1336. public function Equals($oSibling)
  1337. {
  1338. if (get_class($oSibling) != get_class($this))
  1339. {
  1340. return false;
  1341. }
  1342. if ($this->GetKey() != $oSibling->GetKey())
  1343. {
  1344. return false;
  1345. }
  1346. if ($this->m_bIsInDB)
  1347. {
  1348. // If one has changed, then consider them as being different
  1349. if ($this->IsModified() || $oSibling->IsModified())
  1350. {
  1351. return false;
  1352. }
  1353. }
  1354. else
  1355. {
  1356. // Todo - implement this case (loop on every attribute)
  1357. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1358. //{
  1359. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1360. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1361. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1362. //{
  1363. //return false;
  1364. //}
  1365. //}
  1366. return false;
  1367. }
  1368. return true;
  1369. }
  1370. // used only by insert
  1371. protected function OnObjectKeyReady()
  1372. {
  1373. // Meant to be overloaded
  1374. }
  1375. // used both by insert/update
  1376. private function DBWriteLinks()
  1377. {
  1378. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1379. {
  1380. if (!$oAttDef->IsLinkSet()) continue;
  1381. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1382. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1383. $oLinkSet = $this->m_aCurrValues[$sAttCode];
  1384. $oLinkSet->DBWrite($this);
  1385. }
  1386. }
  1387. // used both by insert/update
  1388. private function WriteExternalAttributes()
  1389. {
  1390. foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1391. {
  1392. if (!$oAttDef->LoadInObject()) continue;
  1393. if ($oAttDef->LoadFromDB()) continue;
  1394. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1395. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1396. $oAttDef->WriteValue($this, $this->m_aCurrValues[$sAttCode]);
  1397. }
  1398. }
  1399. // Note: this is experimental - it was designed to speed up the setup of iTop
  1400. // Known limitations:
  1401. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1402. // - the id of the object is not updated
  1403. static public final function BulkInsertStart()
  1404. {
  1405. self::$m_bBulkInsert = true;
  1406. }
  1407. static public final function BulkInsertFlush()
  1408. {
  1409. if (!self::$m_bBulkInsert) return;
  1410. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1411. {
  1412. foreach ($aTables as $sTable => $sColumns)
  1413. {
  1414. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1415. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1416. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1417. }
  1418. }
  1419. // Reset
  1420. self::$m_aBulkInsertItems = array();
  1421. self::$m_aBulkInsertCols = array();
  1422. self::$m_bBulkInsert = false;
  1423. }
  1424. private function DBInsertSingleTable($sTableClass)
  1425. {
  1426. $sTable = MetaModel::DBGetTable($sTableClass);
  1427. // Abstract classes or classes having no specific attribute do not have an associated table
  1428. if ($sTable == '') return;
  1429. $sClass = get_class($this);
  1430. // fields in first array, values in the second
  1431. $aFieldsToWrite = array();
  1432. $aValuesToWrite = array();
  1433. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1434. {
  1435. // Add it to the list of fields to write
  1436. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1437. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1438. }
  1439. $aHierarchicalKeys = array();
  1440. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1441. {
  1442. // Skip this attribute if not defined in this table
  1443. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1444. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1445. foreach($aAttColumns as $sColumn => $sValue)
  1446. {
  1447. $aFieldsToWrite[] = "`$sColumn`";
  1448. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1449. }
  1450. if ($oAttDef->IsHierarchicalKey())
  1451. {
  1452. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1453. }
  1454. }
  1455. if (count($aValuesToWrite) == 0) return false;
  1456. if (MetaModel::DBIsReadOnly())
  1457. {
  1458. $iNewKey = -1;
  1459. }
  1460. else
  1461. {
  1462. if (self::$m_bBulkInsert)
  1463. {
  1464. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1465. {
  1466. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1467. }
  1468. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1469. $iNewKey = 999999; // TODO - compute next id....
  1470. }
  1471. else
  1472. {
  1473. if (count($aHierarchicalKeys) > 0)
  1474. {
  1475. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1476. {
  1477. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1478. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1479. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1480. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1481. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1482. }
  1483. }
  1484. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1485. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1486. }
  1487. }
  1488. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1489. if (empty($this->m_iKey))
  1490. {
  1491. // Take the autonumber
  1492. $this->m_iKey = $iNewKey;
  1493. }
  1494. return $this->m_iKey;
  1495. }
  1496. // Insert of record for the new object into the database
  1497. // Returns the key of the newly created object
  1498. public function DBInsertNoReload()
  1499. {
  1500. if ($this->m_bIsInDB)
  1501. {
  1502. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1503. }
  1504. $sClass = get_class($this);
  1505. $sRootClass = MetaModel::GetRootClass($sClass);
  1506. // Ensure the update of the values (we are accessing the data directly)
  1507. $this->DoComputeValues();
  1508. $this->OnInsert();
  1509. if ($this->m_iKey < 0)
  1510. {
  1511. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1512. $this->m_iKey = null;
  1513. }
  1514. // If not automatically computed, then check that the key is given by the caller
  1515. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1516. {
  1517. if (empty($this->m_iKey))
  1518. {
  1519. 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));
  1520. }
  1521. }
  1522. // Ultimate check - ensure DB integrity
  1523. list($bRes, $aIssues) = $this->CheckToWrite();
  1524. if (!$bRes)
  1525. {
  1526. $sIssues = implode(', ', $aIssues);
  1527. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1528. }
  1529. // Stop watches
  1530. $sState = $this->GetState();
  1531. if ($sState != '')
  1532. {
  1533. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1534. {
  1535. if ($oAttDef instanceof AttributeStopWatch)
  1536. {
  1537. if (in_array($sState, $oAttDef->GetStates()))
  1538. {
  1539. // Start the stop watch and compute the deadlines
  1540. $oSW = $this->Get($sAttCode);
  1541. $oSW->Start($this, $oAttDef);
  1542. $oSW->ComputeDeadlines($this, $oAttDef);
  1543. $this->Set($sAttCode, $oSW);
  1544. }
  1545. }
  1546. }
  1547. }
  1548. // First query built upon on the root class, because the ID must be created first
  1549. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1550. // Then do the leaf class, if different from the root class
  1551. if ($sClass != $sRootClass)
  1552. {
  1553. $this->DBInsertSingleTable($sClass);
  1554. }
  1555. // Then do the other classes
  1556. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1557. {
  1558. if ($sParentClass == $sRootClass) continue;
  1559. $this->DBInsertSingleTable($sParentClass);
  1560. }
  1561. $this->OnObjectKeyReady();
  1562. $this->DBWriteLinks();
  1563. $this->WriteExternalAttributes();
  1564. $this->m_bIsInDB = true;
  1565. $this->m_bDirty = false;
  1566. $this->AfterInsert();
  1567. // Activate any existing trigger
  1568. $sClass = get_class($this);
  1569. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1570. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1571. while ($oTrigger = $oSet->Fetch())
  1572. {
  1573. $oTrigger->DoActivate($this->ToArgs('this'));
  1574. }
  1575. // Callbacks registered with RegisterCallback
  1576. if (isset($this->m_aCallbacks[self::CALLBACK_AFTERINSERT]))
  1577. {
  1578. foreach ($this->m_aCallbacks[self::CALLBACK_AFTERINSERT] as $aCallBackData)
  1579. {
  1580. call_user_func_array($aCallBackData['callback'], $aCallBackData['params']);
  1581. }
  1582. }
  1583. $this->RecordObjCreation();
  1584. return $this->m_iKey;
  1585. }
  1586. protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
  1587. {
  1588. $sTable = MetaModel::DBGetTable($sTableClass);
  1589. // Abstract classes or classes having no specific attribute do not have an associated table
  1590. if ($sTable == '') return;
  1591. $sClass = get_class($this);
  1592. // fields in first array, values in the second
  1593. $aFieldsToWrite = array();
  1594. $aValuesToWrite = array();
  1595. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1596. {
  1597. // Add it to the list of fields to write
  1598. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1599. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1600. }
  1601. $aHierarchicalKeys = array();
  1602. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1603. {
  1604. // Skip this attribute if not defined in this table
  1605. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1606. // Skip link set that can still be undefined though the object is 100% loaded
  1607. if ($oAttDef->IsLinkSet()) continue;
  1608. $value = $this->m_aCurrValues[$sAttCode];
  1609. if ($oAttDef->IsExternalKey())
  1610. {
  1611. $sTargetClass = $oAttDef->GetTargetClass();
  1612. if (is_array($aAuthorizedExtKeys))
  1613. {
  1614. if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
  1615. {
  1616. $value = 0;
  1617. }
  1618. }
  1619. }
  1620. $aAttColumns = $oAttDef->GetSQLValues($value);
  1621. foreach($aAttColumns as $sColumn => $sValue)
  1622. {
  1623. $aFieldsToWrite[] = "`$sColumn`";
  1624. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1625. }
  1626. if ($oAttDef->IsHierarchicalKey())
  1627. {
  1628. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1629. }
  1630. }
  1631. if (count($aValuesToWrite) == 0) return false;
  1632. if (count($aHierarchicalKeys) > 0)
  1633. {
  1634. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1635. {
  1636. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1637. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1638. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1639. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1640. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1641. }
  1642. }
  1643. $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
  1644. }
  1645. public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
  1646. {
  1647. $sClass = get_class($this);
  1648. $sRootClass = MetaModel::GetRootClass($sClass);
  1649. // First query built upon on the root class, because the ID must be created first
  1650. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
  1651. // Then do the leaf class, if different from the root class
  1652. if ($sClass != $sRootClass)
  1653. {
  1654. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
  1655. }
  1656. // Then do the other classes
  1657. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1658. {
  1659. if ($sParentClass == $sRootClass) continue;
  1660. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
  1661. }
  1662. }
  1663. public function DBInsert()
  1664. {
  1665. $this->DBInsertNoReload();
  1666. $this->Reload();
  1667. return $this->m_iKey;
  1668. }
  1669. public function DBInsertTracked(CMDBChange $oChange)
  1670. {
  1671. CMDBObject::SetCurrentChange($oChange);
  1672. return $this->DBInsert();
  1673. }
  1674. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1675. {
  1676. CMDBObject::SetCurrentChange($oChange);
  1677. return $this->DBInsertNoReload();
  1678. }
  1679. // Creates a copy of the current object into the database
  1680. // Returns the id of the newly created object
  1681. public function DBClone($iNewKey = null)
  1682. {
  1683. $this->m_bIsInDB = false;
  1684. $this->m_iKey = $iNewKey;
  1685. $ret = $this->DBInsert();
  1686. $this->RecordObjCreation();
  1687. return $ret;
  1688. }
  1689. /**
  1690. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1691. * The purpose of this method is to reset the appropriate attributes of the object in
  1692. * order to make sure that the newly cloned object is really distinct from its clone
  1693. */
  1694. public function __clone()
  1695. {
  1696. $this->m_bIsInDB = false;
  1697. $this->m_bDirty = true;
  1698. $this->m_iKey = self::GetNextTempId(get_class($this));
  1699. }
  1700. // Update a record
  1701. public function DBUpdate()
  1702. {
  1703. if (!$this->m_bIsInDB)
  1704. {
  1705. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1706. }
  1707. // Protect against reentrance (e.g. cascading the update of ticket logs)
  1708. static $aUpdateReentrance = array();
  1709. $sKey = get_class($this).'::'.$this->GetKey();
  1710. if (array_key_exists($sKey, $aUpdateReentrance))
  1711. {
  1712. return;
  1713. }
  1714. $aUpdateReentrance[$sKey] = true;
  1715. try
  1716. {
  1717. // Stop watches
  1718. $sState = $this->GetState();
  1719. if ($sState != '')
  1720. {
  1721. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1722. {
  1723. if ($oAttDef instanceof AttributeStopWatch)
  1724. {
  1725. if (in_array($sState, $oAttDef->GetStates()))
  1726. {
  1727. // Compute or recompute the deadlines
  1728. $oSW = $this->Get($sAttCode);
  1729. $oSW->ComputeDeadlines($this, $oAttDef);
  1730. $this->Set($sAttCode, $oSW);
  1731. }
  1732. }
  1733. }
  1734. }
  1735. $this->DoComputeValues();
  1736. $this->OnUpdate();
  1737. $aChanges = $this->ListChanges();
  1738. if (count($aChanges) == 0)
  1739. {
  1740. // Attempting to update an unchanged object
  1741. unset($aUpdateReentrance[$sKey]);
  1742. return $this->m_iKey;
  1743. }
  1744. // Ultimate check - ensure DB integrity
  1745. list($bRes, $aIssues) = $this->CheckToWrite();
  1746. if (!$bRes)
  1747. {
  1748. $sIssues = implode(', ', $aIssues);
  1749. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1750. }
  1751. // Save the original values (will be reset to the new values when the object get written to the DB)
  1752. $aOriginalValues = $this->m_aOrigValues;
  1753. $bHasANewExternalKeyValue = false;
  1754. $aHierarchicalKeys = array();
  1755. $aDBChanges = array();
  1756. foreach($aChanges as $sAttCode => $valuecurr)
  1757. {
  1758. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1759. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1760. if ($oAttDef->IsBasedOnDBColumns())
  1761. {
  1762. $aDBChanges[$sAttCode] = $aChanges[$sAttCode];
  1763. }
  1764. if ($oAttDef->IsHierarchicalKey())
  1765. {
  1766. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1767. }
  1768. }
  1769. if (!MetaModel::DBIsReadOnly())
  1770. {
  1771. // Update the left & right indexes for each hierarchical key
  1772. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1773. {
  1774. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1775. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1776. $aRes = CMDBSource::QueryToArray($sSQL);
  1777. $iMyLeft = $aRes[0]['left'];
  1778. $iMyRight = $aRes[0]['right'];
  1779. $iDelta =$iMyRight - $iMyLeft + 1;
  1780. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1781. if ($aDBChanges[$sAttCode] == 0)
  1782. {
  1783. // No new parent, insert completely at the right of the tree
  1784. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1785. $aRes = CMDBSource::QueryToArray($sSQL);
  1786. if (count($aRes) == 0)
  1787. {
  1788. $iNewLeft = 1;
  1789. }
  1790. else
  1791. {
  1792. $iNewLeft = $aRes[0]['max']+1;
  1793. }
  1794. }
  1795. else
  1796. {
  1797. // Insert at the right of the specified parent
  1798. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aDBChanges[$sAttCode]);
  1799. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1800. }
  1801. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1802. $aHKChanges = array();
  1803. $aHKChanges[$sAttCode] = $aDBChanges[$sAttCode];
  1804. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1805. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1806. $aDBChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1807. }
  1808. // Update scalar attributes
  1809. if (count($aDBChanges) != 0)
  1810. {
  1811. $oFilter = new DBObjectSearch(get_class($this));
  1812. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1813. $oFilter->AllowAllData();
  1814. $sSQL = $oFilter->MakeUpdateQuery($aDBChanges);
  1815. CMDBSource::Query($sSQL);
  1816. }
  1817. }
  1818. $this->DBWriteLinks();
  1819. $this->WriteExternalAttributes();
  1820. $this->m_bDirty = false;
  1821. $this->m_aTouchedAtt = array();
  1822. $this->m_aModifiedAtt = array();
  1823. $this->AfterUpdate();
  1824. // Reload to get the external attributes
  1825. if ($bHasANewExternalKeyValue)
  1826. {
  1827. $this->Reload(true /* AllowAllData */);
  1828. }
  1829. else
  1830. {
  1831. // Reset original values although the object has not been reloaded
  1832. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1833. {
  1834. if ($bLoaded)
  1835. {
  1836. $value = $this->m_aCurrValues[$sAttCode];
  1837. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1838. }
  1839. }
  1840. }
  1841. if (count($aChanges) != 0)
  1842. {
  1843. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1844. }
  1845. }
  1846. catch (Exception $e)
  1847. {
  1848. unset($aUpdateReentrance[$sKey]);
  1849. throw $e;
  1850. }
  1851. unset($aUpdateReentrance[$sKey]);
  1852. return $this->m_iKey;
  1853. }
  1854. public function DBUpdateTracked(CMDBChange $oChange)
  1855. {
  1856. CMDBObject::SetCurrentChange($oChange);
  1857. return $this->DBUpdate();
  1858. }
  1859. // Make the current changes persistent - clever wrapper for Insert or Update
  1860. public function DBWrite()
  1861. {
  1862. if ($this->m_bIsInDB)
  1863. {
  1864. return $this->DBUpdate();
  1865. }
  1866. else
  1867. {
  1868. return $this->DBInsert();
  1869. }
  1870. }
  1871. private function DBDeleteSingleTable($sTableClass)
  1872. {
  1873. $sTable = MetaModel::DBGetTable($sTableClass);
  1874. // Abstract classes or classes having no specific attribute do not have an associated table
  1875. if ($sTable == '') return;
  1876. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1877. $sKey = CMDBSource::Quote($this->m_iKey);
  1878. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1879. CMDBSource::DeleteFrom($sDeleteSQL);
  1880. }
  1881. protected function DBDeleteSingleObject()
  1882. {
  1883. if (!MetaModel::DBIsReadOnly())
  1884. {
  1885. $this->OnDelete();
  1886. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1887. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1888. {
  1889. if ($oAttDef->IsHierarchicalKey())
  1890. {
  1891. // Update the left & right indexes for each hierarchical key
  1892. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1893. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1894. $aRes = CMDBSource::QueryToArray($sSQL);
  1895. $iMyLeft = $aRes[0]['left'];
  1896. $iMyRight = $aRes[0]['right'];
  1897. $iDelta =$iMyRight - $iMyLeft + 1;
  1898. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1899. // No new parent for now, insert completely at the right of the tree
  1900. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1901. $aRes = CMDBSource::QueryToArray($sSQL);
  1902. if (count($aRes) == 0)
  1903. {
  1904. $iNewLeft = 1;
  1905. }
  1906. else
  1907. {
  1908. $iNewLeft = $aRes[0]['max']+1;
  1909. }
  1910. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1911. }
  1912. elseif (!$oAttDef->LoadFromDB())
  1913. {
  1914. $oAttDef->DeleteValue($this);
  1915. }
  1916. }
  1917. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1918. {
  1919. $this->DBDeleteSingleTable($sParentClass);
  1920. }
  1921. $this->AfterDelete();
  1922. $this->m_bIsInDB = false;
  1923. // 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)
  1924. // 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
  1925. }
  1926. }
  1927. // Delete an object... and guarantee data integrity
  1928. //
  1929. public function DBDelete(&$oDeletionPlan = null)
  1930. {
  1931. static $iLoopTimeLimit = null;
  1932. if ($iLoopTimeLimit == null)
  1933. {
  1934. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  1935. }
  1936. if (is_null($oDeletionPlan))
  1937. {
  1938. $oDeletionPlan = new DeletionPlan();
  1939. }
  1940. $this->MakeDeletionPlan($oDeletionPlan);
  1941. $oDeletionPlan->ComputeResults();
  1942. if ($oDeletionPlan->FoundStopper())
  1943. {
  1944. $aIssues = $oDeletionPlan->GetIssues();
  1945. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1946. }
  1947. else
  1948. {
  1949. // Getting and setting time limit are not symetric:
  1950. // www.php.net/manual/fr/function.set-time-limit.php#72305
  1951. $iPreviousTimeLimit = ini_get('max_execution_time');
  1952. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1953. {
  1954. foreach ($aToDelete as $iId => $aData)
  1955. {
  1956. $oToDelete = $aData['to_delete'];
  1957. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1958. // because for each object we would try to update all the preceding ones... that are already deleted
  1959. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1960. // As a temporary fix: delete only the objects that are still to be deleted...
  1961. if ($oToDelete->m_bIsInDB)
  1962. {
  1963. set_time_limit($iLoopTimeLimit);
  1964. $oToDelete->DBDeleteSingleObject();
  1965. }
  1966. }
  1967. }
  1968. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1969. {
  1970. foreach ($aToUpdate as $iId => $aData)
  1971. {
  1972. $oToUpdate = $aData['to_reset'];
  1973. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1974. {
  1975. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1976. set_time_limit($iLoopTimeLimit);
  1977. $oToUpdate->DBUpdate();
  1978. }
  1979. }
  1980. }
  1981. set_time_limit($iPreviousTimeLimit);
  1982. }
  1983. return $oDeletionPlan;
  1984. }
  1985. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1986. {
  1987. CMDBObject::SetCurrentChange($oChange);
  1988. $this->DBDelete($oDeletionPlan);
  1989. }
  1990. public function EnumTransitions()
  1991. {
  1992. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1993. if (empty($sStateAttCode)) return array();
  1994. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1995. return MetaModel::EnumTransitions(get_class($this), $sState);
  1996. }
  1997. /**
  1998. * Designed as an action to be called when a stop watch threshold times out
  1999. * or from within the framework
  2000. * @param $sStimulusCode
  2001. * @param bool|false $bDoNotWrite
  2002. * @return bool
  2003. * @throws CoreException
  2004. * @throws CoreUnexpectedValue
  2005. */
  2006. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  2007. {
  2008. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  2009. if (empty($sStateAttCode))
  2010. {
  2011. throw new CoreException('No lifecycle for the class '.get_class($this));
  2012. }
  2013. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  2014. $aStateTransitions = $this->EnumTransitions();
  2015. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  2016. {
  2017. // This simulus has no effect in the current state... do nothing
  2018. return true;
  2019. }
  2020. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  2021. // Change the state before proceeding to the actions, this is necessary because an action might
  2022. // trigger another stimuli (alternative: push the stimuli into a queue)
  2023. $sPreviousState = $this->Get($sStateAttCode);
  2024. $sNewState = $aTransitionDef['target_state'];
  2025. $this->Set($sStateAttCode, $sNewState);
  2026. // $aTransitionDef is an
  2027. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  2028. $bSuccess = true;
  2029. foreach ($aTransitionDef['actions'] as $actionHandler)
  2030. {
  2031. if (is_string($actionHandler))
  2032. {
  2033. // Old (pre-2.1.0 modules) action definition without any parameter
  2034. $aActionCallSpec = array($this, $actionHandler);
  2035. $sActionDesc = get_class($this).'::'.$actionHandler;
  2036. if (!is_callable($aActionCallSpec))
  2037. {
  2038. throw new CoreException("Unable to call action: ".get_class($this)."::$actionHandler");
  2039. }
  2040. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  2041. }
  2042. else // if (is_array($actionHandler))
  2043. {
  2044. // New syntax: 'verb' and typed parameters
  2045. $sAction = $actionHandler['verb'];
  2046. $sActionDesc = get_class($this).'::'.$sAction;
  2047. $aParams = array();
  2048. foreach($actionHandler['params'] as $aDefinition)
  2049. {
  2050. $sParamType = array_key_exists('type', $aDefinition) ? $aDefinition['type'] : 'string';
  2051. switch($sParamType)
  2052. {
  2053. case 'int':
  2054. $value = (int)$aDefinition['value'];
  2055. break;
  2056. case 'float':
  2057. $value = (float)$aDefinition['value'];
  2058. break;
  2059. case 'bool':
  2060. $value = (bool)$aDefinition['value'];
  2061. break;
  2062. case 'reference':
  2063. $value = ${$aDefinition['value']};
  2064. break;
  2065. case 'string':
  2066. default:
  2067. $value = (string)$aDefinition['value'];
  2068. }
  2069. $aParams[] = $value;
  2070. }
  2071. $aCallSpec = array($this, $sAction);
  2072. $bRet = call_user_func_array($aCallSpec, $aParams);
  2073. }
  2074. // if one call fails, the whole is considered as failed
  2075. // (in case there is no returned value, null is obtained and means "ok")
  2076. if ($bRet === false)
  2077. {
  2078. IssueLog::Info("Lifecycle action $sActionDesc returned false on object #".$this->GetKey());
  2079. $bSuccess = false;
  2080. }
  2081. }
  2082. if ($bSuccess)
  2083. {
  2084. $sClass = get_class($this);
  2085. // Stop watches
  2086. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2087. {
  2088. if ($oAttDef instanceof AttributeStopWatch)
  2089. {
  2090. $oSW = $this->Get($sAttCode);
  2091. if (in_array($sNewState, $oAttDef->GetStates()))
  2092. {
  2093. $oSW->Start($this, $oAttDef);
  2094. }
  2095. else
  2096. {
  2097. $oSW->Stop($this, $oAttDef);
  2098. }
  2099. $this->Set($sAttCode, $oSW);
  2100. }
  2101. }
  2102. if (!$bDoNotWrite)
  2103. {
  2104. $this->DBWrite();
  2105. }
  2106. // Change state triggers...
  2107. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  2108. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  2109. while ($oTrigger = $oSet->Fetch())
  2110. {
  2111. $oTrigger->DoActivate($this->ToArgs('this'));
  2112. }
  2113. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  2114. while ($oTrigger = $oSet->Fetch())
  2115. {
  2116. $oTrigger->DoActivate($this->ToArgs('this'));
  2117. }
  2118. }
  2119. return $bSuccess;
  2120. }
  2121. /**
  2122. * Designed as an action to be called when a stop watch threshold times out
  2123. */
  2124. public function ResetStopWatch($sAttCode)
  2125. {
  2126. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2127. if (!$oAttDef instanceof AttributeStopWatch)
  2128. {
  2129. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  2130. }
  2131. $oSW = $this->Get($sAttCode);
  2132. $oSW->Reset($this, $oAttDef);
  2133. $this->Set($sAttCode, $oSW);
  2134. return true;
  2135. }
  2136. /**
  2137. * Lifecycle action: Recover the default value (aka when an object is being created)
  2138. */
  2139. public function Reset($sAttCode)
  2140. {
  2141. $this->Set($sAttCode, $this->GetDefaultValue($sAttCode));
  2142. return true;
  2143. }
  2144. /**
  2145. * Lifecycle action: Copy an attribute to another
  2146. */
  2147. public function Copy($sDestAttCode, $sSourceAttCode)
  2148. {
  2149. $this->Set($sDestAttCode, $this->Get($sSourceAttCode));
  2150. return true;
  2151. }
  2152. /**
  2153. * Lifecycle action: Set the current date/time for the given attribute
  2154. */
  2155. public function SetCurrentDate($sAttCode)
  2156. {
  2157. $this->Set($sAttCode, time());
  2158. return true;
  2159. }
  2160. /**
  2161. * Lifecycle action: Set the current logged in user for the given attribute
  2162. */
  2163. public function SetCurrentUser($sAttCode)
  2164. {
  2165. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2166. if ($oAttDef instanceof AttributeString)
  2167. {
  2168. // Note: the user friendly name is the contact friendly name if a contact is attached to the logged in user
  2169. $this->Set($sAttCode, UserRights::GetUserFriendlyName());
  2170. }
  2171. else
  2172. {
  2173. if ($oAttDef->IsExternalKey())
  2174. {
  2175. if ($oAttDef->GetTargetClass() != 'User')
  2176. {
  2177. throw new Exception("SetCurrentUser: the attribute $sAttCode must be an external key to 'User', found '".$oAttDef->GetTargetClass()."'");
  2178. }
  2179. }
  2180. $this->Set($sAttCode, UserRights::GetUserId());
  2181. }
  2182. return true;
  2183. }
  2184. /**
  2185. * Lifecycle action: Set the current logged in CONTACT for the given attribute
  2186. */
  2187. public function SetCurrentPerson($sAttCode)
  2188. {
  2189. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2190. if ($oAttDef instanceof AttributeString)
  2191. {
  2192. $iPerson = UserRights::GetContactId();
  2193. if ($iPerson == 0)
  2194. {
  2195. $this->Set($sAttCode, '');
  2196. }
  2197. else
  2198. {
  2199. $oPerson = MetaModel::GetObject('Person', $iPerson);
  2200. $this->Set($sAttCode, $oPerson->Get('friendlyname'));
  2201. }
  2202. }
  2203. else
  2204. {
  2205. if ($oAttDef->IsExternalKey())
  2206. {
  2207. if (!MetaModel::IsParentClass($oAttDef->GetTargetClass(), 'Person'))
  2208. {
  2209. throw new Exception("SetCurrentContact: the attribute $sAttCode must be an external key to 'Person' or any other class above 'Person', found '".$oAttDef->GetTargetClass()."'");
  2210. }
  2211. }
  2212. $this->Set($sAttCode, UserRights::GetContactId());
  2213. }
  2214. return true;
  2215. }
  2216. /**
  2217. * Lifecycle action: Set the time elapsed since a reference point
  2218. */
  2219. public function SetElapsedTime($sAttCode, $sRefAttCode, $sWorkingTimeComputer = null)
  2220. {
  2221. if (is_null($sWorkingTimeComputer))
  2222. {
  2223. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  2224. }
  2225. $oComputer = new $sWorkingTimeComputer();
  2226. $aCallSpec = array($oComputer, 'GetOpenDuration');
  2227. if (!is_callable($aCallSpec))
  2228. {
  2229. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  2230. }
  2231. $iStartTime = AttributeDateTime::GetAsUnixSeconds($this->Get($sRefAttCode));
  2232. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  2233. $oEndDate = new DateTime(); // now
  2234. if (class_exists('WorkingTimeRecorder'))
  2235. {
  2236. $sClass = get_class($this);
  2237. WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', array("Class:$sClass/Attribute:$sAttCode"));
  2238. }
  2239. $iElapsed = call_user_func($aCallSpec, $this, $oStartDate, $oEndDate);
  2240. if (class_exists('WorkingTimeRecorder'))
  2241. {
  2242. WorkingTimeRecorder::End();
  2243. }
  2244. $this->Set($sAttCode, $iElapsed);
  2245. return true;
  2246. }
  2247. /**
  2248. * Create query parameters (SELECT ... WHERE service = :this->service_id)
  2249. * to be used with the APIs DBObjectSearch/DBObjectSet
  2250. *
  2251. * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
  2252. * in VariableExpression::Render()
  2253. */
  2254. public function ToArgsForQuery($sArgName = 'this')
  2255. {
  2256. return array($sArgName.'->object()' => $this);
  2257. }
  2258. /**
  2259. * Create template placeholders: now equivalent to ToArgsForQuery since the actual
  2260. * template placeholders are computed on demand.
  2261. */
  2262. public function ToArgs($sArgName = 'this')
  2263. {
  2264. return $this->ToArgsForQuery($sArgName);
  2265. }
  2266. public function GetForTemplate($sPlaceholderAttCode)
  2267. {
  2268. $ret = null;
  2269. if (preg_match('/^([^-]+)-(>|&gt;)(.+)$/', $sPlaceholderAttCode, $aMatches)) // Support both syntaxes: this->xxx or this-&gt;xxx for HTML compatibility
  2270. {
  2271. $sExtKeyAttCode = $aMatches[1];
  2272. $sRemoteAttCode = $aMatches[3];
  2273. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  2274. {
  2275. throw new CoreException("Unknown attribute '$sExtKeyAttCode' for the class ".get_class($this));
  2276. }
  2277. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  2278. if (!$oKeyAttDef instanceof AttributeExternalKey)
  2279. {
  2280. throw new CoreException("'$sExtKeyAttCode' is not an external key of the class ".get_class($this));
  2281. }
  2282. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  2283. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  2284. if (is_null($oRemoteObj))
  2285. {
  2286. $ret = Dict::S('UI:UndefinedObject');
  2287. }
  2288. else
  2289. {
  2290. // Recurse
  2291. $ret = $oRemoteObj->GetForTemplate($sRemoteAttCode);
  2292. }
  2293. }
  2294. else
  2295. {
  2296. switch($sPlaceholderAttCode)
  2297. {
  2298. case 'id':
  2299. $ret = $this->GetKey();
  2300. break;
  2301. case 'name()':
  2302. $ret = $this->GetName();
  2303. break;
  2304. default:
  2305. if (preg_match('/^([^(]+)\\((.*)\\)$/', $sPlaceholderAttCode, $aMatches))
  2306. {
  2307. $sVerb = $aMatches[1];
  2308. $sAttCode = $aMatches[2];
  2309. }
  2310. else
  2311. {
  2312. $sVerb = '';
  2313. $sAttCode = $sPlaceholderAttCode;
  2314. }
  2315. if ($sVerb == 'hyperlink')
  2316. {
  2317. $sPortalId = ($sAttCode === '') ? 'console' : $sAttCode;
  2318. if (!array_key_exists($sPortalId, self::$aPortalToURLMaker))
  2319. {
  2320. throw new Exception("Unknown portal id '$sPortalId' in placeholder '$sPlaceholderAttCode''");
  2321. }
  2322. $ret = $this->GetHyperlink(self::$aPortalToURLMaker[$sPortalId], false);
  2323. }
  2324. else
  2325. {
  2326. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2327. $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this);
  2328. }
  2329. }
  2330. if ($ret === null)
  2331. {
  2332. $ret = '';
  2333. }
  2334. }
  2335. return $ret;
  2336. }
  2337. static protected $aPortalToURLMaker = array('console' => 'iTopStandardURLMaker', 'portal' => 'PortalURLMaker');
  2338. /**
  2339. * Associate a portal to a class that implements iDBObjectURLMaker,
  2340. * and which will be invoked with placeholders like $this->org_id->hyperlink(portal)$
  2341. *
  2342. * @param $sPortalId Identifies the portal. Conventions: the main portal is 'console', The user requests portal is 'portal'.
  2343. * @param $sUrlMakerClass
  2344. */
  2345. static public function RegisterURLMakerClass($sPortalId, $sUrlMakerClass)
  2346. {
  2347. self::$aPortalToURLMaker[$sPortalId] = $sUrlMakerClass;
  2348. }
  2349. // To be optionaly overloaded
  2350. protected function OnInsert()
  2351. {
  2352. }
  2353. // To be optionaly overloaded
  2354. protected function AfterInsert()
  2355. {
  2356. }
  2357. // To be optionaly overloaded
  2358. protected function OnUpdate()
  2359. {
  2360. }
  2361. // To be optionaly overloaded
  2362. protected function AfterUpdate()
  2363. {
  2364. }
  2365. // To be optionaly overloaded
  2366. protected function OnDelete()
  2367. {
  2368. }
  2369. // To be optionaly overloaded
  2370. protected function AfterDelete()
  2371. {
  2372. }
  2373. /**
  2374. * Common to the recording of link set changes (add/remove/modify)
  2375. */
  2376. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  2377. {
  2378. if ($iLinkSetOwnerId <= 0)
  2379. {
  2380. return null;
  2381. }
  2382. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  2383. {
  2384. // The link set owner class does not keep track of its history
  2385. return null;
  2386. }
  2387. // Determine the linked item class and id
  2388. //
  2389. if ($oLinkSet->IsIndirect())
  2390. {
  2391. // The "item" is on the other end (N-N links)
  2392. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  2393. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  2394. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  2395. if ($aOriginalValues)
  2396. {
  2397. // Get the value from the original values
  2398. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  2399. }
  2400. else
  2401. {
  2402. $iItemId = $this->Get($sExtKeyToRemote);
  2403. }
  2404. }
  2405. else
  2406. {
  2407. // I am the "item" (1-N links)
  2408. $sItemClass = get_class($this);
  2409. $iItemId = $this->GetKey();
  2410. }
  2411. // Get the remote object, to determine its exact class
  2412. // 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!
  2413. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  2414. if ($oOwner)
  2415. {
  2416. $sLinkSetOwnerClass = get_class($oOwner);
  2417. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  2418. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  2419. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  2420. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  2421. $oMyChangeOp->Set("item_class", $sItemClass);
  2422. $oMyChangeOp->Set("item_id", $iItemId);
  2423. return $oMyChangeOp;
  2424. }
  2425. else
  2426. {
  2427. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  2428. return null;
  2429. }
  2430. }
  2431. /**
  2432. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  2433. */
  2434. private function RecordLinkSetListChange($bAdd = true)
  2435. {
  2436. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2437. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2438. {
  2439. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2440. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2441. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2442. if ($oMyChangeOp)
  2443. {
  2444. if ($bAdd)
  2445. {
  2446. $oMyChangeOp->Set("type", "added");
  2447. }
  2448. else
  2449. {
  2450. $oMyChangeOp->Set("type", "removed");
  2451. }
  2452. $iId = $oMyChangeOp->DBInsertNoReload();
  2453. }
  2454. }
  2455. }
  2456. protected function RecordObjCreation()
  2457. {
  2458. $this->RecordLinkSetListChange(true);
  2459. }
  2460. protected function RecordObjDeletion($objkey)
  2461. {
  2462. $this->RecordLinkSetListChange(false);
  2463. }
  2464. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  2465. {
  2466. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2467. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2468. {
  2469. if (array_key_exists($sExtKeyAttCode, $aValues))
  2470. {
  2471. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2472. // Keep track of link added/removed
  2473. //
  2474. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  2475. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2476. if ($oMyChangeOp)
  2477. {
  2478. $oMyChangeOp->Set("type", "added");
  2479. $oMyChangeOp->DBInsertNoReload();
  2480. }
  2481. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  2482. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  2483. if ($oMyChangeOp)
  2484. {
  2485. $oMyChangeOp->Set("type", "removed");
  2486. $oMyChangeOp->DBInsertNoReload();
  2487. }
  2488. }
  2489. else
  2490. {
  2491. // Keep track of link changes
  2492. //
  2493. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  2494. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2495. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  2496. if ($oMyChangeOp)
  2497. {
  2498. $oMyChangeOp->Set("link_id", $this->GetKey());
  2499. $iId = $oMyChangeOp->DBInsertNoReload();
  2500. }
  2501. }
  2502. }
  2503. }
  2504. // Return an empty set for the parent of all
  2505. // May be overloaded.
  2506. // Anyhow, this way of implementing the relations suffers limitations (not handling the redundancy)
  2507. // and you should consider defining those things in XML.
  2508. public static function GetRelationQueries($sRelCode)
  2509. {
  2510. return array();
  2511. }
  2512. // Reserved: do not overload
  2513. public static function GetRelationQueriesEx($sRelCode)
  2514. {
  2515. return array();
  2516. }
  2517. /**
  2518. * Will be deprecated soon - use GetRelatedObjectsDown/Up instead to take redundancy into account
  2519. */
  2520. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  2521. {
  2522. // Temporary patch: until the impact analysis GUI gets rewritten,
  2523. // let's consider that "depends on" is equivalent to "impacts/up"
  2524. // The current patch has been implemented in DBObject and MetaModel
  2525. $sHackedRelCode = $sRelCode;
  2526. $bDown = true;
  2527. if ($sRelCode == 'depends on')
  2528. {
  2529. $sHackedRelCode = 'impacts';
  2530. $bDown = false;
  2531. }
  2532. foreach (MetaModel::EnumRelationQueries(get_class($this), $sHackedRelCode, $bDown) as $sDummy => $aQueryInfo)
  2533. {
  2534. $sQuery = $bDown ? $aQueryInfo['sQueryDown'] : $aQueryInfo['sQueryUp'];
  2535. //$bPropagate = $aQueryInfo["bPropagate"];
  2536. //$iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  2537. $iDepth = $iMaxDepth - 1;
  2538. // Note: the loop over the result set has been written in an unusual way for error reporting purposes
  2539. // In the case of a wrong query parameter name, the error occurs on the first call to Fetch,
  2540. // thus we need to have this first call into the try/catch, but
  2541. // we do NOT want to nest the try/catch for the error message to be clear
  2542. try
  2543. {
  2544. $oFlt = DBObjectSearch::FromOQL($sQuery);
  2545. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgsForQuery());
  2546. $oObj = $oObjSet->Fetch();
  2547. }
  2548. catch (Exception $e)
  2549. {
  2550. $sClassOfDefinition = $aQueryInfo['_legacy_'] ? get_class($this).'(or a parent)::GetRelationQueries()' : $aQueryInfo['sDefinedInClass'];
  2551. throw new Exception("Wrong query for the relation $sRelCode/$sClassOfDefinition/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
  2552. }
  2553. if ($oObj)
  2554. {
  2555. do
  2556. {
  2557. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  2558. $sObjKey = $oObj->GetKey();
  2559. if (array_key_exists($sRootClass, $aResults))
  2560. {
  2561. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  2562. {
  2563. continue; // already visited, skip
  2564. }
  2565. }
  2566. $aResults[$sRootClass][$sObjKey] = $oObj;
  2567. if ($iDepth > 0)
  2568. {
  2569. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  2570. }
  2571. }
  2572. while ($oObj = $oObjSet->Fetch());
  2573. }
  2574. }
  2575. return $aResults;
  2576. }
  2577. /**
  2578. * Compute the "RelatedObjects" (forward or "down" direction) for the object
  2579. * for the specified relation
  2580. *
  2581. * @param string $sRelCode The code of the relation to use for the computation
  2582. * @param int $iMaxDepth Maximum recursion depth
  2583. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2584. *
  2585. * @return RelationGraph The graph of all the related objects
  2586. */
  2587. public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2588. {
  2589. $oGraph = new RelationGraph();
  2590. $oGraph->AddSourceObject($this);
  2591. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2592. return $oGraph;
  2593. }
  2594. /**
  2595. * Compute the "RelatedObjects" (reverse or "up" direction) for the object
  2596. * for the specified relation
  2597. *
  2598. * @param string $sRelCode The code of the relation to use for the computation
  2599. * @param int $iMaxDepth Maximum recursion depth
  2600. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2601. *
  2602. * @return RelationGraph The graph of all the related objects
  2603. */
  2604. public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2605. {
  2606. $oGraph = new RelationGraph();
  2607. $oGraph->AddSourceObject($this);
  2608. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2609. return $oGraph;
  2610. }
  2611. public function GetReferencingObjects($bAllowAllData = false)
  2612. {
  2613. $aDependentObjects = array();
  2614. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  2615. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  2616. {
  2617. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  2618. {
  2619. // skip if this external key is behind an external field
  2620. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  2621. $oSearch = new DBObjectSearch($sRemoteClass);
  2622. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  2623. if ($bAllowAllData)
  2624. {
  2625. $oSearch->AllowAllData();
  2626. }
  2627. $oSet = new CMDBObjectSet($oSearch);
  2628. if ($oSet->Count() > 0)
  2629. {
  2630. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  2631. 'attribute' => $oExtKeyAttDef,
  2632. 'objects' => $oSet,
  2633. );
  2634. }
  2635. }
  2636. }
  2637. return $aDependentObjects;
  2638. }
  2639. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  2640. {
  2641. static $iLoopTimeLimit = null;
  2642. if ($iLoopTimeLimit == null)
  2643. {
  2644. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2645. }
  2646. $sClass = get_class($this);
  2647. $iThisId = $this->GetKey();
  2648. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  2649. if (array_key_exists($sClass, $aVisited))
  2650. {
  2651. if (in_array($iThisId, $aVisited[$sClass]))
  2652. {
  2653. return;
  2654. }
  2655. }
  2656. $aVisited[$sClass] = $iThisId;
  2657. if ($iDeleteOption == DEL_MANUAL)
  2658. {
  2659. // Stop the recursion here
  2660. return;
  2661. }
  2662. // Check the node itself
  2663. $this->DoCheckToDelete($oDeletionPlan);
  2664. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  2665. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  2666. // Getting and setting time limit are not symetric:
  2667. // www.php.net/manual/fr/function.set-time-limit.php#72305
  2668. $iPreviousTimeLimit = ini_get('max_execution_time');
  2669. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  2670. {
  2671. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  2672. {
  2673. set_time_limit($iLoopTimeLimit);
  2674. $oAttDef = $aData['attribute'];
  2675. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  2676. $oDepSet = $aData['objects'];
  2677. $oDepSet->Rewind();
  2678. while ($oDependentObj = $oDepSet->fetch())
  2679. {
  2680. $iId = $oDependentObj->GetKey();
  2681. if ($oAttDef->IsNullAllowed())
  2682. {
  2683. // Optional external key, list to reset
  2684. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  2685. {
  2686. // Move the child up one level i.e. set the same parent as the current object
  2687. $iParentId = $this->Get($oAttDef->GetCode());
  2688. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  2689. }
  2690. else
  2691. {
  2692. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  2693. }
  2694. }
  2695. else
  2696. {
  2697. // Mandatory external key, list to delete
  2698. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  2699. }
  2700. }
  2701. }
  2702. }
  2703. set_time_limit($iPreviousTimeLimit);
  2704. }
  2705. /**
  2706. * WILL DEPRECATED SOON
  2707. * Caching relying on an object set is not efficient since 2.0.3
  2708. * Use GetSynchroData instead
  2709. *
  2710. * Get all the synchro replica related to this object
  2711. * @param none
  2712. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  2713. */
  2714. public function GetMasterReplica()
  2715. {
  2716. $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";
  2717. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2718. return $oReplicaSet;
  2719. }
  2720. /**
  2721. * Get all the synchro data related to this object
  2722. * @param none
  2723. * @return array of data_source_id => array
  2724. * 'source' => $oSource,
  2725. * 'attributes' => array of $oSynchroAttribute
  2726. * 'replica' => array of $oReplica (though only one should exist, misuse of the data sync can have this consequence)
  2727. */
  2728. public function GetSynchroData()
  2729. {
  2730. if (is_null($this->m_aSynchroData))
  2731. {
  2732. $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";
  2733. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2734. $this->m_aSynchroData = array();
  2735. while($aData = $oReplicaSet->FetchAssoc())
  2736. {
  2737. $iSourceId = $aData['datasource']->GetKey();
  2738. if (!array_key_exists($iSourceId, $this->m_aSynchroData))
  2739. {
  2740. $aAttributes = array();
  2741. $oAttrSet = $aData['datasource']->Get('attribute_list');
  2742. while($oSyncAttr = $oAttrSet->Fetch())
  2743. {
  2744. $aAttributes[$oSyncAttr->Get('attcode')] = $oSyncAttr;
  2745. }
  2746. $this->m_aSynchroData[$iSourceId] = array(
  2747. 'source' => $aData['datasource'],
  2748. 'attributes' => $aAttributes,
  2749. 'replica' => array()
  2750. );
  2751. }
  2752. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2753. $this->m_aSynchroData[$iSourceId]['replica'][] = $aData['replica'];
  2754. }
  2755. }
  2756. return $this->m_aSynchroData;
  2757. }
  2758. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2759. {
  2760. $iFlags = OPT_ATT_NORMAL;
  2761. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  2762. {
  2763. if ($iSourceId == SynchroExecution::GetCurrentTaskId())
  2764. {
  2765. // Ignore the current task (check to write => ok)
  2766. continue;
  2767. }
  2768. // Assumption: one replica - take the first one!
  2769. $oReplica = reset($aSourceData['replica']);
  2770. $oSource = $aSourceData['source'];
  2771. if (array_key_exists($sAttCode, $aSourceData['attributes']))
  2772. {
  2773. $oSyncAttr = $aSourceData['attributes'][$sAttCode];
  2774. if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2775. {
  2776. $iFlags |= OPT_ATT_SLAVE;
  2777. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2778. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2779. }
  2780. }
  2781. }
  2782. return $iFlags;
  2783. }
  2784. public function InSyncScope()
  2785. {
  2786. //
  2787. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2788. //
  2789. static $aSynchroClasses = null;
  2790. if (is_null($aSynchroClasses))
  2791. {
  2792. $aSynchroClasses = array();
  2793. $sOQL = "SELECT SynchroDataSource AS datasource";
  2794. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2795. while($oSource = $oSourceSet->Fetch())
  2796. {
  2797. $sTarget = $oSource->Get('scope_class');
  2798. $aSynchroClasses[] = $sTarget;
  2799. }
  2800. }
  2801. foreach($aSynchroClasses as $sClass)
  2802. {
  2803. if ($this instanceof $sClass)
  2804. {
  2805. return true;
  2806. }
  2807. }
  2808. return false;
  2809. }
  2810. /////////////////////////////////////////////////////////////////////////
  2811. //
  2812. // Experimental iDisplay implementation
  2813. //
  2814. /////////////////////////////////////////////////////////////////////////
  2815. public static function MapContextParam($sContextParam)
  2816. {
  2817. return null;
  2818. }
  2819. public function GetHilightClass()
  2820. {
  2821. $sCode = $this->ComputeHighlightCode();
  2822. if($sCode != '')
  2823. {
  2824. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  2825. if (array_key_exists($sCode, $aHighlightScale))
  2826. {
  2827. return $aHighlightScale[$sCode]['color'];
  2828. }
  2829. }
  2830. return HILIGHT_CLASS_NONE;
  2831. }
  2832. public function DisplayDetails(WebPage $oPage, $bEditMode = false)
  2833. {
  2834. $oPage->add('<h1>'.MetaModel::GetName(get_class($this)).': '.$this->GetName().'</h1>');
  2835. $aValues = array();
  2836. $aList = MetaModel::FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2837. if (empty($aList))
  2838. {
  2839. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2840. }
  2841. foreach($aList as $sAttCode)
  2842. {
  2843. $aValues[$sAttCode] = array('label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode));
  2844. }
  2845. $oPage->details($aValues);
  2846. }
  2847. const CALLBACK_AFTERINSERT = 0;
  2848. /**
  2849. * Register a call back that will be called when some internal event happens
  2850. *
  2851. * @param $iType string Any of the CALLBACK_x constants
  2852. * @param $callback callable Call specification like a function name, or array('<class>', '<method>') or array($object, '<method>')
  2853. * @param $aParameters Array Values that will be passed to the callback, after $this
  2854. */
  2855. public function RegisterCallback($iType, $callback, $aParameters = array())
  2856. {
  2857. $sCallBackName = '';
  2858. if (!is_callable($callback, false, $sCallBackName))
  2859. {
  2860. throw new Exception('Registering an unknown/protected function or wrong syntax for the call spec: '.$sCallBackName);
  2861. }
  2862. $this->m_aCallbacks[$iType][] = array(
  2863. 'callback' => $callback,
  2864. 'params' => $aParameters
  2865. );
  2866. }
  2867. /**
  2868. * Computes a text-like fingerprint identifying the content of the object
  2869. * but excluding the specified columns
  2870. * @param $aExcludedColumns array The list of columns to exclude
  2871. * @return string
  2872. */
  2873. public function Fingerprint($aExcludedColumns = array())
  2874. {
  2875. $sFingerprint = '';
  2876. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2877. {
  2878. if (!in_array($sAttCode, $aExcludedColumns))
  2879. {
  2880. if ($oAttDef->IsPartOfFingerprint())
  2881. {
  2882. $sFingerprint .= chr(0).$oAttDef->Fingerprint($this->Get($sAttCode));
  2883. }
  2884. }
  2885. }
  2886. return $sFingerprint;
  2887. }
  2888. /**
  2889. * Execute a set of scripted actions onto the current object
  2890. * See ExecAction for the syntax and features of the scripted actions
  2891. *
  2892. * @param $aActions array of statements (e.g. "set(name, Made after $source->name$)")
  2893. * @param $aSourceObjects Array of Alias => Context objects (Convention: some statements require the 'source' element
  2894. * @throws Exception
  2895. */
  2896. public function ExecActions($aActions, $aSourceObjects)
  2897. {
  2898. foreach($aActions as $sAction)
  2899. {
  2900. try
  2901. {
  2902. if (preg_match('/^(\S*)\s*\((.*)\)$/ms', $sAction, $aMatches)) // multiline and newline matched by a dot
  2903. {
  2904. $sVerb = trim($aMatches[1]);
  2905. $sParams = $aMatches[2];
  2906. // the coma is the separator for the parameters
  2907. // comas can be escaped: \,
  2908. $sParams = str_replace(array("\\\\", "\\,"), array("__backslash__", "__coma__"), $sParams);
  2909. $sParams = trim($sParams);
  2910. if (strlen($sParams) == 0)
  2911. {
  2912. $aParams = array();
  2913. }
  2914. else
  2915. {
  2916. $aParams = explode(',', $sParams);
  2917. foreach ($aParams as &$sParam)
  2918. {
  2919. $sParam = str_replace(array("__backslash__", "__coma__"), array("\\", ","), $sParam);
  2920. $sParam = trim($sParam);
  2921. }
  2922. }
  2923. $this->ExecAction($sVerb, $aParams, $aSourceObjects);
  2924. }
  2925. else
  2926. {
  2927. throw new Exception("Invalid syntax");
  2928. }
  2929. }
  2930. catch(Exception $e)
  2931. {
  2932. throw new Exception('Action: '.$sAction.' - '.$e->getMessage());
  2933. }
  2934. }
  2935. }
  2936. /**
  2937. * Helper to copy an attribute between two objects (in memory)
  2938. * Originally designed for ExecAction()
  2939. */
  2940. public function CopyAttribute($oSourceObject, $sSourceAttCode, $sDestAttCode)
  2941. {
  2942. if ($sSourceAttCode == 'id')
  2943. {
  2944. $oSourceAttDef = null;
  2945. }
  2946. else
  2947. {
  2948. if (!MetaModel::IsValidAttCode(get_class($this), $sDestAttCode))
  2949. {
  2950. throw new Exception("Unknown attribute ".get_class($this)."::".$sDestAttCode);
  2951. }
  2952. if (!MetaModel::IsValidAttCode(get_class($oSourceObject), $sSourceAttCode))
  2953. {
  2954. throw new Exception("Unknown attribute ".get_class($oSourceObject)."::".$sSourceAttCode);
  2955. }
  2956. $oSourceAttDef = MetaModel::GetAttributeDef(get_class($oSourceObject), $sSourceAttCode);
  2957. }
  2958. if (is_object($oSourceAttDef) && $oSourceAttDef->IsLinkSet())
  2959. {
  2960. // The copy requires that we create a new object set (the semantic of DBObject::Set is unclear about link sets)
  2961. $oDestSet = DBObjectSet::FromScratch($oSourceAttDef->GetLinkedClass());
  2962. $oSourceSet = $oSourceObject->Get($sSourceAttCode);
  2963. $oSourceSet->Rewind();
  2964. while ($oSourceLink = $oSourceSet->Fetch())
  2965. {
  2966. // Clone the link
  2967. $sLinkClass = get_class($oSourceLink);
  2968. $oLinkClone = MetaModel::NewObject($sLinkClass);
  2969. foreach(MetaModel::ListAttributeDefs($sLinkClass) as $sAttCode => $oAttDef)
  2970. {
  2971. // As of now, ignore other attribute (do not attempt to recurse!)
  2972. if ($oAttDef->IsScalar())
  2973. {
  2974. $oLinkClone->Set($sAttCode, $oSourceLink->Get($sAttCode));
  2975. }
  2976. }
  2977. // Not necessary - this will be handled by DBObject
  2978. // $oLinkClone->Set($oSourceAttDef->GetExtKeyToMe(), 0);
  2979. $oDestSet->AddObject($oLinkClone);
  2980. }
  2981. $this->Set($sDestAttCode, $oDestSet);
  2982. }
  2983. else
  2984. {
  2985. $this->Set($sDestAttCode, $oSourceObject->Get($sSourceAttCode));
  2986. }
  2987. }
  2988. /**
  2989. * Execute a scripted action onto the current object
  2990. * - clone (att1, att2, att3, ...)
  2991. * - clone_scalars ()
  2992. * - copy (source_att, dest_att)
  2993. * - reset (att)
  2994. * - nullify (att)
  2995. * - set (att, value (placeholders $source->att$ or $current_date$, or $current_contact_id$, ...))
  2996. * - append (att, value (placeholders $source->att$ or $current_date$, or $current_contact_id$, ...))
  2997. * - add_to_list (source_key_att, dest_att)
  2998. * - add_to_list (source_key_att, dest_att, lnk_att, lnk_att_value)
  2999. * - apply_stimulus (stimulus)
  3000. * - call_method (method_name)
  3001. *
  3002. * @param $sVerb string Any of the verb listed above (e.g. "set")
  3003. * @param $aParams array of strings (e.g. array('name', 'copied from $source->name$')
  3004. * @param $aSourceObjects Array of Alias => Context objects (Convention: some statements require the 'source' element
  3005. * @throws CoreException
  3006. * @throws CoreUnexpectedValue
  3007. * @throws Exception
  3008. */
  3009. public function ExecAction($sVerb, $aParams, $aSourceObjects)
  3010. {
  3011. switch($sVerb)
  3012. {
  3013. case 'clone':
  3014. if (!array_key_exists('source', $aSourceObjects))
  3015. {
  3016. throw new Exception('Missing conventional "source" object');
  3017. }
  3018. $oObjectToRead = $aSourceObjects['source'];
  3019. foreach($aParams as $sAttCode)
  3020. {
  3021. $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
  3022. }
  3023. break;
  3024. case 'clone_scalars':
  3025. if (!array_key_exists('source', $aSourceObjects))
  3026. {
  3027. throw new Exception('Missing conventional "source" object');
  3028. }
  3029. $oObjectToRead = $aSourceObjects['source'];
  3030. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  3031. {
  3032. if ($oAttDef->IsScalar())
  3033. {
  3034. $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
  3035. }
  3036. }
  3037. break;
  3038. case 'copy':
  3039. if (!array_key_exists('source', $aSourceObjects))
  3040. {
  3041. throw new Exception('Missing conventional "source" object');
  3042. }
  3043. $oObjectToRead = $aSourceObjects['source'];
  3044. if (!array_key_exists(0, $aParams))
  3045. {
  3046. throw new Exception('Missing argument #1: source attribute');
  3047. }
  3048. $sSourceAttCode = $aParams[0];
  3049. if (!array_key_exists(1, $aParams))
  3050. {
  3051. throw new Exception('Missing argument #2: target attribute');
  3052. }
  3053. $sDestAttCode = $aParams[1];
  3054. $this->CopyAttribute($oObjectToRead, $sSourceAttCode, $sDestAttCode);
  3055. break;
  3056. case 'reset':
  3057. if (!array_key_exists(0, $aParams))
  3058. {
  3059. throw new Exception('Missing argument #1: target attribute');
  3060. }
  3061. $sAttCode = $aParams[0];
  3062. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3063. {
  3064. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3065. }
  3066. $this->Set($sAttCode, $this->GetDefaultValue($sAttCode));
  3067. break;
  3068. case 'nullify':
  3069. if (!array_key_exists(0, $aParams))
  3070. {
  3071. throw new Exception('Missing argument #1: target attribute');
  3072. }
  3073. $sAttCode = $aParams[0];
  3074. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3075. {
  3076. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3077. }
  3078. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  3079. $this->Set($sAttCode, $oAttDef->GetNullValue());
  3080. break;
  3081. case 'set':
  3082. if (!array_key_exists(0, $aParams))
  3083. {
  3084. throw new Exception('Missing argument #1: target attribute');
  3085. }
  3086. $sAttCode = $aParams[0];
  3087. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3088. {
  3089. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3090. }
  3091. if (!array_key_exists(1, $aParams))
  3092. {
  3093. throw new Exception('Missing argument #2: value to set');
  3094. }
  3095. $sRawValue = $aParams[1];
  3096. $aContext = array();
  3097. foreach ($aSourceObjects as $sAlias => $oObject)
  3098. {
  3099. $aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
  3100. }
  3101. $aContext['current_contact_id'] = UserRights::GetContactId();
  3102. $aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
  3103. $aContext['current_date'] = date(AttributeDate::GetSQLFormat());
  3104. $aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
  3105. $sValue = MetaModel::ApplyParams($sRawValue, $aContext);
  3106. $this->Set($sAttCode, $sValue);
  3107. break;
  3108. case 'append':
  3109. if (!array_key_exists(0, $aParams))
  3110. {
  3111. throw new Exception('Missing argument #1: target attribute');
  3112. }
  3113. $sAttCode = $aParams[0];
  3114. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3115. {
  3116. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3117. }
  3118. if (!array_key_exists(1, $aParams))
  3119. {
  3120. throw new Exception('Missing argument #2: value to append');
  3121. }
  3122. $sRawAddendum = $aParams[1];
  3123. $aContext = array();
  3124. foreach ($aSourceObjects as $sAlias => $oObject)
  3125. {
  3126. $aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
  3127. }
  3128. $aContext['current_contact_id'] = UserRights::GetContactId();
  3129. $aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
  3130. $aContext['current_date'] = date(AttributeDate::GetSQLFormat());
  3131. $aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
  3132. $sAddendum = MetaModel::ApplyParams($sRawAddendum, $aContext);
  3133. $this->Set($sAttCode, $this->Get($sAttCode).$sAddendum);
  3134. break;
  3135. case 'add_to_list':
  3136. if (!array_key_exists('source', $aSourceObjects))
  3137. {
  3138. throw new Exception('Missing conventional "source" object');
  3139. }
  3140. $oObjectToRead = $aSourceObjects['source'];
  3141. if (!array_key_exists(0, $aParams))
  3142. {
  3143. throw new Exception('Missing argument #1: source attribute');
  3144. }
  3145. $sSourceKeyAttCode = $aParams[0];
  3146. if (($sSourceKeyAttCode != 'id') && !MetaModel::IsValidAttCode(get_class($oObjectToRead), $sSourceKeyAttCode))
  3147. {
  3148. throw new Exception("Unknown attribute ".get_class($oObjectToRead)."::".$sSourceKeyAttCode);
  3149. }
  3150. if (!array_key_exists(1, $aParams))
  3151. {
  3152. throw new Exception('Missing argument #2: target attribute (link set)');
  3153. }
  3154. $sTargetListAttCode = $aParams[1]; // indirect !!!
  3155. if (!MetaModel::IsValidAttCode(get_class($this), $sTargetListAttCode))
  3156. {
  3157. throw new Exception("Unknown attribute ".get_class($this)."::".$sTargetListAttCode);
  3158. }
  3159. if (isset($aParams[2]) && isset($aParams[3]))
  3160. {
  3161. $sRoleAttCode = $aParams[2];
  3162. $sRoleValue = $aParams[3];
  3163. }
  3164. $iObjKey = $oObjectToRead->Get($sSourceKeyAttCode);
  3165. if ($iObjKey > 0)
  3166. {
  3167. $oLinkSet = $this->Get($sTargetListAttCode);
  3168. $oListAttDef = MetaModel::GetAttributeDef(get_class($this), $sTargetListAttCode);
  3169. $oLnk = MetaModel::NewObject($oListAttDef->GetLinkedClass());
  3170. $oLnk->Set($oListAttDef->GetExtKeyToRemote(), $iObjKey);
  3171. if (isset($sRoleAttCode))
  3172. {
  3173. if (!MetaModel::IsValidAttCode(get_class($oLnk), $sRoleAttCode))
  3174. {
  3175. throw new Exception("Unknown attribute ".get_class($oLnk)."::".$sRoleAttCode);
  3176. }
  3177. $oLnk->Set($sRoleAttCode, $sRoleValue);
  3178. }
  3179. $oLinkSet->AddObject($oLnk);
  3180. $this->Set($sTargetListAttCode, $oLinkSet);
  3181. }
  3182. break;
  3183. case 'apply_stimulus':
  3184. if (!array_key_exists(0, $aParams))
  3185. {
  3186. throw new Exception('Missing argument #1: stimulus');
  3187. }
  3188. $sStimulus = $aParams[0];
  3189. if (!in_array($sStimulus, MetaModel::EnumStimuli(get_class($this))))
  3190. {
  3191. throw new Exception("Unknown stimulus ".get_class($this)."::".$sStimulus);
  3192. }
  3193. $this->ApplyStimulus($sStimulus);
  3194. break;
  3195. case 'call_method':
  3196. if (!array_key_exists('source', $aSourceObjects))
  3197. {
  3198. throw new Exception('Missing conventional "source" object');
  3199. }
  3200. $oObjectToRead = $aSourceObjects['source'];
  3201. if (!array_key_exists(0, $aParams))
  3202. {
  3203. throw new Exception('Missing argument #1: method name');
  3204. }
  3205. $sMethod = $aParams[0];
  3206. $aCallSpec = array($this, $sMethod);
  3207. if (!is_callable($aCallSpec))
  3208. {
  3209. throw new Exception("Unknown method ".get_class($this)."::".$sMethod.'()');
  3210. }
  3211. // Note: $oObjectToRead has been preserved when adding $aSourceObjects, so as to remain backward compatible with methods having only 1 parameter ($oObjectToRead�
  3212. call_user_func($aCallSpec, $oObjectToRead, $aSourceObjects);
  3213. break;
  3214. default:
  3215. throw new Exception("Invalid verb");
  3216. }
  3217. }
  3218. public function IsArchived($sKeyAttCode = null)
  3219. {
  3220. $bRet = false;
  3221. $sFlagAttCode = is_null($sKeyAttCode) ? 'archive_flag' : $sKeyAttCode.'_archive_flag';
  3222. if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode))
  3223. {
  3224. $bRet = true;
  3225. }
  3226. return $bRet;
  3227. }
  3228. public function IsObsolete($sKeyAttCode = null)
  3229. {
  3230. $bRet = false;
  3231. $sFlagAttCode = is_null($sKeyAttCode) ? 'obsolescence_flag' : $sKeyAttCode.'_obsolescence_flag';
  3232. if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode))
  3233. {
  3234. $bRet = true;
  3235. }
  3236. return $bRet;
  3237. }
  3238. /**
  3239. * @param $bArchive
  3240. * @throws Exception
  3241. */
  3242. protected function DBWriteArchiveFlag($bArchive)
  3243. {
  3244. if (!MetaModel::IsArchivable(get_class($this)))
  3245. {
  3246. throw new Exception(get_class($this).' is not an archivable class');
  3247. }
  3248. $iFlag = $bArchive ? 1 : 0;
  3249. $sDate = $bArchive ? '"'.date(AttributeDate::GetSQLFormat()).'"' : 'null';
  3250. $sClass = get_class($this);
  3251. $sArchiveRoot = MetaModel::GetAttributeOrigin($sClass, 'archive_flag');
  3252. $sRootTable = MetaModel::DBGetTable($sArchiveRoot);
  3253. $sRootKey = MetaModel::DBGetKey($sArchiveRoot);
  3254. $aJoins = array("`$sRootTable`");
  3255. $aUpdates = array();
  3256. foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  3257. {
  3258. if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) continue;
  3259. $sTable = MetaModel::DBGetTable($sParentClass);
  3260. $aUpdates[] = "`$sTable`.`archive_flag` = $iFlag";
  3261. if ($sParentClass == $sArchiveRoot)
  3262. {
  3263. if (!$bArchive || $this->Get('archive_date') == '')
  3264. {
  3265. // Erase or set the date (do not change it)
  3266. $aUpdates[] = "`$sTable`.`archive_date` = $sDate";
  3267. }
  3268. }
  3269. else
  3270. {
  3271. $sKey = MetaModel::DBGetKey($sParentClass);
  3272. $aJoins[] = "`$sTable` ON `$sTable`.`$sKey` = `$sRootTable`.`$sRootKey`";
  3273. }
  3274. }
  3275. $sJoins = implode(' INNER JOIN ', $aJoins);
  3276. $sValues = implode(', ', $aUpdates);
  3277. $sUpdateQuery = "UPDATE $sJoins SET $sValues WHERE `$sRootTable`.`$sRootKey` = ".$this->GetKey();
  3278. CMDBSource::Query($sUpdateQuery);
  3279. }
  3280. /**
  3281. * Can be called to repair the database (tables consistency)
  3282. * The archive_date will be preserved
  3283. * @throws Exception
  3284. */
  3285. public function DBArchive()
  3286. {
  3287. $this->DBWriteArchiveFlag(true);
  3288. $this->m_aCurrValues['archive_flag'] = true;
  3289. $this->m_aOrigValues['archive_flag'] = true;
  3290. }
  3291. public function DBUnarchive()
  3292. {
  3293. $this->DBWriteArchiveFlag(false);
  3294. $this->m_aCurrValues['archive_flag'] = false;
  3295. $this->m_aOrigValues['archive_flag'] = false;
  3296. $this->m_aCurrValues['archive_date'] = null;
  3297. $this->m_aOrigValues['archive_date'] = null;
  3298. }
  3299. }