dbobject.class.php 39 KB

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