dbobject.class.php 39 KB

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