dbobject.class.php 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481
  1. <?php
  2. // Copyright (C) 2010-2014 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. * Class dbObject: the root of persistent classes
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('metamodel.class.php');
  25. require_once('deletionplan.class.inc.php');
  26. require_once('mutex.class.inc.php');
  27. /**
  28. * A persistent object, as defined by the metamodel
  29. *
  30. * @package iTopORM
  31. */
  32. abstract class DBObject
  33. {
  34. private static $m_aMemoryObjectsByClass = array();
  35. private static $m_aBulkInsertItems = array(); // class => array of ('table' => array of (array of <sql_value>))
  36. private static $m_aBulkInsertCols = array(); // class => array of ('table' => array of <sql_column>)
  37. private static $m_bBulkInsert = false;
  38. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  39. private $m_iKey = null;
  40. private $m_aCurrValues = array();
  41. protected $m_aOrigValues = array();
  42. protected $m_aExtendedData = null;
  43. private $m_bDirty = false; // Means: "a modification is ongoing"
  44. // The object may have incorrect external keys, then any attempt of reload must be avoided
  45. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  46. // if null, then the check has to be performed again to know the status
  47. protected $m_bSecurityIssue = null;
  48. protected $m_aCheckIssues = null;
  49. protected $m_aDeleteIssues = null;
  50. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  51. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  52. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  53. protected $m_oMasterReplicaSet = null; // Set of SynchroReplica related to this object
  54. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  55. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  56. {
  57. if (!empty($aRow))
  58. {
  59. $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  60. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  61. return;
  62. }
  63. // Creation of a brand new object
  64. //
  65. $this->m_iKey = self::GetNextTempId(get_class($this));
  66. // set default values
  67. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  68. {
  69. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  70. $this->m_aOrigValues[$sAttCode] = null;
  71. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  72. {
  73. // This field has to be read from the DB
  74. // Leave the flag unset (optimization)
  75. }
  76. else
  77. {
  78. // No need to trigger a reload for that attribute
  79. // Let's consider it as being already fully loaded
  80. $this->m_aLoadedAtt[$sAttCode] = true;
  81. }
  82. }
  83. }
  84. // Read-only <=> Written once (archive)
  85. public function RegisterAsDirty()
  86. {
  87. // While the object may be written to the DB, it is NOT possible to reload it
  88. // or at least not possible to reload it the same way
  89. $this->m_bDirty = true;
  90. }
  91. public function IsNew()
  92. {
  93. return (!$this->m_bIsInDB);
  94. }
  95. // Returns an Id for memory objects
  96. static protected function GetNextTempId($sClass)
  97. {
  98. $sRootClass = MetaModel::GetRootClass($sClass);
  99. if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
  100. {
  101. self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
  102. }
  103. self::$m_aMemoryObjectsByClass[$sRootClass]++;
  104. return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
  105. }
  106. public function __toString()
  107. {
  108. $sRet = '';
  109. $sClass = get_class($this);
  110. $sRootClass = MetaModel::GetRootClass($sClass);
  111. $iPKey = $this->GetKey();
  112. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  113. $sRet .= "<ul class=\"treeview\">\n";
  114. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  115. {
  116. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  117. }
  118. $sRet .= "</ul>";
  119. return $sRet;
  120. }
  121. // Restore initial values... mmmm, to be discussed
  122. public function DBRevert()
  123. {
  124. $this->Reload();
  125. }
  126. protected function IsFullyLoaded()
  127. {
  128. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  129. {
  130. if (!$oAttDef->LoadInObject()) continue;
  131. if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
  132. {
  133. return false;
  134. }
  135. }
  136. return true;
  137. }
  138. public function Reload()
  139. {
  140. assert($this->m_bIsInDB);
  141. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false/*, $this->m_bAllowAllData*/);
  142. if (empty($aRow))
  143. {
  144. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  145. }
  146. $this->FromRow($aRow);
  147. // Process linked set attributes
  148. //
  149. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  150. {
  151. if (!$oAttDef->IsLinkSet()) continue;
  152. // Load the link information
  153. $sLinkClass = $oAttDef->GetLinkedClass();
  154. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  155. // The class to target is not the current class, because if this is a derived class,
  156. // it may differ from the target class, then things start to become confusing
  157. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  158. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  159. $oMyselfSearch = new DBObjectSearch($sMyClass);
  160. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  161. $oLinkSearch = new DBObjectSearch($sLinkClass);
  162. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  163. $oLinks = new DBObjectSet($oLinkSearch);
  164. $this->m_aCurrValues[$sAttCode] = $oLinks;
  165. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  166. $this->m_aLoadedAtt[$sAttCode] = true;
  167. }
  168. $this->m_bFullyLoaded = true;
  169. }
  170. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  171. {
  172. if (strlen($sClassAlias) == 0)
  173. {
  174. // Default to the current class
  175. $sClassAlias = get_class($this);
  176. }
  177. $this->m_iKey = null;
  178. $this->m_bIsInDB = true;
  179. $this->m_aCurrValues = array();
  180. $this->m_aOrigValues = array();
  181. $this->m_aLoadedAtt = array();
  182. $this->m_bCheckStatus = true;
  183. // Get the key
  184. //
  185. $sKeyField = $sClassAlias."id";
  186. if (!array_key_exists($sKeyField, $aRow))
  187. {
  188. // #@# Bug ?
  189. throw new CoreException("Missing key for class '".get_class($this)."'");
  190. }
  191. $iPKey = $aRow[$sKeyField];
  192. if (!self::IsValidPKey($iPKey))
  193. {
  194. if (is_null($iPKey))
  195. {
  196. throw new CoreException("Missing object id in query result (found null)");
  197. }
  198. else
  199. {
  200. throw new CoreException("An object id must be an integer value ($iPKey)");
  201. }
  202. }
  203. $this->m_iKey = $iPKey;
  204. // Build the object from an array of "attCode"=>"value")
  205. //
  206. $bFullyLoaded = true; // ... set to false if any attribute is not found
  207. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  208. {
  209. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  210. }
  211. else
  212. {
  213. $aAttList = $aAttToLoad[$sClassAlias];
  214. }
  215. foreach($aAttList as $sAttCode=>$oAttDef)
  216. {
  217. // Skip links (could not be loaded by the mean of this query)
  218. if ($oAttDef->IsLinkSet()) continue;
  219. if (!$oAttDef->LoadInObject()) continue;
  220. // Note: we assume that, for a given attribute, if it can be loaded,
  221. // then one column will be found with an empty suffix, the others have a suffix
  222. // Take care: the function isset will return false in case the value is null,
  223. // which is something that could happen on open joins
  224. $sAttRef = $sClassAlias.$sAttCode;
  225. if (array_key_exists($sAttRef, $aRow))
  226. {
  227. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  228. $this->m_aCurrValues[$sAttCode] = $value;
  229. if (is_object($value))
  230. {
  231. $this->m_aOrigValues[$sAttCode] = clone $value;
  232. }
  233. else
  234. {
  235. $this->m_aOrigValues[$sAttCode] = $value;
  236. }
  237. $this->m_aLoadedAtt[$sAttCode] = true;
  238. }
  239. else
  240. {
  241. // This attribute was expected and not found in the query columns
  242. $bFullyLoaded = false;
  243. }
  244. }
  245. // Load extended data
  246. if ($aExtendedDataSpec != null)
  247. {
  248. $aExtendedDataSpec['table'];
  249. foreach($aExtendedDataSpec['fields'] as $sColumn)
  250. {
  251. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  252. if (array_key_exists($sColRef, $aRow))
  253. {
  254. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  255. }
  256. }
  257. }
  258. return $bFullyLoaded;
  259. }
  260. public function Set($sAttCode, $value)
  261. {
  262. if ($sAttCode == 'finalclass')
  263. {
  264. // Ignore it - this attribute is set upon object creation and that's it
  265. return;
  266. }
  267. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  268. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  269. {
  270. // First time Set is called... ensure that the object gets fully loaded
  271. // Otherwise we would lose the values on a further Reload
  272. // + consistency does not make sense !
  273. $this->Reload();
  274. }
  275. if ($oAttDef->IsExternalKey())
  276. {
  277. if (is_object($value))
  278. {
  279. // Setting an external key with a whole object (instead of just an ID)
  280. // let's initialize also the external fields that depend on it
  281. // (useful when building objects in memory and not from a query)
  282. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  283. {
  284. 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");
  285. }
  286. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  287. {
  288. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  289. {
  290. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  291. }
  292. }
  293. }
  294. else if ($this->m_aCurrValues[$sAttCode] != $value)
  295. {
  296. // Setting an external key, but no any other information is available...
  297. // Invalidate the corresponding fields so that they get reloaded in case they are needed (See Get())
  298. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  299. {
  300. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  301. {
  302. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  303. unset($this->m_aLoadedAtt[$sCode]);
  304. }
  305. }
  306. }
  307. }
  308. if(!$oAttDef->IsScalar() && !is_object($value))
  309. {
  310. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  311. }
  312. if($oAttDef->IsLinkSet())
  313. {
  314. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  315. {
  316. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  317. }
  318. $oObjectSet = $value;
  319. $sSetClass = $oObjectSet->GetClass();
  320. $sLinkClass = $oAttDef->GetLinkedClass();
  321. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  322. if ($sSetClass != $sLinkClass)
  323. {
  324. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  325. }
  326. }
  327. $realvalue = $oAttDef->MakeRealValue($value, $this);
  328. $this->m_aCurrValues[$sAttCode] = $realvalue;
  329. // The object has changed, reset caches
  330. $this->m_bCheckStatus = null;
  331. $this->m_aAsArgs = null;
  332. // Make sure we do not reload it anymore... before saving it
  333. $this->RegisterAsDirty();
  334. }
  335. public function GetLabel($sAttCode)
  336. {
  337. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  338. return $oAttDef->GetLabel();
  339. }
  340. public function Get($sAttCode)
  341. {
  342. if (($iPos = strpos($sAttCode, '->')) === false)
  343. {
  344. return $this->GetStrict($sAttCode);
  345. }
  346. else
  347. {
  348. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  349. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  350. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  351. {
  352. throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
  353. }
  354. $oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode);
  355. if (!is_null($oExtFieldAtt))
  356. {
  357. return $this->GetStrict($oExtFieldAtt->GetCode());
  358. }
  359. else
  360. {
  361. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  362. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  363. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  364. if (is_null($oRemoteObj))
  365. {
  366. return '';
  367. }
  368. else
  369. {
  370. return $oRemoteObj->Get($sRemoteAttCode);
  371. }
  372. }
  373. }
  374. }
  375. public function GetStrict($sAttCode)
  376. {
  377. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  378. if (!$oAttDef->LoadInObject())
  379. {
  380. $sParentAttCode = $oAttDef->GetParentAttCode();
  381. $parentValue = $this->GetStrict($sParentAttCode);
  382. $value = $oAttDef->GetValue($parentValue, $this);
  383. }
  384. else
  385. {
  386. if (isset($this->m_aLoadedAtt[$sAttCode]))
  387. {
  388. // Standard case... we have the information directly
  389. }
  390. elseif ($this->m_bIsInDB && !$this->m_bDirty)
  391. {
  392. // Lazy load (polymorphism): complete by reloading the entire object
  393. // #@# non-scalar attributes.... handle that differently?
  394. $oKPI = new ExecutionKPI();
  395. $this->Reload();
  396. $oKPI->ComputeStats('Reload', get_class($this).'/'.$sAttCode);
  397. }
  398. elseif ($sAttCode == 'friendlyname')
  399. {
  400. // The friendly name is not computed and the object is dirty
  401. // Todo: implement the computation of the friendly name based on sprintf()
  402. //
  403. $this->m_aCurrValues[$sAttCode] = '';
  404. }
  405. else
  406. {
  407. // Not loaded... is it related to an external key?
  408. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  409. {
  410. // Let's get the object and compute all of the corresponding attributes
  411. // (i.e not only the requested attribute)
  412. //
  413. $sExtKeyAttCode = $oAttDef->GetKeyAttCode();
  414. if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
  415. {
  416. $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  417. // Note: "allow all data" must be enabled because the external fields are always visible
  418. // to the current user even if this is not the case for the remote object
  419. // This is consistent with the behavior of the lists
  420. $oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
  421. }
  422. else
  423. {
  424. $oRemote = null;
  425. }
  426. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  427. {
  428. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sExtKeyAttCode))
  429. {
  430. if ($oRemote)
  431. {
  432. $this->m_aCurrValues[$sCode] = $oRemote->Get($oDef->GetExtAttCode());
  433. }
  434. else
  435. {
  436. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  437. }
  438. $this->m_aLoadedAtt[$sCode] = true;
  439. }
  440. }
  441. }
  442. }
  443. $value = $this->m_aCurrValues[$sAttCode];
  444. }
  445. if ($value instanceof DBObjectSet)
  446. {
  447. $value->Rewind();
  448. }
  449. return $value;
  450. }
  451. public function GetOriginal($sAttCode)
  452. {
  453. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  454. {
  455. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  456. }
  457. return $this->m_aOrigValues[$sAttCode];
  458. }
  459. /**
  460. * Returns data loaded by the mean of a dynamic and explicit JOIN
  461. */
  462. public function GetExtendedData()
  463. {
  464. return $this->m_aExtendedData;
  465. }
  466. /**
  467. * Updates the value of an external field by (re)loading the object
  468. * corresponding to the external key and getting the value from it
  469. *
  470. * UNUSED ?
  471. *
  472. * @param string $sAttCode Attribute code of the external field to update
  473. * @return void
  474. */
  475. protected function UpdateExternalField($sAttCode)
  476. {
  477. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  478. if ($oAttDef->IsExternalField())
  479. {
  480. $sTargetClass = $oAttDef->GetTargetClass();
  481. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  482. // Note: "allow all data" must be enabled because the external fields are always visible
  483. // to the current user even if this is not the case for the remote object
  484. // This is consistent with the behavior of the lists
  485. $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
  486. if (is_object($oObj))
  487. {
  488. $value = $oObj->Get($oAttDef->GetExtAttCode());
  489. $this->Set($sAttCode, $value);
  490. }
  491. }
  492. }
  493. public function ComputeValues()
  494. {
  495. }
  496. // Compute scalar attributes that depend on any other type of attribute
  497. final public function DoComputeValues()
  498. {
  499. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  500. // First check that we are not currently computing the fields
  501. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  502. foreach (debug_backtrace() as $aCallInfo)
  503. {
  504. if (!array_key_exists("class", $aCallInfo)) continue;
  505. if ($aCallInfo["class"] != get_class($this)) continue;
  506. if ($aCallInfo["function"] != "ComputeValues") continue;
  507. return; //skip!
  508. }
  509. $this->ComputeValues();
  510. }
  511. public function GetAsHTML($sAttCode, $bLocalize = true)
  512. {
  513. $sClass = get_class($this);
  514. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  515. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  516. {
  517. //return $this->Get($sAttCode.'_friendlyname');
  518. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  519. $iTargetKey = $this->Get($sAttCode);
  520. if ($iTargetKey < 0)
  521. {
  522. // the key points to an object that exists only in memory... no hyperlink points to it yet
  523. return '';
  524. }
  525. else
  526. {
  527. $sLabel = $this->Get($sAttCode.'_friendlyname');
  528. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  529. }
  530. }
  531. // That's a standard attribute (might be an ext field or a direct field, etc.)
  532. return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
  533. }
  534. public function GetEditValue($sAttCode)
  535. {
  536. $sClass = get_class($this);
  537. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  538. if ($oAtt->IsExternalKey())
  539. {
  540. $sTargetClass = $oAtt->GetTargetClass();
  541. if ($this->IsNew())
  542. {
  543. // The current object exists only in memory, don't try to query it in the DB !
  544. // instead let's query for the object pointed by the external key, and get its name
  545. $targetObjId = $this->Get($sAttCode);
  546. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  547. if (is_object($oTargetObj))
  548. {
  549. $sEditValue = $oTargetObj->GetName();
  550. }
  551. else
  552. {
  553. $sEditValue = 0;
  554. }
  555. }
  556. else
  557. {
  558. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  559. }
  560. }
  561. else
  562. {
  563. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
  564. }
  565. return $sEditValue;
  566. }
  567. public function GetAsXML($sAttCode, $bLocalize = true)
  568. {
  569. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  570. return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
  571. }
  572. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  573. {
  574. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  575. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  576. }
  577. public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
  578. {
  579. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  580. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
  581. }
  582. public function GetOriginalAsXML($sAttCode, $bLocalize = true)
  583. {
  584. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  585. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
  586. }
  587. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  588. {
  589. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  590. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  591. }
  592. public static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true)
  593. {
  594. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  595. // Safety net
  596. //
  597. if (empty($sLabel))
  598. {
  599. // If the object if not issued from a query but constructed programmatically
  600. // the label may be empty. In this case run a query to get the object's friendly name
  601. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
  602. if (is_object($oTmpObj))
  603. {
  604. $sLabel = $oTmpObj->GetName();
  605. }
  606. else
  607. {
  608. // May happen in case the target object is not in the list of allowed values for this attribute
  609. $sLabel = "<em>$sObjClass::$sObjKey</em>";
  610. }
  611. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  612. }
  613. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  614. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  615. if (strlen($sUrl) > 0)
  616. {
  617. return "<a href=\"$sUrl\" title=\"$sHint\">$sLabel</a>";
  618. }
  619. else
  620. {
  621. return $sLabel;
  622. }
  623. }
  624. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  625. {
  626. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext);
  627. }
  628. public static function ComputeStandardUIPage($sClass)
  629. {
  630. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  631. if (!isset($aUIPagesCache[$sClass]))
  632. {
  633. $UIPage = false;
  634. if (is_callable("$sClass::GetUIPage"))
  635. {
  636. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  637. }
  638. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  639. }
  640. $sPage = $aUIPagesCache[$sClass];
  641. return $sPage;
  642. }
  643. public static function GetUIPage()
  644. {
  645. return 'UI.php';
  646. }
  647. // could be in the metamodel ?
  648. public static function IsValidPKey($value)
  649. {
  650. return ((string)$value === (string)(int)$value);
  651. }
  652. public function GetKey()
  653. {
  654. return $this->m_iKey;
  655. }
  656. public function SetKey($iNewKey)
  657. {
  658. if (!self::IsValidPKey($iNewKey))
  659. {
  660. throw new CoreException("An object id must be an integer value ($iNewKey)");
  661. }
  662. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  663. {
  664. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  665. }
  666. $this->m_iKey = $iNewKey;
  667. }
  668. /**
  669. * Get the icon representing this object
  670. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  671. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  672. */
  673. public function GetIcon($bImgTag = true)
  674. {
  675. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  676. }
  677. /**
  678. * Gets the name of an object in a safe manner for displaying inside a web page
  679. * @return string
  680. */
  681. public function GetName()
  682. {
  683. return htmlentities($this->GetRawName(), ENT_QUOTES, 'UTF-8');
  684. }
  685. /**
  686. * Gets the raw name of an object, this is not safe for displaying inside a web page
  687. * since the " < > characters are not escaped and the name may contain some XSS script
  688. * instructions.
  689. * Use this function only for internal computations or for an output to a non-HTML destination
  690. * @return string
  691. */
  692. public function GetRawName()
  693. {
  694. return $this->Get('friendlyname');
  695. }
  696. public function GetState()
  697. {
  698. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  699. if (empty($sStateAttCode))
  700. {
  701. return '';
  702. }
  703. else
  704. {
  705. return $this->Get($sStateAttCode);
  706. }
  707. }
  708. public function GetStateLabel()
  709. {
  710. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  711. if (empty($sStateAttCode))
  712. {
  713. return '';
  714. }
  715. else
  716. {
  717. $sStateValue = $this->Get($sStateAttCode);
  718. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  719. }
  720. }
  721. public function GetStateDescription()
  722. {
  723. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  724. if (empty($sStateAttCode))
  725. {
  726. return '';
  727. }
  728. else
  729. {
  730. $sStateValue = $this->Get($sStateAttCode);
  731. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  732. }
  733. }
  734. /**
  735. * Overridable - Define attributes read-only from the end-user perspective
  736. *
  737. * @return array List of attcodes
  738. */
  739. public static function GetReadOnlyAttributes()
  740. {
  741. return null;
  742. }
  743. /**
  744. * Overridable - Get predefined objects (could be hardcoded)
  745. * The predefined objects will be synchronized with the DB at each install/upgrade
  746. * As soon as a class has predefined objects, then nobody can create nor delete objects
  747. * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
  748. */
  749. public static function GetPredefinedObjects()
  750. {
  751. return null;
  752. }
  753. /**
  754. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  755. * for the given attribute in the current state of the object
  756. * @param $sAttCode string $sAttCode The code of the attribute
  757. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  758. * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
  759. * @return integer Flags: the binary combination of the flags applicable to this attribute
  760. */
  761. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  762. {
  763. $iFlags = 0; // By default (if no life cycle) no flag at all
  764. $aReadOnlyAtts = $this->GetReadOnlyAttributes();
  765. if ($aReadOnlyAtts != null)
  766. {
  767. if (in_array($sAttCode, $aReadOnlyAtts))
  768. {
  769. return OPT_ATT_READONLY;
  770. }
  771. }
  772. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  773. if (!empty($sStateAttCode))
  774. {
  775. if ($sTargetState != '')
  776. {
  777. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  778. }
  779. else
  780. {
  781. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  782. }
  783. }
  784. $aReasons = array();
  785. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  786. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  787. }
  788. /**
  789. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  790. * for the given attribute for the current state of the object considered as an INITIAL state
  791. * @param string $sAttCode The code of the attribute
  792. * @return integer Flags: the binary combination of the flags applicable to this attribute
  793. */
  794. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  795. {
  796. $iFlags = 0;
  797. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  798. if (!empty($sStateAttCode))
  799. {
  800. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  801. }
  802. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  803. }
  804. // check if the given (or current) value is suitable for the attribute
  805. // return true if successfull
  806. // return the error desciption otherwise
  807. public function CheckValue($sAttCode, $value = null)
  808. {
  809. if (!is_null($value))
  810. {
  811. $toCheck = $value;
  812. }
  813. else
  814. {
  815. $toCheck = $this->Get($sAttCode);
  816. }
  817. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  818. if (!$oAtt->IsWritable())
  819. {
  820. return true;
  821. }
  822. elseif ($oAtt->IsNull($toCheck))
  823. {
  824. if ($oAtt->IsNullAllowed())
  825. {
  826. return true;
  827. }
  828. else
  829. {
  830. return "Null not allowed";
  831. }
  832. }
  833. elseif ($oAtt->IsExternalKey())
  834. {
  835. if (!MetaModel::SkipCheckExtKeys())
  836. {
  837. $sTargetClass = $oAtt->GetTargetClass();
  838. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  839. if (is_null($oTargetObj))
  840. {
  841. return "Target object not found ($sTargetClass::$toCheck)";
  842. }
  843. }
  844. if ($oAtt->IsHierarchicalKey())
  845. {
  846. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  847. if ($toCheck == $this->GetKey())
  848. {
  849. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  850. }
  851. }
  852. }
  853. elseif ($oAtt->IsScalar())
  854. {
  855. $aValues = $oAtt->GetAllowedValues($this->ToArgsForQuery());
  856. if (count($aValues) > 0)
  857. {
  858. if (!array_key_exists($toCheck, $aValues))
  859. {
  860. return "Value not allowed [$toCheck]";
  861. }
  862. }
  863. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  864. {
  865. $iLen = strlen($toCheck);
  866. if ($iLen > $iMaxSize)
  867. {
  868. return "String too long (found $iLen, limited to $iMaxSize)";
  869. }
  870. }
  871. if (!$oAtt->CheckFormat($toCheck))
  872. {
  873. return "Wrong format [$toCheck]";
  874. }
  875. }
  876. return true;
  877. }
  878. // check attributes together
  879. public function CheckConsistency()
  880. {
  881. return true;
  882. }
  883. // check integrity rules (before inserting or updating the object)
  884. // a displayable error is returned
  885. public function DoCheckToWrite()
  886. {
  887. $this->DoComputeValues();
  888. $aChanges = $this->ListChanges();
  889. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  890. {
  891. $res = $this->CheckValue($sAttCode);
  892. if ($res !== true)
  893. {
  894. // $res contains the error description
  895. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  896. }
  897. }
  898. if (count($this->m_aCheckIssues) > 0)
  899. {
  900. // No need to check consistency between attributes if any of them has
  901. // an unexpected value
  902. return;
  903. }
  904. $res = $this->CheckConsistency();
  905. if ($res !== true)
  906. {
  907. // $res contains the error description
  908. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  909. }
  910. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  911. //
  912. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  913. {
  914. foreach($aChanges as $sAttCode => $value)
  915. {
  916. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  917. if ($iFlags & OPT_ATT_SLAVE)
  918. {
  919. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  920. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  921. $sAttLabel = $oAttDef->GetLabel();
  922. foreach($aReasons as $aReasonInfo)
  923. {
  924. // Todo: associate the attribute code with the error
  925. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  926. }
  927. }
  928. }
  929. }
  930. }
  931. final public function CheckToWrite()
  932. {
  933. if (MetaModel::SkipCheckToWrite())
  934. {
  935. return array(true, array());
  936. }
  937. if (is_null($this->m_bCheckStatus))
  938. {
  939. $this->m_aCheckIssues = array();
  940. $oKPI = new ExecutionKPI();
  941. $this->DoCheckToWrite();
  942. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  943. if (count($this->m_aCheckIssues) == 0)
  944. {
  945. $this->m_bCheckStatus = true;
  946. }
  947. else
  948. {
  949. $this->m_bCheckStatus = false;
  950. }
  951. }
  952. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  953. }
  954. // check if it is allowed to delete the existing object from the database
  955. // a displayable error is returned
  956. protected function DoCheckToDelete(&$oDeletionPlan)
  957. {
  958. $this->m_aDeleteIssues = array(); // Ok
  959. if ($this->InSyncScope())
  960. {
  961. $oReplicaSet = $this->GetMasterReplica();
  962. if ($oReplicaSet->Count() > 0)
  963. {
  964. while($aData = $oReplicaSet->FetchAssoc())
  965. {
  966. $oDataSource = $aData['datasource'];
  967. $oReplica = $aData['replica'];
  968. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  969. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  970. {
  971. // The current task has the right to delete the object
  972. continue;
  973. }
  974. if ($oReplica->Get('status_dest_creator') != 1)
  975. {
  976. // The object is not owned by the task
  977. continue;
  978. }
  979. $sLink = $oDataSource->GetName();
  980. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  981. switch($sUserDeletePolicy)
  982. {
  983. case 'nobody':
  984. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  985. break;
  986. case 'administrators':
  987. if (!UserRights::IsAdministrator())
  988. {
  989. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  990. }
  991. break;
  992. case 'everybody':
  993. default:
  994. // Ok
  995. break;
  996. }
  997. }
  998. }
  999. }
  1000. }
  1001. final public function CheckToDelete(&$oDeletionPlan)
  1002. {
  1003. $this->MakeDeletionPlan($oDeletionPlan);
  1004. $oDeletionPlan->ComputeResults();
  1005. return (!$oDeletionPlan->FoundStopper());
  1006. }
  1007. protected function ListChangedValues(array $aProposal)
  1008. {
  1009. $aDelta = array();
  1010. foreach ($aProposal as $sAtt => $proposedValue)
  1011. {
  1012. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1013. {
  1014. // The value was not set
  1015. $aDelta[$sAtt] = $proposedValue;
  1016. }
  1017. elseif(is_object($proposedValue))
  1018. {
  1019. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1020. // The value is an object, the comparison is not strict
  1021. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  1022. {
  1023. $aDelta[$sAtt] = $proposedValue;
  1024. }
  1025. }
  1026. else
  1027. {
  1028. // The value is a scalar, the comparison must be 100% strict
  1029. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1030. {
  1031. //echo "$sAtt:<pre>\n";
  1032. //var_dump($this->m_aOrigValues[$sAtt]);
  1033. //var_dump($proposedValue);
  1034. //echo "</pre>\n";
  1035. $aDelta[$sAtt] = $proposedValue;
  1036. }
  1037. }
  1038. }
  1039. return $aDelta;
  1040. }
  1041. // List the attributes that have been changed
  1042. // Returns an array of attname => currentvalue
  1043. public function ListChanges()
  1044. {
  1045. if ($this->m_bIsInDB)
  1046. {
  1047. return $this->ListChangedValues($this->m_aCurrValues);
  1048. }
  1049. else
  1050. {
  1051. return $this->m_aCurrValues;
  1052. }
  1053. }
  1054. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1055. public function IsModified()
  1056. {
  1057. $aChanges = $this->ListChanges();
  1058. return (count($aChanges) != 0);
  1059. }
  1060. public function Equals($oSibling)
  1061. {
  1062. if (get_class($oSibling) != get_class($this))
  1063. {
  1064. return false;
  1065. }
  1066. if ($this->GetKey() != $oSibling->GetKey())
  1067. {
  1068. return false;
  1069. }
  1070. if ($this->m_bIsInDB)
  1071. {
  1072. // If one has changed, then consider them as being different
  1073. if ($this->IsModified() || $oSibling->IsModified())
  1074. {
  1075. return false;
  1076. }
  1077. }
  1078. else
  1079. {
  1080. // Todo - implement this case (loop on every attribute)
  1081. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1082. //{
  1083. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1084. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1085. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1086. //{
  1087. //return false;
  1088. //}
  1089. //}
  1090. return false;
  1091. }
  1092. return true;
  1093. }
  1094. // used both by insert/update
  1095. private function DBWriteLinks()
  1096. {
  1097. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1098. {
  1099. if (!$oAttDef->IsLinkSet()) continue;
  1100. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  1101. if ($oOriginalSet != null)
  1102. {
  1103. $aOriginalList = $oOriginalSet->ToArray();
  1104. }
  1105. else
  1106. {
  1107. $aOriginalList = array();
  1108. }
  1109. $oLinks = $this->Get($sAttCode);
  1110. $oLinks->Rewind();
  1111. while ($oLinkedObject = $oLinks->Fetch())
  1112. {
  1113. if (!array_key_exists($oLinkedObject->GetKey(), $aOriginalList))
  1114. {
  1115. // New object added to the set, make it point properly
  1116. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1117. }
  1118. if ($oLinkedObject->IsModified())
  1119. {
  1120. // Objects can be modified because:
  1121. // 1) They've just been added into the set, so their ExtKey is modified
  1122. // 2) They are about to be removed from the set BUT NOT deleted, their ExtKey has been reset
  1123. $oLinkedObject->DBWrite();
  1124. }
  1125. }
  1126. // Delete the objects that were initialy present and disappeared from the list
  1127. // (if any)
  1128. if (count($aOriginalList) > 0)
  1129. {
  1130. $aNewSet = $oLinks->ToArray();
  1131. foreach($aOriginalList as $iId => $oObject)
  1132. {
  1133. if (!array_key_exists($iId, $aNewSet))
  1134. {
  1135. // It disappeared from the list
  1136. $oObject->DBDelete();
  1137. }
  1138. }
  1139. }
  1140. }
  1141. }
  1142. // Note: this is experimental - it was designed to speed up the setup of iTop
  1143. // Known limitations:
  1144. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1145. // - the id of the object is not updated
  1146. static public final function BulkInsertStart()
  1147. {
  1148. self::$m_bBulkInsert = true;
  1149. }
  1150. static public final function BulkInsertFlush()
  1151. {
  1152. if (!self::$m_bBulkInsert) return;
  1153. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1154. {
  1155. foreach ($aTables as $sTable => $sColumns)
  1156. {
  1157. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1158. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1159. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1160. }
  1161. }
  1162. // Reset
  1163. self::$m_aBulkInsertItems = array();
  1164. self::$m_aBulkInsertCols = array();
  1165. self::$m_bBulkInsert = false;
  1166. }
  1167. private function DBInsertSingleTable($sTableClass)
  1168. {
  1169. $sTable = MetaModel::DBGetTable($sTableClass);
  1170. // Abstract classes or classes having no specific attribute do not have an associated table
  1171. if ($sTable == '') return;
  1172. $sClass = get_class($this);
  1173. // fields in first array, values in the second
  1174. $aFieldsToWrite = array();
  1175. $aValuesToWrite = array();
  1176. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1177. {
  1178. // Add it to the list of fields to write
  1179. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1180. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1181. }
  1182. $aHierarchicalKeys = array();
  1183. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1184. {
  1185. // Skip this attribute if not defined in this table
  1186. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1187. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1188. foreach($aAttColumns as $sColumn => $sValue)
  1189. {
  1190. $aFieldsToWrite[] = "`$sColumn`";
  1191. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1192. }
  1193. if ($oAttDef->IsHierarchicalKey())
  1194. {
  1195. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1196. }
  1197. }
  1198. if (count($aValuesToWrite) == 0) return false;
  1199. if (MetaModel::DBIsReadOnly())
  1200. {
  1201. $iNewKey = -1;
  1202. }
  1203. else
  1204. {
  1205. if (self::$m_bBulkInsert)
  1206. {
  1207. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1208. {
  1209. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1210. }
  1211. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1212. $iNewKey = 999999; // TODO - compute next id....
  1213. }
  1214. else
  1215. {
  1216. if (count($aHierarchicalKeys) > 0)
  1217. {
  1218. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1219. {
  1220. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1221. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1222. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1223. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1224. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1225. }
  1226. }
  1227. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1228. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1229. }
  1230. }
  1231. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1232. if (empty($this->m_iKey))
  1233. {
  1234. // Take the autonumber
  1235. $this->m_iKey = $iNewKey;
  1236. }
  1237. return $this->m_iKey;
  1238. }
  1239. // Insert of record for the new object into the database
  1240. // Returns the key of the newly created object
  1241. public function DBInsertNoReload()
  1242. {
  1243. if ($this->m_bIsInDB)
  1244. {
  1245. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1246. }
  1247. $sClass = get_class($this);
  1248. $sRootClass = MetaModel::GetRootClass($sClass);
  1249. // Ensure the update of the values (we are accessing the data directly)
  1250. $this->DoComputeValues();
  1251. $this->OnInsert();
  1252. if ($this->m_iKey < 0)
  1253. {
  1254. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1255. $this->m_iKey = null;
  1256. }
  1257. // If not automatically computed, then check that the key is given by the caller
  1258. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1259. {
  1260. if (empty($this->m_iKey))
  1261. {
  1262. 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));
  1263. }
  1264. }
  1265. // Ultimate check - ensure DB integrity
  1266. list($bRes, $aIssues) = $this->CheckToWrite();
  1267. if (!$bRes)
  1268. {
  1269. $sIssues = implode(', ', $aIssues);
  1270. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1271. }
  1272. // Stop watches
  1273. $sState = $this->GetState();
  1274. if ($sState != '')
  1275. {
  1276. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1277. {
  1278. if ($oAttDef instanceof AttributeStopWatch)
  1279. {
  1280. if (in_array($sState, $oAttDef->GetStates()))
  1281. {
  1282. // Start the stop watch and compute the deadlines
  1283. $oSW = $this->Get($sAttCode);
  1284. $oSW->Start($this, $oAttDef);
  1285. $oSW->ComputeDeadlines($this, $oAttDef);
  1286. $this->Set($sAttCode, $oSW);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. // First query built upon on the root class, because the ID must be created first
  1292. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1293. // Then do the leaf class, if different from the root class
  1294. if ($sClass != $sRootClass)
  1295. {
  1296. $this->DBInsertSingleTable($sClass);
  1297. }
  1298. // Then do the other classes
  1299. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1300. {
  1301. if ($sParentClass == $sRootClass) continue;
  1302. $this->DBInsertSingleTable($sParentClass);
  1303. }
  1304. $this->DBWriteLinks();
  1305. $this->m_bIsInDB = true;
  1306. $this->m_bDirty = false;
  1307. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  1308. $this->m_aAsArgs = null;
  1309. $this->AfterInsert();
  1310. // Activate any existing trigger
  1311. $sClass = get_class($this);
  1312. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1313. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1314. while ($oTrigger = $oSet->Fetch())
  1315. {
  1316. $oTrigger->DoActivate($this->ToArgs('this'));
  1317. }
  1318. $this->RecordObjCreation();
  1319. return $this->m_iKey;
  1320. }
  1321. protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
  1322. {
  1323. $sTable = MetaModel::DBGetTable($sTableClass);
  1324. // Abstract classes or classes having no specific attribute do not have an associated table
  1325. if ($sTable == '') return;
  1326. $sClass = get_class($this);
  1327. // fields in first array, values in the second
  1328. $aFieldsToWrite = array();
  1329. $aValuesToWrite = array();
  1330. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1331. {
  1332. // Add it to the list of fields to write
  1333. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1334. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1335. }
  1336. $aHierarchicalKeys = array();
  1337. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1338. {
  1339. // Skip this attribute if not defined in this table
  1340. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1341. // Skip link set that can still be undefined though the object is 100% loaded
  1342. if ($oAttDef->IsLinkSet()) continue;
  1343. $value = $this->m_aCurrValues[$sAttCode];
  1344. if ($oAttDef->IsExternalKey())
  1345. {
  1346. $sTargetClass = $oAttDef->GetTargetClass();
  1347. if (is_array($aAuthorizedExtKeys))
  1348. {
  1349. if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
  1350. {
  1351. $value = 0;
  1352. }
  1353. }
  1354. }
  1355. $aAttColumns = $oAttDef->GetSQLValues($value);
  1356. foreach($aAttColumns as $sColumn => $sValue)
  1357. {
  1358. $aFieldsToWrite[] = "`$sColumn`";
  1359. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1360. }
  1361. if ($oAttDef->IsHierarchicalKey())
  1362. {
  1363. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1364. }
  1365. }
  1366. if (count($aValuesToWrite) == 0) return false;
  1367. if (count($aHierarchicalKeys) > 0)
  1368. {
  1369. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1370. {
  1371. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1372. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1373. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1374. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1375. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1376. }
  1377. }
  1378. $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
  1379. }
  1380. public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
  1381. {
  1382. $sClass = get_class($this);
  1383. $sRootClass = MetaModel::GetRootClass($sClass);
  1384. // First query built upon on the root class, because the ID must be created first
  1385. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
  1386. // Then do the leaf class, if different from the root class
  1387. if ($sClass != $sRootClass)
  1388. {
  1389. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
  1390. }
  1391. // Then do the other classes
  1392. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1393. {
  1394. if ($sParentClass == $sRootClass) continue;
  1395. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
  1396. }
  1397. }
  1398. public function DBInsert()
  1399. {
  1400. $this->DBInsertNoReload();
  1401. $this->Reload();
  1402. return $this->m_iKey;
  1403. }
  1404. public function DBInsertTracked(CMDBChange $oChange)
  1405. {
  1406. CMDBObject::SetCurrentChange($oChange);
  1407. return $this->DBInsert();
  1408. }
  1409. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1410. {
  1411. CMDBObject::SetCurrentChange($oChange);
  1412. return $this->DBInsertNoReload();
  1413. }
  1414. // Creates a copy of the current object into the database
  1415. // Returns the id of the newly created object
  1416. public function DBClone($iNewKey = null)
  1417. {
  1418. $this->m_bIsInDB = false;
  1419. $this->m_iKey = $iNewKey;
  1420. $ret = $this->DBInsert();
  1421. $this->RecordObjCreation();
  1422. return $ret;
  1423. }
  1424. /**
  1425. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1426. * The purpose of this method is to reset the appropriate attributes of the object in
  1427. * order to make sure that the newly cloned object is really distinct from its clone
  1428. */
  1429. public function __clone()
  1430. {
  1431. $this->m_bIsInDB = false;
  1432. $this->m_bDirty = true;
  1433. $this->m_iKey = self::GetNextTempId(get_class($this));
  1434. }
  1435. // Update a record
  1436. public function DBUpdate()
  1437. {
  1438. if (!$this->m_bIsInDB)
  1439. {
  1440. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1441. }
  1442. // Stop watches
  1443. $sState = $this->GetState();
  1444. if ($sState != '')
  1445. {
  1446. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1447. {
  1448. if ($oAttDef instanceof AttributeStopWatch)
  1449. {
  1450. if (in_array($sState, $oAttDef->GetStates()))
  1451. {
  1452. // Compute or recompute the deadlines
  1453. $oSW = $this->Get($sAttCode);
  1454. $oSW->ComputeDeadlines($this, $oAttDef);
  1455. $this->Set($sAttCode, $oSW);
  1456. }
  1457. }
  1458. }
  1459. }
  1460. $this->DoComputeValues();
  1461. $this->OnUpdate();
  1462. $aChanges = $this->ListChanges();
  1463. if (count($aChanges) == 0)
  1464. {
  1465. // Attempting to update an unchanged object
  1466. return;
  1467. }
  1468. // Ultimate check - ensure DB integrity
  1469. list($bRes, $aIssues) = $this->CheckToWrite();
  1470. if (!$bRes)
  1471. {
  1472. $sIssues = implode(', ', $aIssues);
  1473. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1474. }
  1475. // Save the original values (will be reset to the new values when the object get written to the DB)
  1476. $aOriginalValues = $this->m_aOrigValues;
  1477. $bHasANewExternalKeyValue = false;
  1478. $aHierarchicalKeys = array();
  1479. foreach($aChanges as $sAttCode => $valuecurr)
  1480. {
  1481. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1482. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1483. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1484. if ($oAttDef->IsHierarchicalKey())
  1485. {
  1486. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1487. }
  1488. }
  1489. if (!MetaModel::DBIsReadOnly())
  1490. {
  1491. // Update the left & right indexes for each hierarchical key
  1492. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1493. {
  1494. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1495. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1496. $aRes = CMDBSource::QueryToArray($sSQL);
  1497. $iMyLeft = $aRes[0]['left'];
  1498. $iMyRight = $aRes[0]['right'];
  1499. $iDelta =$iMyRight - $iMyLeft + 1;
  1500. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1501. if ($aChanges[$sAttCode] == 0)
  1502. {
  1503. // No new parent, insert completely at the right of the tree
  1504. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1505. $aRes = CMDBSource::QueryToArray($sSQL);
  1506. if (count($aRes) == 0)
  1507. {
  1508. $iNewLeft = 1;
  1509. }
  1510. else
  1511. {
  1512. $iNewLeft = $aRes[0]['max']+1;
  1513. }
  1514. }
  1515. else
  1516. {
  1517. // Insert at the right of the specified parent
  1518. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aChanges[$sAttCode]);
  1519. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1520. }
  1521. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1522. $aHKChanges = array();
  1523. $aHKChanges[$sAttCode] = $aChanges[$sAttCode];
  1524. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1525. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1526. $aChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1527. }
  1528. // Update scalar attributes
  1529. if (count($aChanges) != 0)
  1530. {
  1531. $oFilter = new DBObjectSearch(get_class($this));
  1532. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1533. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1534. CMDBSource::Query($sSQL);
  1535. }
  1536. }
  1537. $this->DBWriteLinks();
  1538. $this->m_bDirty = false;
  1539. $this->AfterUpdate();
  1540. // Reload to get the external attributes
  1541. if ($bHasANewExternalKeyValue)
  1542. {
  1543. $this->Reload();
  1544. }
  1545. else
  1546. {
  1547. // Reset original values although the object has not been reloaded
  1548. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1549. {
  1550. if ($bLoaded)
  1551. {
  1552. $value = $this->m_aCurrValues[$sAttCode];
  1553. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1554. }
  1555. }
  1556. }
  1557. if (count($aChanges) != 0)
  1558. {
  1559. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1560. }
  1561. return $this->m_iKey;
  1562. }
  1563. public function DBUpdateTracked(CMDBChange $oChange)
  1564. {
  1565. CMDBObject::SetCurrentChange($oChange);
  1566. return $this->DBUpdate();
  1567. }
  1568. // Make the current changes persistent - clever wrapper for Insert or Update
  1569. public function DBWrite()
  1570. {
  1571. if ($this->m_bIsInDB)
  1572. {
  1573. return $this->DBUpdate();
  1574. }
  1575. else
  1576. {
  1577. return $this->DBInsert();
  1578. }
  1579. }
  1580. private function DBDeleteSingleTable($sTableClass)
  1581. {
  1582. $sTable = MetaModel::DBGetTable($sTableClass);
  1583. // Abstract classes or classes having no specific attribute do not have an associated table
  1584. if ($sTable == '') return;
  1585. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1586. $sKey = CMDBSource::Quote($this->m_iKey);
  1587. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1588. CMDBSource::DeleteFrom($sDeleteSQL);
  1589. }
  1590. protected function DBDeleteSingleObject()
  1591. {
  1592. if (!MetaModel::DBIsReadOnly())
  1593. {
  1594. $this->OnDelete();
  1595. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1596. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1597. {
  1598. if ($oAttDef->IsHierarchicalKey())
  1599. {
  1600. // Update the left & right indexes for each hierarchical key
  1601. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1602. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1603. $aRes = CMDBSource::QueryToArray($sSQL);
  1604. $iMyLeft = $aRes[0]['left'];
  1605. $iMyRight = $aRes[0]['right'];
  1606. $iDelta =$iMyRight - $iMyLeft + 1;
  1607. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1608. // No new parent for now, insert completely at the right of the tree
  1609. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1610. $aRes = CMDBSource::QueryToArray($sSQL);
  1611. if (count($aRes) == 0)
  1612. {
  1613. $iNewLeft = 1;
  1614. }
  1615. else
  1616. {
  1617. $iNewLeft = $aRes[0]['max']+1;
  1618. }
  1619. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1620. }
  1621. }
  1622. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1623. {
  1624. $this->DBDeleteSingleTable($sParentClass);
  1625. }
  1626. $this->AfterDelete();
  1627. $this->m_bIsInDB = false;
  1628. $this->m_iKey = null;
  1629. }
  1630. }
  1631. // Delete an object... and guarantee data integrity
  1632. //
  1633. public function DBDelete(&$oDeletionPlan = null)
  1634. {
  1635. static $iLoopTimeLimit = null;
  1636. if ($iLoopTimeLimit == null)
  1637. {
  1638. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  1639. }
  1640. if (is_null($oDeletionPlan))
  1641. {
  1642. $oDeletionPlan = new DeletionPlan();
  1643. }
  1644. $this->MakeDeletionPlan($oDeletionPlan);
  1645. $oDeletionPlan->ComputeResults();
  1646. if ($oDeletionPlan->FoundStopper())
  1647. {
  1648. $aIssues = $oDeletionPlan->GetIssues();
  1649. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1650. }
  1651. else
  1652. {
  1653. // Getting and setting time limit are not symetric:
  1654. // www.php.net/manual/fr/function.set-time-limit.php#72305
  1655. $iPreviousTimeLimit = ini_get('max_execution_time');
  1656. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1657. {
  1658. foreach ($aToDelete as $iId => $aData)
  1659. {
  1660. $oToDelete = $aData['to_delete'];
  1661. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1662. // because for each object we would try to update all the preceding ones... that are already deleted
  1663. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1664. // As a temporary fix: delete only the objects that are still to be deleted...
  1665. if ($oToDelete->m_bIsInDB)
  1666. {
  1667. set_time_limit($iLoopTimeLimit);
  1668. $oToDelete->DBDeleteSingleObject();
  1669. }
  1670. }
  1671. }
  1672. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1673. {
  1674. foreach ($aToUpdate as $iId => $aData)
  1675. {
  1676. $oToUpdate = $aData['to_reset'];
  1677. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1678. {
  1679. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1680. set_time_limit($iLoopTimeLimit);
  1681. $oToUpdate->DBUpdate();
  1682. }
  1683. }
  1684. }
  1685. set_time_limit($iPreviousTimeLimit);
  1686. }
  1687. return $oDeletionPlan;
  1688. }
  1689. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1690. {
  1691. CMDBObject::SetCurrentChange($oChange);
  1692. $this->DBDelete($oDeletionPlan);
  1693. }
  1694. public function EnumTransitions()
  1695. {
  1696. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1697. if (empty($sStateAttCode)) return array();
  1698. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1699. return MetaModel::EnumTransitions(get_class($this), $sState);
  1700. }
  1701. /**
  1702. * Designed as an action to be called when a stop watch threshold times out
  1703. * or from within the framework
  1704. */
  1705. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  1706. {
  1707. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1708. if (empty($sStateAttCode)) return false;
  1709. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1710. $aStateTransitions = $this->EnumTransitions();
  1711. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  1712. {
  1713. // This simulus has no effect in the current state... do nothing
  1714. return;
  1715. }
  1716. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1717. // Change the state before proceeding to the actions, this is necessary because an action might
  1718. // trigger another stimuli (alternative: push the stimuli into a queue)
  1719. $sPreviousState = $this->Get($sStateAttCode);
  1720. $sNewState = $aTransitionDef['target_state'];
  1721. $this->Set($sStateAttCode, $sNewState);
  1722. // $aTransitionDef is an
  1723. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1724. $bSuccess = true;
  1725. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1726. {
  1727. // std PHP spec
  1728. $aActionCallSpec = array($this, $sActionHandler);
  1729. if (!is_callable($aActionCallSpec))
  1730. {
  1731. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1732. return;
  1733. }
  1734. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1735. // if one call fails, the whole is considered as failed
  1736. if (!$bRet) $bSuccess = false;
  1737. }
  1738. if ($bSuccess)
  1739. {
  1740. $sClass = get_class($this);
  1741. // Stop watches
  1742. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1743. {
  1744. if ($oAttDef instanceof AttributeStopWatch)
  1745. {
  1746. $oSW = $this->Get($sAttCode);
  1747. if (in_array($sNewState, $oAttDef->GetStates()))
  1748. {
  1749. $oSW->Start($this, $oAttDef);
  1750. }
  1751. else
  1752. {
  1753. $oSW->Stop($this, $oAttDef);
  1754. }
  1755. $this->Set($sAttCode, $oSW);
  1756. }
  1757. }
  1758. if (!$bDoNotWrite)
  1759. {
  1760. $this->DBWrite();
  1761. }
  1762. // Change state triggers...
  1763. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1764. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1765. while ($oTrigger = $oSet->Fetch())
  1766. {
  1767. $oTrigger->DoActivate($this->ToArgs('this'));
  1768. }
  1769. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1770. while ($oTrigger = $oSet->Fetch())
  1771. {
  1772. $oTrigger->DoActivate($this->ToArgs('this'));
  1773. }
  1774. }
  1775. return $bSuccess;
  1776. }
  1777. /**
  1778. * Designed as an action to be called when a stop watch threshold times out
  1779. */
  1780. public function ResetStopWatch($sAttCode)
  1781. {
  1782. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1783. if (!$oAttDef instanceof AttributeStopWatch)
  1784. {
  1785. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  1786. }
  1787. $oSW = $this->Get($sAttCode);
  1788. $oSW->Reset($this, $oAttDef);
  1789. $this->Set($sAttCode, $oSW);
  1790. }
  1791. /*
  1792. * Create query parameters (SELECT ... WHERE service = :this->service_id)
  1793. * to be used with the APIs DBObjectSearch/DBObjectSet
  1794. *
  1795. * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
  1796. * in VariableExpression::Render()
  1797. */
  1798. public function ToArgsForQuery($sArgName = 'this')
  1799. {
  1800. return array($sArgName.'->object()' => $this);
  1801. }
  1802. /*
  1803. * Create template placeholders
  1804. * An improvement could be to compute the values on demand
  1805. * (i.e. interpret the template to determine the placeholders)
  1806. */
  1807. public function ToArgs($sArgName = 'this')
  1808. {
  1809. if (is_null($this->m_aAsArgs))
  1810. {
  1811. $oKPI = new ExecutionKPI();
  1812. $aScalarArgs = $this->ToArgsForQuery($sArgName);
  1813. $aScalarArgs[$sArgName] = $this->GetKey();
  1814. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1815. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink('iTopStandardURLMaker', false);
  1816. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = $this->GetHyperlink('PortalURLMaker', false);
  1817. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1818. $sClass = get_class($this);
  1819. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1820. {
  1821. if ($oAttDef instanceof AttributeCaseLog)
  1822. {
  1823. $oCaseLog = $this->Get($sAttCode);
  1824. $aScalarArgs[$sArgName.'->'.$sAttCode] = $oCaseLog->GetText();
  1825. $aScalarArgs[$sArgName.'->head('.$sAttCode.')'] = $oCaseLog->GetLatestEntry();
  1826. }
  1827. elseif ($oAttDef->IsScalar())
  1828. {
  1829. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1830. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1831. $sAsHtml = $this->GetAsHtml($sAttCode);
  1832. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1833. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = $this->GetEditValue($sAttCode); // "Nice" display value, but without HTML tags and entities
  1834. }
  1835. elseif ($oAttDef->IsLinkSet())
  1836. {
  1837. $sRemoteName = $oAttDef->IsIndirect() ? $oAttDef->GetExtKeyToRemote().'_friendlyname' : 'friendlyname';
  1838. $oLinkSet = clone $this->Get($sAttCode); // Workaround/Safety net for Trac #887
  1839. $iLimit = MetaModel::GetConfig()->Get('max_linkset_output');
  1840. if ($iLimit > 0)
  1841. {
  1842. $oLinkSet->SetLimit($iLimit);
  1843. }
  1844. $aNames = $oLinkSet->GetColumnAsArray($sRemoteName);
  1845. if ($iLimit > 0)
  1846. {
  1847. $iTotal = $oLinkSet->Count();
  1848. if ($iTotal > count($aNames))
  1849. {
  1850. $aNames[] = '... '.Dict::Format('UI:TruncatedResults', count($aNames), $iTotal);
  1851. }
  1852. }
  1853. $sNames = implode("\n", $aNames);
  1854. $aScalarArgs[$sArgName.'->'.$sAttCode] = $sNames;
  1855. }
  1856. }
  1857. $this->m_aAsArgs = $aScalarArgs;
  1858. $oKPI->ComputeStats('ToArgs', get_class($this));
  1859. }
  1860. return $this->m_aAsArgs;
  1861. }
  1862. // To be optionaly overloaded
  1863. protected function OnInsert()
  1864. {
  1865. }
  1866. // To be optionaly overloaded
  1867. protected function AfterInsert()
  1868. {
  1869. }
  1870. // To be optionaly overloaded
  1871. protected function OnUpdate()
  1872. {
  1873. }
  1874. // To be optionaly overloaded
  1875. protected function AfterUpdate()
  1876. {
  1877. }
  1878. // To be optionaly overloaded
  1879. protected function OnDelete()
  1880. {
  1881. }
  1882. // To be optionaly overloaded
  1883. protected function AfterDelete()
  1884. {
  1885. }
  1886. /**
  1887. * Common to the recording of link set changes (add/remove/modify)
  1888. */
  1889. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  1890. {
  1891. if ($iLinkSetOwnerId <= 0)
  1892. {
  1893. return null;
  1894. }
  1895. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  1896. {
  1897. // The link set owner class does not keep track of its history
  1898. return null;
  1899. }
  1900. // Determine the linked item class and id
  1901. //
  1902. if ($oLinkSet->IsIndirect())
  1903. {
  1904. // The "item" is on the other end (N-N links)
  1905. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  1906. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  1907. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  1908. if ($aOriginalValues)
  1909. {
  1910. // Get the value from the original values
  1911. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  1912. }
  1913. else
  1914. {
  1915. $iItemId = $this->Get($sExtKeyToRemote);
  1916. }
  1917. }
  1918. else
  1919. {
  1920. // I am the "item" (1-N links)
  1921. $sItemClass = get_class($this);
  1922. $iItemId = $this->GetKey();
  1923. }
  1924. // Get the remote object, to determine its exact class
  1925. // 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!
  1926. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  1927. if ($oOwner)
  1928. {
  1929. $sLinkSetOwnerClass = get_class($oOwner);
  1930. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  1931. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  1932. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  1933. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  1934. $oMyChangeOp->Set("item_class", $sItemClass);
  1935. $oMyChangeOp->Set("item_id", $iItemId);
  1936. return $oMyChangeOp;
  1937. }
  1938. else
  1939. {
  1940. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  1941. return null;
  1942. }
  1943. }
  1944. /**
  1945. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  1946. */
  1947. private function RecordLinkSetListChange($bAdd = true)
  1948. {
  1949. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1950. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1951. {
  1952. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1953. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  1954. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  1955. if ($oMyChangeOp)
  1956. {
  1957. if ($bAdd)
  1958. {
  1959. $oMyChangeOp->Set("type", "added");
  1960. }
  1961. else
  1962. {
  1963. $oMyChangeOp->Set("type", "removed");
  1964. }
  1965. $iId = $oMyChangeOp->DBInsertNoReload();
  1966. }
  1967. }
  1968. }
  1969. protected function RecordObjCreation()
  1970. {
  1971. $this->RecordLinkSetListChange(true);
  1972. }
  1973. protected function RecordObjDeletion($objkey)
  1974. {
  1975. $this->RecordLinkSetListChange(false);
  1976. }
  1977. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  1978. {
  1979. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1980. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1981. {
  1982. if (array_key_exists($sExtKeyAttCode, $aValues))
  1983. {
  1984. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1985. // Keep track of link added/removed
  1986. //
  1987. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  1988. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  1989. if ($oMyChangeOp)
  1990. {
  1991. $oMyChangeOp->Set("type", "added");
  1992. $oMyChangeOp->DBInsertNoReload();
  1993. }
  1994. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  1995. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  1996. if ($oMyChangeOp)
  1997. {
  1998. $oMyChangeOp->Set("type", "removed");
  1999. $oMyChangeOp->DBInsertNoReload();
  2000. }
  2001. }
  2002. else
  2003. {
  2004. // Keep track of link changes
  2005. //
  2006. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  2007. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2008. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  2009. if ($oMyChangeOp)
  2010. {
  2011. $oMyChangeOp->Set("link_id", $this->GetKey());
  2012. $iId = $oMyChangeOp->DBInsertNoReload();
  2013. }
  2014. }
  2015. }
  2016. }
  2017. // Return an empty set for the parent of all
  2018. public static function GetRelationQueries($sRelCode)
  2019. {
  2020. return array();
  2021. }
  2022. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  2023. {
  2024. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  2025. {
  2026. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  2027. $sQuery = $aQueryInfo["sQuery"];
  2028. $bPropagate = $aQueryInfo["bPropagate"];
  2029. $iDistance = $aQueryInfo["iDistance"];
  2030. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  2031. $oFlt = DBObjectSearch::FromOQL($sQuery);
  2032. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgsForQuery());
  2033. while ($oObj = $oObjSet->Fetch())
  2034. {
  2035. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  2036. $sObjKey = $oObj->GetKey();
  2037. if (array_key_exists($sRootClass, $aResults))
  2038. {
  2039. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  2040. {
  2041. continue; // already visited, skip
  2042. }
  2043. }
  2044. $aResults[$sRootClass][$sObjKey] = $oObj;
  2045. if ($iDepth > 0)
  2046. {
  2047. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  2048. }
  2049. }
  2050. }
  2051. return $aResults;
  2052. }
  2053. public function GetReferencingObjects($bAllowAllData = false)
  2054. {
  2055. $aDependentObjects = array();
  2056. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  2057. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  2058. {
  2059. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  2060. {
  2061. // skip if this external key is behind an external field
  2062. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  2063. $oSearch = new DBObjectSearch($sRemoteClass);
  2064. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  2065. if ($bAllowAllData)
  2066. {
  2067. $oSearch->AllowAllData();
  2068. }
  2069. $oSet = new CMDBObjectSet($oSearch);
  2070. if ($oSet->Count() > 0)
  2071. {
  2072. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  2073. 'attribute' => $oExtKeyAttDef,
  2074. 'objects' => $oSet,
  2075. );
  2076. }
  2077. }
  2078. }
  2079. return $aDependentObjects;
  2080. }
  2081. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  2082. {
  2083. static $iLoopTimeLimit = null;
  2084. if ($iLoopTimeLimit == null)
  2085. {
  2086. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2087. }
  2088. $sClass = get_class($this);
  2089. $iThisId = $this->GetKey();
  2090. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  2091. if (array_key_exists($sClass, $aVisited))
  2092. {
  2093. if (in_array($iThisId, $aVisited[$sClass]))
  2094. {
  2095. return;
  2096. }
  2097. }
  2098. $aVisited[$sClass] = $iThisId;
  2099. if ($iDeleteOption == DEL_MANUAL)
  2100. {
  2101. // Stop the recursion here
  2102. return;
  2103. }
  2104. // Check the node itself
  2105. $this->DoCheckToDelete($oDeletionPlan);
  2106. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  2107. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  2108. // Getting and setting time limit are not symetric:
  2109. // www.php.net/manual/fr/function.set-time-limit.php#72305
  2110. $iPreviousTimeLimit = ini_get('max_execution_time');
  2111. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  2112. {
  2113. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  2114. {
  2115. set_time_limit($iLoopTimeLimit);
  2116. $oAttDef = $aData['attribute'];
  2117. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  2118. $oDepSet = $aData['objects'];
  2119. $oDepSet->Rewind();
  2120. while ($oDependentObj = $oDepSet->fetch())
  2121. {
  2122. $iId = $oDependentObj->GetKey();
  2123. if ($oAttDef->IsNullAllowed())
  2124. {
  2125. // Optional external key, list to reset
  2126. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  2127. {
  2128. // Move the child up one level i.e. set the same parent as the current object
  2129. $iParentId = $this->Get($oAttDef->GetCode());
  2130. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  2131. }
  2132. else
  2133. {
  2134. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  2135. }
  2136. }
  2137. else
  2138. {
  2139. // Mandatory external key, list to delete
  2140. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  2141. }
  2142. }
  2143. }
  2144. }
  2145. set_time_limit($iPreviousTimeLimit);
  2146. }
  2147. /**
  2148. * Get all the synchro replica related to this object
  2149. * @param none
  2150. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  2151. */
  2152. public function GetMasterReplica()
  2153. {
  2154. if ($this->m_oMasterReplicaSet == null)
  2155. {
  2156. //$aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  2157. //$sClassesList = "'".implode("','", $aParentClasses)."'";
  2158. $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";
  2159. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2160. $this->m_oMasterReplicaSet = $oReplicaSet;
  2161. }
  2162. else
  2163. {
  2164. $this->m_oMasterReplicaSet->Rewind();
  2165. }
  2166. return $this->m_oMasterReplicaSet;
  2167. }
  2168. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2169. {
  2170. $iFlags = OPT_ATT_NORMAL;
  2171. $oSet = $this->GetMasterReplica();
  2172. while($aData = $oSet->FetchAssoc())
  2173. {
  2174. if ($aData['datasource']->GetKey() == SynchroExecution::GetCurrentTaskId())
  2175. {
  2176. // Ignore the current task (check to write => ok)
  2177. continue;
  2178. }
  2179. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2180. $oReplica = $aData['replica'];
  2181. $oSource = $aData['datasource'];
  2182. $oAttrSet = $oSource->Get('attribute_list');
  2183. while($oSyncAttr = $oAttrSet->Fetch())
  2184. {
  2185. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2186. {
  2187. $iFlags |= OPT_ATT_SLAVE;
  2188. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2189. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2190. }
  2191. }
  2192. }
  2193. return $iFlags;
  2194. }
  2195. public function InSyncScope()
  2196. {
  2197. return true;
  2198. // TODO - FINALIZE THIS OPTIMIZATION
  2199. //
  2200. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2201. //
  2202. static $aSynchroClasses = null;
  2203. if (is_null($aSynchroClasses))
  2204. {
  2205. $aSynchroClasses = array();
  2206. $sOQL = "SELECT SynchroDataSource AS datasource";
  2207. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2208. while($oSource = $oSourceSet->Fetch())
  2209. {
  2210. $sTarget = $oSource->Get('scope_class');
  2211. $aSynchroClasses[] = $oSource;
  2212. }
  2213. }
  2214. // to be continued...
  2215. }
  2216. }
  2217. ?>