dbobject.class.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Class dbObject: the root of persistent classes
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once('metamodel.class.php');
  25. /**
  26. * A persistent object, as defined by the metamodel
  27. *
  28. * @package iTopORM
  29. */
  30. abstract class DBObject
  31. {
  32. private static $m_aMemoryObjectsByClass = array();
  33. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  34. private $m_iKey = null;
  35. private $m_aCurrValues = array();
  36. protected $m_aOrigValues = array();
  37. protected $m_aExtendedData = null;
  38. private $m_bDirty = false; // Means: "a modification is ongoing"
  39. // The object may have incorrect external keys, then any attempt of reload must be avoided
  40. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  41. // if null, then the check has to be performed again to know the status
  42. protected $m_aCheckIssues = null;
  43. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  44. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  45. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  46. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  47. public function __construct($aRow = null, $sClassAlias = '', $aExtendedDataSpec = null)
  48. {
  49. if (!empty($aRow))
  50. {
  51. $this->FromRow($aRow, $sClassAlias, $aExtendedDataSpec);
  52. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  53. return;
  54. }
  55. // Creation of brand new object
  56. //
  57. $this->m_iKey = self::GetNextTempId(get_class($this));
  58. // set default values
  59. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  60. {
  61. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  62. $this->m_aOrigValues[$sAttCode] = null;
  63. if ($oAttDef->IsExternalField())
  64. {
  65. // This field has to be read from the DB
  66. $this->m_aLoadedAtt[$sAttCode] = false;
  67. }
  68. else
  69. {
  70. // No need to trigger a reload for that attribute
  71. // Let's consider it as being already fully loaded
  72. $this->m_aLoadedAtt[$sAttCode] = true;
  73. }
  74. }
  75. }
  76. // Read-only <=> Written once (archive)
  77. public function RegisterAsDirty()
  78. {
  79. // While the object may be written to the DB, it is NOT possible to reload it
  80. // or at least not possible to reload it the same way
  81. $this->m_bDirty = true;
  82. }
  83. public function IsNew()
  84. {
  85. return (!$this->m_bIsInDB);
  86. }
  87. // Returns an Id for memory objects
  88. static protected function GetNextTempId($sClass)
  89. {
  90. if (!array_key_exists($sClass, self::$m_aMemoryObjectsByClass))
  91. {
  92. self::$m_aMemoryObjectsByClass[$sClass] = 0;
  93. }
  94. self::$m_aMemoryObjectsByClass[$sClass]++;
  95. return (- self::$m_aMemoryObjectsByClass[$sClass]);
  96. }
  97. public function __toString()
  98. {
  99. $sRet = '';
  100. $sClass = get_class($this);
  101. $sRootClass = MetaModel::GetRootClass($sClass);
  102. $iPKey = $this->GetKey();
  103. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  104. $sRet .= "<ul class=\"treeview\">\n";
  105. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  106. {
  107. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  108. }
  109. $sRet .= "</ul>";
  110. return $sRet;
  111. }
  112. // Restore initial values... mmmm, to be discussed
  113. public function DBRevert()
  114. {
  115. $this->Reload();
  116. }
  117. protected function IsFullyLoaded()
  118. {
  119. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  120. {
  121. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  122. if ($bIsLoaded !== true)
  123. {
  124. return false;
  125. }
  126. }
  127. return true;
  128. }
  129. protected function Reload()
  130. {
  131. assert($this->m_bIsInDB);
  132. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey);
  133. if (empty($aRow))
  134. {
  135. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  136. }
  137. $this->FromRow($aRow);
  138. // Process linked set attributes
  139. //
  140. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  141. {
  142. if (!$oAttDef->IsLinkSet()) continue;
  143. // Load the link information
  144. $sLinkClass = $oAttDef->GetLinkedClass();
  145. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  146. // The class to target is not the current class, because if this is a derived class,
  147. // it may differ from the target class, then things start to become confusing
  148. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  149. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  150. $oMyselfSearch = new DBObjectSearch($sMyClass);
  151. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  152. $oLinkSearch = new DBObjectSearch($sLinkClass);
  153. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  154. $oLinks = new DBObjectSet($oLinkSearch);
  155. $this->m_aCurrValues[$sAttCode] = $oLinks;
  156. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  157. $this->m_aLoadedAtt[$sAttCode] = true;
  158. }
  159. $this->m_bFullyLoaded = true;
  160. }
  161. protected function FromRow($aRow, $sClassAlias = '', $aExtendedDataSpec = null)
  162. {
  163. if (strlen($sClassAlias) == 0)
  164. {
  165. // Default to the current class
  166. $sClassAlias = get_class($this);
  167. }
  168. $this->m_iKey = null;
  169. $this->m_bIsInDB = true;
  170. $this->m_aCurrValues = array();
  171. $this->m_aOrigValues = array();
  172. $this->m_aLoadedAtt = array();
  173. $this->m_bCheckStatus = true;
  174. // Get the key
  175. //
  176. $sKeyField = $sClassAlias."id";
  177. if (!array_key_exists($sKeyField, $aRow))
  178. {
  179. // #@# Bug ?
  180. throw new CoreException("Missing key for class '".get_class($this)."'");
  181. }
  182. else
  183. {
  184. $iPKey = $aRow[$sKeyField];
  185. if (!self::IsValidPKey($iPKey))
  186. {
  187. throw new CoreWarning("An object id must be an integer value ($iPKey)");
  188. }
  189. $this->m_iKey = $iPKey;
  190. }
  191. // Build the object from an array of "attCode"=>"value")
  192. //
  193. $bFullyLoaded = true; // ... set to false if any attribute is not found
  194. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  195. {
  196. // Say something, whatever the type of attribute
  197. $this->m_aLoadedAtt[$sAttCode] = false;
  198. // Skip links (could not be loaded by the mean of this query)
  199. if ($oAttDef->IsLinkSet()) continue;
  200. // Note: we assume that, for a given attribute, if it can be loaded,
  201. // then one column will be found with an empty suffix, the others have a suffix
  202. // Take care: the function isset will return false in case the value is null,
  203. // which is something that could happen on open joins
  204. $sAttRef = $sClassAlias.$sAttCode;
  205. if (array_key_exists($sAttRef, $aRow))
  206. {
  207. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  208. $this->m_aCurrValues[$sAttCode] = $value;
  209. $this->m_aOrigValues[$sAttCode] = $value;
  210. $this->m_aLoadedAtt[$sAttCode] = true;
  211. }
  212. else
  213. {
  214. // This attribute was expected and not found in the query columns
  215. $bFullyLoaded = false;
  216. }
  217. }
  218. // Load extended data
  219. if ($aExtendedDataSpec != null)
  220. {
  221. $aExtendedDataSpec['table'];
  222. foreach($aExtendedDataSpec['fields'] as $sColumn)
  223. {
  224. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  225. if (array_key_exists($sColRef, $aRow))
  226. {
  227. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  228. }
  229. }
  230. }
  231. return $bFullyLoaded;
  232. }
  233. public function Set($sAttCode, $value)
  234. {
  235. if ($sAttCode == 'finalclass')
  236. {
  237. // Ignore it - this attribute is set upon object creation and that's it
  238. return;
  239. }
  240. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  241. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  242. {
  243. // First time Set is called... ensure that the object gets fully loaded
  244. // Otherwise we would lose the values on a further Reload
  245. // + consistency does not make sense !
  246. $this->Reload();
  247. }
  248. if ($oAttDef->IsExternalKey() && is_object($value))
  249. {
  250. // Setting an external key with a whole object (instead of just an ID)
  251. // let's initialize also the external fields that depend on it
  252. // (useful when building objects in memory and not from a query)
  253. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  254. {
  255. 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");
  256. }
  257. else
  258. {
  259. // The object has changed, reset caches
  260. $this->m_bCheckStatus = null;
  261. $this->m_aAsArgs = null;
  262. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  263. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  264. {
  265. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  266. {
  267. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  268. }
  269. }
  270. }
  271. return;
  272. }
  273. if(!$oAttDef->IsScalar() && !is_object($value))
  274. {
  275. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  276. }
  277. if($oAttDef->IsLinkSet())
  278. {
  279. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  280. {
  281. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  282. }
  283. $oObjectSet = $value;
  284. $sSetClass = $oObjectSet->GetClass();
  285. $sLinkClass = $oAttDef->GetLinkedClass();
  286. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  287. if ($sSetClass != $sLinkClass)
  288. {
  289. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  290. }
  291. }
  292. $realvalue = $oAttDef->MakeRealValue($value);
  293. $this->m_aCurrValues[$sAttCode] = $realvalue;
  294. // The object has changed, reset caches
  295. $this->m_bCheckStatus = null;
  296. $this->m_aAsArgs = null;
  297. // Make sure we do not reload it anymore... before saving it
  298. $this->RegisterAsDirty();
  299. }
  300. public function Get($sAttCode)
  301. {
  302. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  303. {
  304. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  305. }
  306. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  307. {
  308. // #@# non-scalar attributes.... handle that differently
  309. $this->Reload();
  310. }
  311. return $this->m_aCurrValues[$sAttCode];
  312. }
  313. public function GetOriginal($sAttCode)
  314. {
  315. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  316. {
  317. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  318. }
  319. return $this->m_aOrigValues[$sAttCode];
  320. }
  321. /**
  322. * Returns data loaded by the mean of a dynamic and explicit JOIN
  323. */
  324. public function GetExtendedData()
  325. {
  326. return $this->m_aExtendedData;
  327. }
  328. /**
  329. * Updates the value of an external field by (re)loading the object
  330. * corresponding to the external key and getting the value from it
  331. * @param string $sAttCode Attribute code of the external field to update
  332. * @return void
  333. */
  334. protected function UpdateExternalField($sAttCode)
  335. {
  336. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  337. if ($oAttDef->IsExternalField())
  338. {
  339. $sTargetClass = $oAttDef->GetTargetClass();
  340. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  341. $oObj = MetaModel::GetObject($sTargetClass, $objkey);
  342. if (is_object($oObj))
  343. {
  344. $value = $oObj->Get($oAttDef->GetExtAttCode());
  345. $this->Set($sAttCode, $value);
  346. }
  347. }
  348. }
  349. // Compute scalar attributes that depend on any other type of attribute
  350. public function DoComputeValues()
  351. {
  352. if (is_callable(array($this, 'ComputeValues')))
  353. {
  354. // First check that we are not currently computing the fields
  355. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  356. foreach (debug_backtrace() as $aCallInfo)
  357. {
  358. if (!array_key_exists("class", $aCallInfo)) continue;
  359. if ($aCallInfo["class"] != get_class($this)) continue;
  360. if ($aCallInfo["function"] != "ComputeValues") continue;
  361. return; //skip!
  362. }
  363. $this->ComputeValues();
  364. }
  365. }
  366. public function GetAsHTML($sAttCode)
  367. {
  368. $sClass = get_class($this);
  369. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  370. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  371. {
  372. //return $this->Get($sAttCode.'_friendlyname');
  373. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  374. $iTargetKey = $this->Get($sAttCode);
  375. $sLabel = $this->Get($sAttCode.'_friendlyname');
  376. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  377. }
  378. // That's a standard attribute (might be an ext field or a direct field, etc.)
  379. return $oAtt->GetAsHTML($this->Get($sAttCode));
  380. }
  381. public function GetEditValue($sAttCode)
  382. {
  383. $sClass = get_class($this);
  384. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  385. if ($oAtt->IsExternalKey())
  386. {
  387. $sTargetClass = $oAtt->GetTargetClass();
  388. if ($this->IsNew())
  389. {
  390. // The current object exists only in memory, don't try to query it in the DB !
  391. // instead let's query for the object pointed by the external key, and get its name
  392. $targetObjId = $this->Get($sAttCode);
  393. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  394. if (is_object($oTargetObj))
  395. {
  396. $sEditValue = $oTargetObj->GetName();
  397. }
  398. else
  399. {
  400. $sEditValue = 0;
  401. }
  402. }
  403. else
  404. {
  405. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  406. }
  407. }
  408. else
  409. {
  410. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  411. }
  412. return $sEditValue;
  413. }
  414. public function GetAsXML($sAttCode)
  415. {
  416. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  417. return $oAtt->GetAsXML($this->Get($sAttCode));
  418. }
  419. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  420. {
  421. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  422. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  423. }
  424. protected static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '')
  425. {
  426. if ($sObjKey == 0) return '<em>undefined</em>';
  427. return MetaModel::GetName($sObjClass)."::$sObjKey";
  428. }
  429. public function GetHyperlink()
  430. {
  431. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName());
  432. }
  433. // could be in the metamodel ?
  434. public static function IsValidPKey($value)
  435. {
  436. return ((string)$value === (string)(int)$value);
  437. }
  438. public function GetKey()
  439. {
  440. return $this->m_iKey;
  441. }
  442. public function SetKey($iNewKey)
  443. {
  444. if (!self::IsValidPKey($iNewKey))
  445. {
  446. throw new CoreException("An object id must be an integer value ($iNewKey)");
  447. }
  448. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  449. {
  450. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  451. }
  452. $this->m_iKey = $iNewKey;
  453. }
  454. /**
  455. * Get the icon representing this object
  456. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  457. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  458. */
  459. public function GetIcon($bImgTag = true)
  460. {
  461. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  462. }
  463. public function GetName()
  464. {
  465. $aNameSpec = MetaModel::GetNameSpec(get_class($this));
  466. $sFormat = $aNameSpec[0];
  467. $aAttributes = $aNameSpec[1];
  468. $aValues = array();
  469. foreach ($aAttributes as $sAttCode)
  470. {
  471. if (empty($sAttCode))
  472. {
  473. $aValues[] = $this->m_iKey;
  474. }
  475. else
  476. {
  477. $aValues[] = $this->Get($sAttCode);
  478. }
  479. }
  480. return vsprintf($sFormat, $aValues);
  481. }
  482. public function GetState()
  483. {
  484. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  485. if (empty($sStateAttCode))
  486. {
  487. return '';
  488. }
  489. else
  490. {
  491. return $this->Get($sStateAttCode);
  492. }
  493. }
  494. public function GetStateLabel()
  495. {
  496. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  497. if (empty($sStateAttCode))
  498. {
  499. return '';
  500. }
  501. else
  502. {
  503. $sStateValue = $this->Get($sStateAttCode);
  504. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  505. }
  506. }
  507. public function GetStateDescription()
  508. {
  509. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  510. if (empty($sStateAttCode))
  511. {
  512. return '';
  513. }
  514. else
  515. {
  516. $sStateValue = $this->Get($sStateAttCode);
  517. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  518. }
  519. }
  520. /**
  521. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  522. * for the given attribute in the current state of the object
  523. * @param string $sAttCode The code of the attribute
  524. * @return integer Flags: the binary combination of the flags applicable to this attribute
  525. */
  526. public function GetAttributeFlags($sAttCode)
  527. {
  528. $iFlags = 0; // By default (if no life cycle) no flag at all
  529. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  530. if (!empty($sStateAttCode))
  531. {
  532. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  533. }
  534. return $iFlags;
  535. }
  536. // check if the given (or current) value is suitable for the attribute
  537. // return true if successfull
  538. // return the error desciption otherwise
  539. public function CheckValue($sAttCode, $value = null)
  540. {
  541. if (!is_null($value))
  542. {
  543. $toCheck = $value;
  544. }
  545. else
  546. {
  547. $toCheck = $this->Get($sAttCode);
  548. }
  549. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  550. if (!$oAtt->IsWritable())
  551. {
  552. return true;
  553. }
  554. elseif ($oAtt->IsNull($toCheck))
  555. {
  556. if ($oAtt->IsNullAllowed())
  557. {
  558. return true;
  559. }
  560. else
  561. {
  562. return "Null not allowed";
  563. }
  564. }
  565. elseif ($oAtt->IsExternalKey())
  566. {
  567. if (!MetaModel::SkipCheckExtKeys())
  568. {
  569. $sTargetClass = $oAtt->GetTargetClass();
  570. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  571. if (is_null($oTargetObj))
  572. {
  573. return "Target object not found ($sTargetClass::$toCheck)";
  574. }
  575. }
  576. }
  577. elseif ($oAtt->IsScalar())
  578. {
  579. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  580. if (count($aValues) > 0)
  581. {
  582. if (!array_key_exists($toCheck, $aValues))
  583. {
  584. return "Value not allowed [$toCheck]";
  585. }
  586. }
  587. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  588. {
  589. $iLen = strlen($toCheck);
  590. if ($iLen > $iMaxSize)
  591. {
  592. return "String too long (found $iLen, limited to $iMaxSize)";
  593. }
  594. }
  595. if (!$oAtt->CheckFormat($toCheck))
  596. {
  597. return "Wrong format [$toCheck]";
  598. }
  599. }
  600. return true;
  601. }
  602. // check attributes together
  603. public function CheckConsistency()
  604. {
  605. return true;
  606. }
  607. // check integrity rules (before inserting or updating the object)
  608. // a displayable error is returned
  609. public function DoCheckToWrite()
  610. {
  611. $this->DoComputeValues();
  612. $this->m_aCheckIssues = array();
  613. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  614. {
  615. $res = $this->CheckValue($sAttCode);
  616. if ($res !== true)
  617. {
  618. // $res contains the error description
  619. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  620. }
  621. }
  622. if (count($this->m_aCheckIssues) > 0)
  623. {
  624. // No need to check consistency between attributes if any of them has
  625. // an unexpected value
  626. return;
  627. }
  628. $res = $this->CheckConsistency();
  629. if ($res !== true)
  630. {
  631. // $res contains the error description
  632. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  633. }
  634. }
  635. final public function CheckToWrite()
  636. {
  637. if (MetaModel::SkipCheckToWrite())
  638. {
  639. return array(true, array());
  640. }
  641. if (is_null($this->m_bCheckStatus))
  642. {
  643. $oKPI = new ExecutionKPI();
  644. $this->DoCheckToWrite();
  645. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  646. if (count($this->m_aCheckIssues) == 0)
  647. {
  648. $this->m_bCheckStatus = true;
  649. }
  650. else
  651. {
  652. $this->m_bCheckStatus = false;
  653. }
  654. }
  655. return array($this->m_bCheckStatus, $this->m_aCheckIssues);
  656. }
  657. // check if it is allowed to delete the existing object from the database
  658. // a displayable error is returned
  659. public function CheckToDelete()
  660. {
  661. return true;
  662. }
  663. protected function ListChangedValues(array $aProposal)
  664. {
  665. $aDelta = array();
  666. foreach ($aProposal as $sAtt => $proposedValue)
  667. {
  668. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  669. {
  670. // The value was not set
  671. $aDelta[$sAtt] = $proposedValue;
  672. }
  673. elseif(is_object($proposedValue))
  674. {
  675. // The value is an object, the comparison is not strict
  676. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  677. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  678. {
  679. $aDelta[$sAtt] = $proposedValue;
  680. }
  681. }
  682. else
  683. {
  684. // The value is a scalar, the comparison must be 100% strict
  685. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  686. {
  687. //echo "$sAtt:<pre>\n";
  688. //var_dump($this->m_aOrigValues[$sAtt]);
  689. //var_dump($proposedValue);
  690. //echo "</pre>\n";
  691. $aDelta[$sAtt] = $proposedValue;
  692. }
  693. }
  694. }
  695. return $aDelta;
  696. }
  697. // List the attributes that have been changed
  698. // Returns an array of attname => currentvalue
  699. public function ListChanges()
  700. {
  701. return $this->ListChangedValues($this->m_aCurrValues);
  702. }
  703. // Tells whether or not an object was modified
  704. public function IsModified()
  705. {
  706. $aChanges = $this->ListChanges();
  707. return (count($aChanges) != 0);
  708. }
  709. // used both by insert/update
  710. private function DBWriteLinks()
  711. {
  712. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  713. {
  714. if (!$oAttDef->IsLinkSet()) continue;
  715. $oLinks = $this->Get($sAttCode);
  716. $oLinks->Rewind();
  717. while ($oLinkedObject = $oLinks->Fetch())
  718. {
  719. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  720. if ($oLinkedObject->IsModified())
  721. {
  722. $oLinkedObject->DBWrite();
  723. }
  724. }
  725. // Delete the objects that were initialy present and disappeared from the list
  726. // (if any)
  727. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  728. if ($oOriginalSet != null)
  729. {
  730. $aOriginalList = $oOriginalSet->ToArray();
  731. $aNewSet = $oLinks->ToArray();
  732. foreach($aOriginalList as $iId => $oObject)
  733. {
  734. if (!array_key_exists($iId, $aNewSet))
  735. {
  736. // It disappeared from the list
  737. $oObject->DBDelete();
  738. }
  739. }
  740. }
  741. }
  742. }
  743. private function DBInsertSingleTable($sTableClass)
  744. {
  745. $sTable = MetaModel::DBGetTable($sTableClass);
  746. // Abstract classes or classes having no specific attribute do not have an associated table
  747. if ($sTable == '') return;
  748. $sClass = get_class($this);
  749. // fields in first array, values in the second
  750. $aFieldsToWrite = array();
  751. $aValuesToWrite = array();
  752. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  753. {
  754. // Add it to the list of fields to write
  755. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  756. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  757. }
  758. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  759. {
  760. // Skip this attribute if not defined in this table
  761. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  762. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  763. foreach($aAttColumns as $sColumn => $sValue)
  764. {
  765. $aFieldsToWrite[] = "`$sColumn`";
  766. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  767. }
  768. }
  769. if (count($aValuesToWrite) == 0) return false;
  770. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  771. if (MetaModel::DBIsReadOnly())
  772. {
  773. $iNewKey = -1;
  774. }
  775. else
  776. {
  777. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  778. }
  779. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  780. if (empty($this->m_iKey))
  781. {
  782. // Take the autonumber
  783. $this->m_iKey = $iNewKey;
  784. }
  785. return $this->m_iKey;
  786. }
  787. // Insert of record for the new object into the database
  788. // Returns the key of the newly created object
  789. public function DBInsertNoReload()
  790. {
  791. if ($this->m_bIsInDB)
  792. {
  793. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  794. }
  795. $sClass = get_class($this);
  796. $sRootClass = MetaModel::GetRootClass($sClass);
  797. // Ensure the update of the values (we are accessing the data directly)
  798. $this->DoComputeValues();
  799. $this->OnInsert();
  800. if ($this->m_iKey < 0)
  801. {
  802. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  803. $this->m_iKey = null;
  804. }
  805. // If not automatically computed, then check that the key is given by the caller
  806. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  807. {
  808. if (empty($this->m_iKey))
  809. {
  810. 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));
  811. }
  812. }
  813. // Ultimate check - ensure DB integrity
  814. list($bRes, $aIssues) = $this->CheckToWrite();
  815. if (!$bRes)
  816. {
  817. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  818. }
  819. // First query built upon on the root class, because the ID must be created first
  820. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  821. // Then do the leaf class, if different from the root class
  822. if ($sClass != $sRootClass)
  823. {
  824. $this->DBInsertSingleTable($sClass);
  825. }
  826. // Then do the other classes
  827. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  828. {
  829. if ($sParentClass == $sRootClass) continue;
  830. $this->DBInsertSingleTable($sParentClass);
  831. }
  832. $this->DBWriteLinks();
  833. $this->m_bIsInDB = true;
  834. $this->m_bDirty = false;
  835. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  836. $this->m_aAsArgs = null;
  837. $this->AfterInsert();
  838. // Activate any existing trigger
  839. $sClass = get_class($this);
  840. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  841. while ($oTrigger = $oSet->Fetch())
  842. {
  843. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  844. {
  845. $oTrigger->DoActivate($this->ToArgs('this'));
  846. }
  847. }
  848. return $this->m_iKey;
  849. }
  850. public function DBInsert()
  851. {
  852. $this->DBInsertNoReload();
  853. $this->Reload();
  854. return $this->m_iKey;
  855. }
  856. public function DBInsertTracked(CMDBChange $oVoid)
  857. {
  858. return $this->DBInsert();
  859. }
  860. // Creates a copy of the current object into the database
  861. // Returns the id of the newly created object
  862. public function DBClone($iNewKey = null)
  863. {
  864. $this->m_bIsInDB = false;
  865. $this->m_iKey = $iNewKey;
  866. return $this->DBInsert();
  867. }
  868. /**
  869. * This function is automatically called after cloning an object with the "clone" PHP language construct
  870. * The purpose of this method is to reset the appropriate attributes of the object in
  871. * order to make sure that the newly cloned object is really distinct from its clone
  872. */
  873. public function __clone()
  874. {
  875. $this->m_bIsInDB = false;
  876. $this->m_bDirty = true;
  877. $this->m_iKey = self::GetNextTempId(get_class($this));
  878. }
  879. // Update a record
  880. public function DBUpdate()
  881. {
  882. if (!$this->m_bIsInDB)
  883. {
  884. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  885. }
  886. $this->DoComputeValues();
  887. $this->OnUpdate();
  888. $aChanges = $this->ListChanges();
  889. if (count($aChanges) == 0)
  890. {
  891. //throw new CoreWarning("Attempting to update an unchanged object");
  892. return;
  893. }
  894. // Ultimate check - ensure DB integrity
  895. list($bRes, $aIssues) = $this->CheckToWrite();
  896. if (!$bRes)
  897. {
  898. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => get_class($this), 'id' => $this->GetKey(), 'issues' => $aIssues));
  899. }
  900. $bHasANewExternalKeyValue = false;
  901. foreach($aChanges as $sAttCode => $valuecurr)
  902. {
  903. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  904. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  905. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  906. }
  907. // Update scalar attributes
  908. if (count($aChanges) != 0)
  909. {
  910. $oFilter = new DBObjectSearch(get_class($this));
  911. $oFilter->AddCondition('id', $this->m_iKey, '=');
  912. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  913. if (!MetaModel::DBIsReadOnly())
  914. {
  915. CMDBSource::Query($sSQL);
  916. }
  917. }
  918. $this->DBWriteLinks();
  919. $this->m_bDirty = false;
  920. $this->AfterUpdate();
  921. // Reload to get the external attributes
  922. if ($bHasANewExternalKeyValue)
  923. {
  924. $this->Reload();
  925. }
  926. return $this->m_iKey;
  927. }
  928. public function DBUpdateTracked(CMDBChange $oVoid)
  929. {
  930. return $this->DBUpdate();
  931. }
  932. // Make the current changes persistent - clever wrapper for Insert or Update
  933. public function DBWrite()
  934. {
  935. if ($this->m_bIsInDB)
  936. {
  937. return $this->DBUpdate();
  938. }
  939. else
  940. {
  941. return $this->DBInsert();
  942. }
  943. }
  944. // Delete a record
  945. public function DBDelete()
  946. {
  947. $oFilter = new DBObjectSearch(get_class($this));
  948. $oFilter->AddCondition('id', $this->m_iKey, '=');
  949. $this->OnDelete();
  950. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  951. if (!MetaModel::DBIsReadOnly())
  952. {
  953. CMDBSource::Query($sSQL);
  954. }
  955. $this->AfterDelete();
  956. $this->m_bIsInDB = false;
  957. $this->m_iKey = null;
  958. }
  959. public function DBDeleteTracked(CMDBChange $oVoid)
  960. {
  961. $this->DBDelete();
  962. }
  963. public function EnumTransitions()
  964. {
  965. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  966. if (empty($sStateAttCode)) return array();
  967. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  968. return MetaModel::EnumTransitions(get_class($this), $sState);
  969. }
  970. public function ApplyStimulus($sStimulusCode)
  971. {
  972. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  973. if (empty($sStateAttCode)) return false;
  974. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  975. $aStateTransitions = $this->EnumTransitions();
  976. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  977. // Change the state before proceeding to the actions, this is necessary because an action might
  978. // trigger another stimuli (alternative: push the stimuli into a queue)
  979. $sPreviousState = $this->Get($sStateAttCode);
  980. $sNewState = $aTransitionDef['target_state'];
  981. $this->Set($sStateAttCode, $sNewState);
  982. // $aTransitionDef is an
  983. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  984. $bSuccess = true;
  985. foreach ($aTransitionDef['actions'] as $sActionHandler)
  986. {
  987. // std PHP spec
  988. $aActionCallSpec = array($this, $sActionHandler);
  989. if (!is_callable($aActionCallSpec))
  990. {
  991. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  992. return;
  993. }
  994. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  995. // if one call fails, the whole is considered as failed
  996. if (!$bRet) $bSuccess = false;
  997. }
  998. // Change state triggers...
  999. $sClass = get_class($this);
  1000. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1001. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1002. while ($oTrigger = $oSet->Fetch())
  1003. {
  1004. $oTrigger->DoActivate($this->ToArgs('this'));
  1005. }
  1006. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1007. while ($oTrigger = $oSet->Fetch())
  1008. {
  1009. $oTrigger->DoActivate($this->ToArgs('this'));
  1010. }
  1011. return $bSuccess;
  1012. }
  1013. // Make standard context arguments
  1014. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1015. // Several options here:
  1016. // 1) cache the result
  1017. // 2) set only the object ref and resolve the values iif needed from contextual templates and queries (easy for the queries, not for the templates)
  1018. public function ToArgs($sArgName = 'this')
  1019. {
  1020. if (is_null($this->m_aAsArgs))
  1021. {
  1022. $oKPI = new ExecutionKPI();
  1023. $aScalarArgs = array();
  1024. $aScalarArgs[$sArgName] = $this->GetKey();
  1025. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1026. $aScalarArgs[$sArgName.'->object()'] = $this;
  1027. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  1028. // #@# Prototype for a user portal - to be dehardcoded later
  1029. $sToPortal = utils::GetAbsoluteUrlPath().'../portal/index.php?operation=details&id='.$this->GetKey();
  1030. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1031. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1032. $sClass = get_class($this);
  1033. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1034. {
  1035. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1036. if ($oAttDef->IsScalar())
  1037. {
  1038. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1039. $sAsHtml = $this->GetAsHtml($sAttCode);
  1040. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1041. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1042. }
  1043. }
  1044. $this->m_aAsArgs = $aScalarArgs;
  1045. $oKPI->ComputeStats('ToArgs', get_class($this));
  1046. }
  1047. return $this->m_aAsArgs;
  1048. }
  1049. // To be optionaly overloaded
  1050. protected function OnInsert()
  1051. {
  1052. }
  1053. // To be optionaly overloaded
  1054. protected function AfterInsert()
  1055. {
  1056. }
  1057. // To be optionaly overloaded
  1058. protected function OnUpdate()
  1059. {
  1060. }
  1061. // To be optionaly overloaded
  1062. protected function AfterUpdate()
  1063. {
  1064. }
  1065. // To be optionaly overloaded
  1066. protected function OnDelete()
  1067. {
  1068. }
  1069. // To be optionaly overloaded
  1070. protected function AfterDelete()
  1071. {
  1072. }
  1073. // Return an empty set for the parent of all
  1074. public static function GetRelationQueries($sRelCode)
  1075. {
  1076. return array();
  1077. }
  1078. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1079. {
  1080. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1081. {
  1082. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1083. $sQuery = $aQueryInfo["sQuery"];
  1084. $bPropagate = $aQueryInfo["bPropagate"];
  1085. $iDistance = $aQueryInfo["iDistance"];
  1086. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1087. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1088. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1089. while ($oObj = $oObjSet->Fetch())
  1090. {
  1091. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1092. $sObjKey = $oObj->GetKey();
  1093. if (array_key_exists($sRootClass, $aResults))
  1094. {
  1095. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1096. {
  1097. continue; // already visited, skip
  1098. }
  1099. }
  1100. $aResults[$sRootClass][$sObjKey] = $oObj;
  1101. if ($iDepth > 0)
  1102. {
  1103. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1104. }
  1105. }
  1106. }
  1107. return $aResults;
  1108. }
  1109. public function GetReferencingObjects()
  1110. {
  1111. $aDependentObjects = array();
  1112. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1113. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1114. {
  1115. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1116. {
  1117. // skip if this external key is behind an external field
  1118. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1119. $oSearch = new DBObjectSearch($sRemoteClass);
  1120. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1121. $oSet = new CMDBObjectSet($oSearch);
  1122. if ($oSet->Count() > 0)
  1123. {
  1124. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1125. 'attribute' => $oExtKeyAttDef,
  1126. 'objects' => $oSet,
  1127. );
  1128. }
  1129. }
  1130. }
  1131. return $aDependentObjects;
  1132. }
  1133. /**
  1134. * $aDeletedObjs = array(); // [class][key] => structure
  1135. * $aResetedObjs = array(); // [class][key] => object
  1136. */
  1137. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1138. {
  1139. if (array_key_exists(get_class($this), $aVisited))
  1140. {
  1141. if (in_array($this->GetKey(), $aVisited[get_class($this)]))
  1142. {
  1143. return;
  1144. }
  1145. }
  1146. $aVisited[get_class($this)] = $this->GetKey();
  1147. $aDependentObjects = $this->GetReferencingObjects();
  1148. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1149. {
  1150. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1151. {
  1152. $oAttDef = $aData['attribute'];
  1153. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1154. $oDepSet = $aData['objects'];
  1155. $oDepSet->Rewind();
  1156. while ($oDependentObj = $oDepSet->fetch())
  1157. {
  1158. $iId = $oDependentObj->GetKey();
  1159. if ($oAttDef->IsNullAllowed())
  1160. {
  1161. // Optional external key, list to reset
  1162. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1163. {
  1164. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1165. }
  1166. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1167. }
  1168. else
  1169. {
  1170. // Mandatory external key, list to delete
  1171. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1172. {
  1173. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1174. if ($iCurrentOption == DEL_AUTO)
  1175. {
  1176. // be conservative, take the new option
  1177. // (DEL_MANUAL has precedence over DEL_AUTO)
  1178. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1179. }
  1180. else
  1181. {
  1182. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1183. }
  1184. }
  1185. else
  1186. {
  1187. // First time we find the given object in the list
  1188. // (and most likely case is that no other occurence will be found)
  1189. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1190. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1191. // Recursively inspect this object
  1192. if ($iDeletePropagationOption == DEL_AUTO)
  1193. {
  1194. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1195. }
  1196. }
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }
  1202. }
  1203. ?>