dbobject.class.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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. $aExtKeyFriends = MetaModel::GetExtKeyFriends($sClass, $sAttCode);
  350. if (count($aExtKeyFriends) > 0)
  351. {
  352. // This attribute is an ext key (in this class or in another class)
  353. // The corresponding value is an id of the remote object
  354. // Let's try to use the corresponding external fields for a sexy display
  355. $aAvailableFields = array();
  356. foreach ($aExtKeyFriends as $sDispAttCode => $oExtField)
  357. {
  358. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  359. }
  360. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  361. return $this->MakeHyperLink($sTargetClass, $this->Get($sAttCode), $aAvailableFields);
  362. }
  363. // That's a standard attribute (might be an ext field or a direct field, etc.)
  364. return $oAtt->GetAsHTML($this->Get($sAttCode));
  365. }
  366. public function GetEditValue($sAttCode)
  367. {
  368. $sClass = get_class($this);
  369. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  370. if ($oAtt->IsExternalKey())
  371. {
  372. $sTargetClass = $oAtt->GetTargetClass();
  373. if ($this->IsNew())
  374. {
  375. // The current object exists only in memory, don't try to query it in the DB !
  376. // instead let's query for the object pointed by the external key, and get its name
  377. $targetObjId = $this->Get($sAttCode);
  378. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  379. if (is_object($oTargetObj))
  380. {
  381. $sEditValue = $oTargetObj->GetName();
  382. }
  383. else
  384. {
  385. $sEditValue = 0;
  386. }
  387. }
  388. else
  389. {
  390. $aAvailableFields = array();
  391. // retrieve the "external fields" linked to this external key
  392. foreach (MetaModel::GetExternalFields(get_class($this), $sAttCode) as $oExtField)
  393. {
  394. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  395. }
  396. // Use the "name" of the target class as the label of the hyperlink
  397. // unless it's not available in the external fields...
  398. $sExtClassNameAtt = MetaModel::GetNameAttributeCode($sTargetClass);
  399. if (isset($aAvailableFields[$sExtClassNameAtt]))
  400. {
  401. $sEditValue = $aAvailableFields[$sExtClassNameAtt];
  402. }
  403. else
  404. {
  405. $sEditValue = implode(' / ', $aAvailableFields);
  406. }
  407. }
  408. }
  409. else
  410. {
  411. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  412. }
  413. return $sEditValue;
  414. }
  415. public function GetAsXML($sAttCode)
  416. {
  417. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  418. return $oAtt->GetAsXML($this->Get($sAttCode));
  419. }
  420. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  421. {
  422. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  423. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  424. }
  425. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  426. {
  427. if ($sObjKey == 0) return '<em>undefined</em>';
  428. return MetaModel::GetName($sObjClass)."::$sObjKey";
  429. }
  430. public function GetHyperlink()
  431. {
  432. $aAvailableFields[MetaModel::GetNameAttributeCode(get_class($this))] = $this->GetName();
  433. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $aAvailableFields);
  434. }
  435. // could be in the metamodel ?
  436. public static function IsValidPKey($value)
  437. {
  438. return ((string)$value === (string)(int)$value);
  439. }
  440. public function GetKey()
  441. {
  442. return $this->m_iKey;
  443. }
  444. public function SetKey($iNewKey)
  445. {
  446. if (!self::IsValidPKey($iNewKey))
  447. {
  448. throw new CoreException("An object id must be an integer value ($iNewKey)");
  449. }
  450. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  451. {
  452. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  453. }
  454. $this->m_iKey = $iNewKey;
  455. }
  456. /**
  457. * Get the icon representing this object
  458. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  459. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  460. */
  461. public function GetIcon($bImgTag = true)
  462. {
  463. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  464. }
  465. public function GetName()
  466. {
  467. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  468. if (empty($sNameAttCode))
  469. {
  470. return $this->m_iKey;
  471. }
  472. else
  473. {
  474. return $this->Get($sNameAttCode);
  475. }
  476. }
  477. public function GetState()
  478. {
  479. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  480. if (empty($sStateAttCode))
  481. {
  482. return '';
  483. }
  484. else
  485. {
  486. return $this->Get($sStateAttCode);
  487. }
  488. }
  489. public function GetStateLabel()
  490. {
  491. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  492. if (empty($sStateAttCode))
  493. {
  494. return '';
  495. }
  496. else
  497. {
  498. $sStateValue = $this->Get($sStateAttCode);
  499. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  500. }
  501. }
  502. public function GetStateDescription()
  503. {
  504. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  505. if (empty($sStateAttCode))
  506. {
  507. return '';
  508. }
  509. else
  510. {
  511. $sStateValue = $this->Get($sStateAttCode);
  512. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  513. }
  514. }
  515. /**
  516. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  517. * for the given attribute in the current state of the object
  518. * @param string $sAttCode The code of the attribute
  519. * @return integer Flags: the binary combination of the flags applicable to this attribute
  520. */
  521. public function GetAttributeFlags($sAttCode)
  522. {
  523. $iFlags = 0; // By default (if no life cycle) no flag at all
  524. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  525. if (!empty($sStateAttCode))
  526. {
  527. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  528. }
  529. return $iFlags;
  530. }
  531. // check if the given (or current) value is suitable for the attribute
  532. // return true if successfull
  533. // return the error desciption otherwise
  534. public function CheckValue($sAttCode, $value = null)
  535. {
  536. if (!is_null($value))
  537. {
  538. $toCheck = $value;
  539. }
  540. else
  541. {
  542. $toCheck = $this->Get($sAttCode);
  543. }
  544. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  545. if (!$oAtt->IsWritable())
  546. {
  547. return true;
  548. }
  549. elseif ($oAtt->IsNull($toCheck))
  550. {
  551. if ($oAtt->IsNullAllowed())
  552. {
  553. return true;
  554. }
  555. else
  556. {
  557. return "Null not allowed";
  558. }
  559. }
  560. elseif ($oAtt->IsExternalKey())
  561. {
  562. if (!MetaModel::SkipCheckExtKeys())
  563. {
  564. $sTargetClass = $oAtt->GetTargetClass();
  565. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  566. if (is_null($oTargetObj))
  567. {
  568. return "Target object not found ($sTargetClass::$toCheck)";
  569. }
  570. }
  571. }
  572. elseif ($oAtt->IsScalar())
  573. {
  574. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  575. if (count($aValues) > 0)
  576. {
  577. if (!array_key_exists($toCheck, $aValues))
  578. {
  579. return "Value not allowed [$toCheck]";
  580. }
  581. }
  582. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  583. {
  584. $iLen = strlen($toCheck);
  585. if ($iLen > $iMaxSize)
  586. {
  587. return "String too long (found $iLen, limited to $iMaxSize)";
  588. }
  589. }
  590. if (!$oAtt->CheckFormat($toCheck))
  591. {
  592. return "Wrong format [$toCheck]";
  593. }
  594. }
  595. return true;
  596. }
  597. // check attributes together
  598. public function CheckConsistency()
  599. {
  600. return true;
  601. }
  602. // check integrity rules (before inserting or updating the object)
  603. // a displayable error is returned
  604. public function DoCheckToWrite()
  605. {
  606. $this->DoComputeValues();
  607. $this->m_aCheckIssues = array();
  608. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  609. {
  610. $res = $this->CheckValue($sAttCode);
  611. if ($res !== true)
  612. {
  613. // $res contains the error description
  614. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  615. }
  616. }
  617. if (count($this->m_aCheckIssues) > 0)
  618. {
  619. // No need to check consistency between attributes if any of them has
  620. // an unexpected value
  621. return;
  622. }
  623. $res = $this->CheckConsistency();
  624. if ($res !== true)
  625. {
  626. // $res contains the error description
  627. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  628. }
  629. }
  630. final public function CheckToWrite()
  631. {
  632. if (MetaModel::SkipCheckToWrite())
  633. {
  634. return array(true, array());
  635. }
  636. if (is_null($this->m_bCheckStatus))
  637. {
  638. $oKPI = new ExecutionKPI();
  639. $this->DoCheckToWrite();
  640. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  641. if (count($this->m_aCheckIssues) == 0)
  642. {
  643. $this->m_bCheckStatus = true;
  644. }
  645. else
  646. {
  647. $this->m_bCheckStatus = false;
  648. }
  649. }
  650. return array($this->m_bCheckStatus, $this->m_aCheckIssues);
  651. }
  652. // check if it is allowed to delete the existing object from the database
  653. // a displayable error is returned
  654. public function CheckToDelete()
  655. {
  656. return true;
  657. }
  658. protected function ListChangedValues(array $aProposal)
  659. {
  660. $aDelta = array();
  661. foreach ($aProposal as $sAtt => $proposedValue)
  662. {
  663. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  664. {
  665. // The value was not set
  666. $aDelta[$sAtt] = $proposedValue;
  667. }
  668. elseif(is_object($proposedValue))
  669. {
  670. // The value is an object, the comparison is not strict
  671. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  672. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  673. {
  674. $aDelta[$sAtt] = $proposedValue;
  675. }
  676. }
  677. else
  678. {
  679. // The value is a scalar, the comparison must be 100% strict
  680. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  681. {
  682. //echo "$sAtt:<pre>\n";
  683. //var_dump($this->m_aOrigValues[$sAtt]);
  684. //var_dump($proposedValue);
  685. //echo "</pre>\n";
  686. $aDelta[$sAtt] = $proposedValue;
  687. }
  688. }
  689. }
  690. return $aDelta;
  691. }
  692. // List the attributes that have been changed
  693. // Returns an array of attname => currentvalue
  694. public function ListChanges()
  695. {
  696. return $this->ListChangedValues($this->m_aCurrValues);
  697. }
  698. // Tells whether or not an object was modified
  699. public function IsModified()
  700. {
  701. $aChanges = $this->ListChanges();
  702. return (count($aChanges) != 0);
  703. }
  704. // used both by insert/update
  705. private function DBWriteLinks()
  706. {
  707. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  708. {
  709. if (!$oAttDef->IsLinkSet()) continue;
  710. $oLinks = $this->Get($sAttCode);
  711. $oLinks->Rewind();
  712. while ($oLinkedObject = $oLinks->Fetch())
  713. {
  714. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  715. if ($oLinkedObject->IsModified())
  716. {
  717. $oLinkedObject->DBWrite();
  718. }
  719. }
  720. // Delete the objects that were initialy present and disappeared from the list
  721. // (if any)
  722. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  723. if ($oOriginalSet != null)
  724. {
  725. $aOriginalList = $oOriginalSet->ToArray();
  726. $aNewSet = $oLinks->ToArray();
  727. foreach($aOriginalList as $iId => $oObject)
  728. {
  729. if (!array_key_exists($iId, $aNewSet))
  730. {
  731. // It disappeared from the list
  732. $oObject->DBDelete();
  733. }
  734. }
  735. }
  736. }
  737. }
  738. private function DBInsertSingleTable($sTableClass)
  739. {
  740. $sTable = MetaModel::DBGetTable($sTableClass);
  741. // Abstract classes or classes having no specific attribute do not have an associated table
  742. if ($sTable == '') return;
  743. $sClass = get_class($this);
  744. // fields in first array, values in the second
  745. $aFieldsToWrite = array();
  746. $aValuesToWrite = array();
  747. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  748. {
  749. // Add it to the list of fields to write
  750. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  751. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  752. }
  753. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  754. {
  755. // Skip this attribute if not defined in this table
  756. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  757. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  758. foreach($aAttColumns as $sColumn => $sValue)
  759. {
  760. $aFieldsToWrite[] = "`$sColumn`";
  761. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  762. }
  763. }
  764. if (count($aValuesToWrite) == 0) return false;
  765. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  766. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  767. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  768. if (empty($this->m_iKey))
  769. {
  770. // Take the autonumber
  771. $this->m_iKey = $iNewKey;
  772. }
  773. return $this->m_iKey;
  774. }
  775. // Insert of record for the new object into the database
  776. // Returns the key of the newly created object
  777. public function DBInsertNoReload()
  778. {
  779. if ($this->m_bIsInDB)
  780. {
  781. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  782. }
  783. $sClass = get_class($this);
  784. $sRootClass = MetaModel::GetRootClass($sClass);
  785. // Ensure the update of the values (we are accessing the data directly)
  786. $this->DoComputeValues();
  787. $this->OnInsert();
  788. if ($this->m_iKey < 0)
  789. {
  790. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  791. $this->m_iKey = null;
  792. }
  793. // If not automatically computed, then check that the key is given by the caller
  794. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  795. {
  796. if (empty($this->m_iKey))
  797. {
  798. 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));
  799. }
  800. }
  801. // Ultimate check - ensure DB integrity
  802. list($bRes, $aIssues) = $this->CheckToWrite();
  803. if (!$bRes)
  804. {
  805. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  806. }
  807. // First query built upon on the root class, because the ID must be created first
  808. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  809. // Then do the leaf class, if different from the root class
  810. if ($sClass != $sRootClass)
  811. {
  812. $this->DBInsertSingleTable($sClass);
  813. }
  814. // Then do the other classes
  815. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  816. {
  817. if ($sParentClass == $sRootClass) continue;
  818. $this->DBInsertSingleTable($sParentClass);
  819. }
  820. $this->DBWriteLinks();
  821. $this->m_bIsInDB = true;
  822. $this->m_bDirty = false;
  823. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  824. $this->m_aAsArgs = null;
  825. $this->AfterInsert();
  826. // Activate any existing trigger
  827. $sClass = get_class($this);
  828. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  829. while ($oTrigger = $oSet->Fetch())
  830. {
  831. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  832. {
  833. $oTrigger->DoActivate($this->ToArgs('this'));
  834. }
  835. }
  836. return $this->m_iKey;
  837. }
  838. public function DBInsert()
  839. {
  840. $this->DBInsertNoReload();
  841. $this->Reload();
  842. return $this->m_iKey;
  843. }
  844. // Creates a copy of the current object into the database
  845. // Returns the id of the newly created object
  846. public function DBClone($iNewKey = null)
  847. {
  848. $this->m_bIsInDB = false;
  849. $this->m_iKey = $iNewKey;
  850. return $this->DBInsert();
  851. }
  852. /**
  853. * This function is automatically called after cloning an object with the "clone" PHP language construct
  854. * The purpose of this method is to reset the appropriate attributes of the object in
  855. * order to make sure that the newly cloned object is really distinct from its clone
  856. */
  857. public function __clone()
  858. {
  859. $this->m_bIsInDB = false;
  860. $this->m_bDirty = true;
  861. $this->m_iKey = self::GetNextTempId(get_class($this));
  862. }
  863. // Update a record
  864. public function DBUpdate()
  865. {
  866. if (!$this->m_bIsInDB)
  867. {
  868. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  869. }
  870. $this->DoComputeValues();
  871. $this->OnUpdate();
  872. $aChanges = $this->ListChanges();
  873. if (count($aChanges) == 0)
  874. {
  875. //throw new CoreWarning("Attempting to update an unchanged object");
  876. return;
  877. }
  878. // Ultimate check - ensure DB integrity
  879. list($bRes, $aIssues) = $this->CheckToWrite();
  880. if (!$bRes)
  881. {
  882. 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));
  883. }
  884. $bHasANewExternalKeyValue = false;
  885. foreach($aChanges as $sAttCode => $valuecurr)
  886. {
  887. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  888. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  889. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  890. }
  891. // Update scalar attributes
  892. if (count($aChanges) != 0)
  893. {
  894. $oFilter = new DBObjectSearch(get_class($this));
  895. $oFilter->AddCondition('id', $this->m_iKey, '=');
  896. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  897. CMDBSource::Query($sSQL);
  898. }
  899. $this->DBWriteLinks();
  900. $this->m_bDirty = false;
  901. $this->AfterUpdate();
  902. // Reload to get the external attributes
  903. if ($bHasANewExternalKeyValue)
  904. {
  905. $this->Reload();
  906. }
  907. return $this->m_iKey;
  908. }
  909. // Make the current changes persistent - clever wrapper for Insert or Update
  910. public function DBWrite()
  911. {
  912. if ($this->m_bIsInDB)
  913. {
  914. return $this->DBUpdate();
  915. }
  916. else
  917. {
  918. return $this->DBInsert();
  919. }
  920. }
  921. // Delete a record
  922. public function DBDelete()
  923. {
  924. $oFilter = new DBObjectSearch(get_class($this));
  925. $oFilter->AddCondition('id', $this->m_iKey, '=');
  926. $this->OnDelete();
  927. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  928. CMDBSource::Query($sSQL);
  929. $this->AfterDelete();
  930. $this->m_bIsInDB = false;
  931. $this->m_iKey = null;
  932. }
  933. public function EnumTransitions()
  934. {
  935. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  936. if (empty($sStateAttCode)) return array();
  937. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  938. return MetaModel::EnumTransitions(get_class($this), $sState);
  939. }
  940. public function ApplyStimulus($sStimulusCode)
  941. {
  942. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  943. if (empty($sStateAttCode)) return false;
  944. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  945. $aStateTransitions = $this->EnumTransitions();
  946. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  947. // Change the state before proceeding to the actions, this is necessary because an action might
  948. // trigger another stimuli (alternative: push the stimuli into a queue)
  949. $sPreviousState = $this->Get($sStateAttCode);
  950. $sNewState = $aTransitionDef['target_state'];
  951. $this->Set($sStateAttCode, $sNewState);
  952. // $aTransitionDef is an
  953. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  954. $bSuccess = true;
  955. foreach ($aTransitionDef['actions'] as $sActionHandler)
  956. {
  957. // std PHP spec
  958. $aActionCallSpec = array($this, $sActionHandler);
  959. if (!is_callable($aActionCallSpec))
  960. {
  961. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  962. return;
  963. }
  964. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  965. // if one call fails, the whole is considered as failed
  966. if (!$bRet) $bSuccess = false;
  967. }
  968. // Change state triggers...
  969. $sClass = get_class($this);
  970. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  971. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  972. while ($oTrigger = $oSet->Fetch())
  973. {
  974. $oTrigger->DoActivate($this->ToArgs('this'));
  975. }
  976. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  977. while ($oTrigger = $oSet->Fetch())
  978. {
  979. $oTrigger->DoActivate($this->ToArgs('this'));
  980. }
  981. return $bSuccess;
  982. }
  983. // Make standard context arguments
  984. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  985. // Several options here:
  986. // 1) cache the result
  987. // 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)
  988. public function ToArgs($sArgName = 'this')
  989. {
  990. if (is_null($this->m_aAsArgs))
  991. {
  992. $oKPI = new ExecutionKPI();
  993. $aScalarArgs = array();
  994. $aScalarArgs[$sArgName] = $this->GetKey();
  995. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  996. $aScalarArgs[$sArgName.'->object()'] = $this;
  997. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  998. // #@# Prototype for a user portal - to be dehardcoded later
  999. $sToPortal = utils::GetAbsoluteUrlPath().'../portal/index.php?operation=details&id='.$this->GetKey();
  1000. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1001. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1002. $sClass = get_class($this);
  1003. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1004. {
  1005. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1006. if ($oAttDef->IsScalar())
  1007. {
  1008. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1009. $sAsHtml = $this->GetAsHtml($sAttCode);
  1010. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1011. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1012. }
  1013. }
  1014. $this->m_aAsArgs = $aScalarArgs;
  1015. $oKPI->ComputeStats('ToArgs', get_class($this));
  1016. }
  1017. return $this->m_aAsArgs;
  1018. }
  1019. // To be optionaly overloaded
  1020. protected function OnInsert()
  1021. {
  1022. }
  1023. // To be optionaly overloaded
  1024. protected function AfterInsert()
  1025. {
  1026. }
  1027. // To be optionaly overloaded
  1028. protected function OnUpdate()
  1029. {
  1030. }
  1031. // To be optionaly overloaded
  1032. protected function AfterUpdate()
  1033. {
  1034. }
  1035. // To be optionaly overloaded
  1036. protected function OnDelete()
  1037. {
  1038. }
  1039. // To be optionaly overloaded
  1040. protected function AfterDelete()
  1041. {
  1042. }
  1043. // Return an empty set for the parent of all
  1044. public static function GetRelationQueries($sRelCode)
  1045. {
  1046. return array();
  1047. }
  1048. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1049. {
  1050. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1051. {
  1052. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1053. $sQuery = $aQueryInfo["sQuery"];
  1054. $bPropagate = $aQueryInfo["bPropagate"];
  1055. $iDistance = $aQueryInfo["iDistance"];
  1056. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1057. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1058. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1059. while ($oObj = $oObjSet->Fetch())
  1060. {
  1061. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1062. $sObjKey = $oObj->GetKey();
  1063. if (array_key_exists($sRootClass, $aResults))
  1064. {
  1065. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1066. {
  1067. continue; // already visited, skip
  1068. }
  1069. }
  1070. $aResults[$sRootClass][$sObjKey] = $oObj;
  1071. if ($iDepth > 0)
  1072. {
  1073. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1074. }
  1075. }
  1076. }
  1077. return $aResults;
  1078. }
  1079. public function GetReferencingObjects()
  1080. {
  1081. $aDependentObjects = array();
  1082. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1083. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1084. {
  1085. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1086. {
  1087. // skip if this external key is behind an external field
  1088. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1089. $oSearch = new DBObjectSearch($sRemoteClass);
  1090. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1091. $oSet = new CMDBObjectSet($oSearch);
  1092. if ($oSet->Count() > 0)
  1093. {
  1094. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1095. 'attribute' => $oExtKeyAttDef,
  1096. 'objects' => $oSet,
  1097. );
  1098. }
  1099. }
  1100. }
  1101. return $aDependentObjects;
  1102. }
  1103. /**
  1104. * $aDeletedObjs = array(); // [class][key] => structure
  1105. * $aResetedObjs = array(); // [class][key] => object
  1106. */
  1107. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1108. {
  1109. if (array_key_exists(get_class($this), $aVisited))
  1110. {
  1111. if (in_array($this->GetKey(), $aVisited[get_class($this)]))
  1112. {
  1113. return;
  1114. }
  1115. }
  1116. $aVisited[get_class($this)] = $this->GetKey();
  1117. $aDependentObjects = $this->GetReferencingObjects();
  1118. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1119. {
  1120. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1121. {
  1122. $oAttDef = $aData['attribute'];
  1123. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1124. $oDepSet = $aData['objects'];
  1125. $oDepSet->Rewind();
  1126. while ($oDependentObj = $oDepSet->fetch())
  1127. {
  1128. $iId = $oDependentObj->GetKey();
  1129. if ($oAttDef->IsNullAllowed())
  1130. {
  1131. // Optional external key, list to reset
  1132. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1133. {
  1134. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1135. }
  1136. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1137. }
  1138. else
  1139. {
  1140. // Mandatory external key, list to delete
  1141. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1142. {
  1143. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1144. if ($iCurrentOption == DEL_AUTO)
  1145. {
  1146. // be conservative, take the new option
  1147. // (DEL_MANUAL has precedence over DEL_AUTO)
  1148. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1149. }
  1150. else
  1151. {
  1152. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1153. }
  1154. }
  1155. else
  1156. {
  1157. // First time we find the given object in the list
  1158. // (and most likely case is that no other occurence will be found)
  1159. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1160. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1161. // Recursively inspect this object
  1162. if ($iDeletePropagationOption == DEL_AUTO)
  1163. {
  1164. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1165. }
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. }
  1173. ?>