dbobject.class.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  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->m_aCheckIssues = array();
  607. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  608. {
  609. $res = $this->CheckValue($sAttCode);
  610. if ($res !== true)
  611. {
  612. // $res contains the error description
  613. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  614. }
  615. }
  616. if (count($this->m_aCheckIssues) > 0)
  617. {
  618. // No need to check consistency between attributes if any of them has
  619. // an unexpected value
  620. return;
  621. }
  622. $res = $this->CheckConsistency();
  623. if ($res !== true)
  624. {
  625. // $res contains the error description
  626. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  627. }
  628. }
  629. final public function CheckToWrite()
  630. {
  631. if (MetaModel::SkipCheckToWrite())
  632. {
  633. return array(true, array());
  634. }
  635. if (is_null($this->m_bCheckStatus))
  636. {
  637. $oKPI = new ExecutionKPI();
  638. $this->DoCheckToWrite();
  639. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  640. if (count($this->m_aCheckIssues) == 0)
  641. {
  642. $this->m_bCheckStatus = true;
  643. }
  644. else
  645. {
  646. $this->m_bCheckStatus = false;
  647. }
  648. }
  649. return array($this->m_bCheckStatus, $this->m_aCheckIssues);
  650. }
  651. // check if it is allowed to delete the existing object from the database
  652. // a displayable error is returned
  653. public function CheckToDelete()
  654. {
  655. return true;
  656. }
  657. protected function ListChangedValues(array $aProposal)
  658. {
  659. $aDelta = array();
  660. foreach ($aProposal as $sAtt => $proposedValue)
  661. {
  662. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  663. {
  664. // The value was not set
  665. $aDelta[$sAtt] = $proposedValue;
  666. }
  667. elseif(is_object($proposedValue))
  668. {
  669. // The value is an object, the comparison is not strict
  670. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  671. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  672. {
  673. $aDelta[$sAtt] = $proposedValue;
  674. }
  675. }
  676. else
  677. {
  678. // The value is a scalar, the comparison must be 100% strict
  679. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  680. {
  681. //echo "$sAtt:<pre>\n";
  682. //var_dump($this->m_aOrigValues[$sAtt]);
  683. //var_dump($proposedValue);
  684. //echo "</pre>\n";
  685. $aDelta[$sAtt] = $proposedValue;
  686. }
  687. }
  688. }
  689. return $aDelta;
  690. }
  691. // List the attributes that have been changed
  692. // Returns an array of attname => currentvalue
  693. public function ListChanges()
  694. {
  695. return $this->ListChangedValues($this->m_aCurrValues);
  696. }
  697. // Tells whether or not an object was modified
  698. public function IsModified()
  699. {
  700. $aChanges = $this->ListChanges();
  701. return (count($aChanges) != 0);
  702. }
  703. // used both by insert/update
  704. private function DBWriteLinks()
  705. {
  706. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  707. {
  708. if (!$oAttDef->IsLinkSet()) continue;
  709. $oLinks = $this->Get($sAttCode);
  710. $oLinks->Rewind();
  711. while ($oLinkedObject = $oLinks->Fetch())
  712. {
  713. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  714. if ($oLinkedObject->IsModified())
  715. {
  716. $oLinkedObject->DBWrite();
  717. }
  718. }
  719. // Delete the objects that were initialy present and disappeared from the list
  720. // (if any)
  721. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  722. if ($oOriginalSet != null)
  723. {
  724. $aOriginalList = $oOriginalSet->ToArray();
  725. $aNewSet = $oLinks->ToArray();
  726. foreach($aOriginalList as $iId => $oObject)
  727. {
  728. if (!array_key_exists($iId, $aNewSet))
  729. {
  730. // It disappeared from the list
  731. $oObject->DBDelete();
  732. }
  733. }
  734. }
  735. }
  736. }
  737. private function DBInsertSingleTable($sTableClass)
  738. {
  739. $sTable = MetaModel::DBGetTable($sTableClass);
  740. // Abstract classes or classes having no specific attribute do not have an associated table
  741. if ($sTable == '') return;
  742. $sClass = get_class($this);
  743. // fields in first array, values in the second
  744. $aFieldsToWrite = array();
  745. $aValuesToWrite = array();
  746. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  747. {
  748. // Add it to the list of fields to write
  749. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  750. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  751. }
  752. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  753. {
  754. // Skip this attribute if not defined in this table
  755. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  756. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  757. foreach($aAttColumns as $sColumn => $sValue)
  758. {
  759. $aFieldsToWrite[] = "`$sColumn`";
  760. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  761. }
  762. }
  763. if (count($aValuesToWrite) == 0) return false;
  764. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  765. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  766. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  767. if (empty($this->m_iKey))
  768. {
  769. // Take the autonumber
  770. $this->m_iKey = $iNewKey;
  771. }
  772. return $this->m_iKey;
  773. }
  774. // Insert of record for the new object into the database
  775. // Returns the key of the newly created object
  776. public function DBInsertNoReload()
  777. {
  778. if ($this->m_bIsInDB)
  779. {
  780. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  781. }
  782. $sClass = get_class($this);
  783. $sRootClass = MetaModel::GetRootClass($sClass);
  784. // Ensure the update of the values (we are accessing the data directly)
  785. $this->DoComputeValues();
  786. $this->OnInsert();
  787. if ($this->m_iKey < 0)
  788. {
  789. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  790. $this->m_iKey = null;
  791. }
  792. // If not automatically computed, then check that the key is given by the caller
  793. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  794. {
  795. if (empty($this->m_iKey))
  796. {
  797. 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));
  798. }
  799. }
  800. // Ultimate check - ensure DB integrity
  801. list($bRes, $aIssues) = $this->CheckToWrite();
  802. if (!$bRes)
  803. {
  804. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  805. }
  806. // First query built upon on the root class, because the ID must be created first
  807. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  808. // Then do the leaf class, if different from the root class
  809. if ($sClass != $sRootClass)
  810. {
  811. $this->DBInsertSingleTable($sClass);
  812. }
  813. // Then do the other classes
  814. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  815. {
  816. if ($sParentClass == $sRootClass) continue;
  817. $this->DBInsertSingleTable($sParentClass);
  818. }
  819. $this->DBWriteLinks();
  820. $this->m_bIsInDB = true;
  821. $this->m_bDirty = false;
  822. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  823. $this->m_aAsArgs = null;
  824. $this->AfterInsert();
  825. // Activate any existing trigger
  826. $sClass = get_class($this);
  827. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  828. while ($oTrigger = $oSet->Fetch())
  829. {
  830. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  831. {
  832. $oTrigger->DoActivate($this->ToArgs('this'));
  833. }
  834. }
  835. return $this->m_iKey;
  836. }
  837. public function DBInsert()
  838. {
  839. $this->DBInsertNoReload();
  840. $this->Reload();
  841. return $this->m_iKey;
  842. }
  843. // Creates a copy of the current object into the database
  844. // Returns the id of the newly created object
  845. public function DBClone($iNewKey = null)
  846. {
  847. $this->m_bIsInDB = false;
  848. $this->m_iKey = $iNewKey;
  849. return $this->DBInsert();
  850. }
  851. /**
  852. * This function is automatically called after cloning an object with the "clone" PHP language construct
  853. * The purpose of this method is to reset the appropriate attributes of the object in
  854. * order to make sure that the newly cloned object is really distinct from its clone
  855. */
  856. public function __clone()
  857. {
  858. $this->m_bIsInDB = false;
  859. $this->m_bDirty = true;
  860. $this->m_iKey = self::GetNextTempId(get_class($this));
  861. }
  862. // Update a record
  863. public function DBUpdate()
  864. {
  865. if (!$this->m_bIsInDB)
  866. {
  867. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  868. }
  869. $this->DoComputeValues();
  870. $this->OnUpdate();
  871. $aChanges = $this->ListChanges();
  872. if (count($aChanges) == 0)
  873. {
  874. //throw new CoreWarning("Attempting to update an unchanged object");
  875. return;
  876. }
  877. // Ultimate check - ensure DB integrity
  878. list($bRes, $aIssues) = $this->CheckToWrite();
  879. if (!$bRes)
  880. {
  881. 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));
  882. }
  883. $bHasANewExternalKeyValue = false;
  884. foreach($aChanges as $sAttCode => $valuecurr)
  885. {
  886. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  887. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  888. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  889. }
  890. // Update scalar attributes
  891. if (count($aChanges) != 0)
  892. {
  893. $oFilter = new DBObjectSearch(get_class($this));
  894. $oFilter->AddCondition('id', $this->m_iKey, '=');
  895. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  896. CMDBSource::Query($sSQL);
  897. }
  898. $this->DBWriteLinks();
  899. $this->m_bDirty = false;
  900. $this->AfterUpdate();
  901. // Reload to get the external attributes
  902. if ($bHasANewExternalKeyValue)
  903. {
  904. $this->Reload();
  905. }
  906. return $this->m_iKey;
  907. }
  908. // Make the current changes persistent - clever wrapper for Insert or Update
  909. public function DBWrite()
  910. {
  911. if ($this->m_bIsInDB)
  912. {
  913. return $this->DBUpdate();
  914. }
  915. else
  916. {
  917. return $this->DBInsert();
  918. }
  919. }
  920. // Delete a record
  921. public function DBDelete()
  922. {
  923. $oFilter = new DBObjectSearch(get_class($this));
  924. $oFilter->AddCondition('id', $this->m_iKey, '=');
  925. $this->OnDelete();
  926. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  927. CMDBSource::Query($sSQL);
  928. $this->AfterDelete();
  929. $this->m_bIsInDB = false;
  930. $this->m_iKey = null;
  931. }
  932. public function EnumTransitions()
  933. {
  934. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  935. if (empty($sStateAttCode)) return array();
  936. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  937. return MetaModel::EnumTransitions(get_class($this), $sState);
  938. }
  939. public function ApplyStimulus($sStimulusCode)
  940. {
  941. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  942. if (empty($sStateAttCode)) return false;
  943. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  944. $aStateTransitions = $this->EnumTransitions();
  945. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  946. // Change the state before proceeding to the actions, this is necessary because an action might
  947. // trigger another stimuli (alternative: push the stimuli into a queue)
  948. $sPreviousState = $this->Get($sStateAttCode);
  949. $sNewState = $aTransitionDef['target_state'];
  950. $this->Set($sStateAttCode, $sNewState);
  951. // $aTransitionDef is an
  952. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  953. $bSuccess = true;
  954. foreach ($aTransitionDef['actions'] as $sActionHandler)
  955. {
  956. // std PHP spec
  957. $aActionCallSpec = array($this, $sActionHandler);
  958. if (!is_callable($aActionCallSpec))
  959. {
  960. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  961. return;
  962. }
  963. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  964. // if one call fails, the whole is considered as failed
  965. if (!$bRet) $bSuccess = false;
  966. }
  967. // Change state triggers...
  968. $sClass = get_class($this);
  969. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  970. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  971. while ($oTrigger = $oSet->Fetch())
  972. {
  973. $oTrigger->DoActivate($this->ToArgs('this'));
  974. }
  975. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  976. while ($oTrigger = $oSet->Fetch())
  977. {
  978. $oTrigger->DoActivate($this->ToArgs('this'));
  979. }
  980. return $bSuccess;
  981. }
  982. // Make standard context arguments
  983. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  984. // Several options here:
  985. // 1) cache the result
  986. // 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)
  987. public function ToArgs($sArgName = 'this')
  988. {
  989. if (is_null($this->m_aAsArgs))
  990. {
  991. $oKPI = new ExecutionKPI();
  992. $aScalarArgs = array();
  993. $aScalarArgs[$sArgName] = $this->GetKey();
  994. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  995. $aScalarArgs[$sArgName.'->object()'] = $this;
  996. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  997. // #@# Prototype for a user portal - to be dehardcoded later
  998. $sToPortal = utils::GetAbsoluteUrlRoot().'/portal/index.php?operation=details&id='.$this->GetKey();
  999. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1000. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1001. $sClass = get_class($this);
  1002. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1003. {
  1004. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1005. if ($oAttDef->IsScalar())
  1006. {
  1007. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1008. $sAsHtml = $this->GetAsHtml($sAttCode);
  1009. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1010. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1011. }
  1012. }
  1013. $this->m_aAsArgs = $aScalarArgs;
  1014. $oKPI->ComputeStats('ToArgs', get_class($this));
  1015. }
  1016. return $this->m_aAsArgs;
  1017. }
  1018. // To be optionaly overloaded
  1019. protected function OnInsert()
  1020. {
  1021. }
  1022. // To be optionaly overloaded
  1023. protected function AfterInsert()
  1024. {
  1025. }
  1026. // To be optionaly overloaded
  1027. protected function OnUpdate()
  1028. {
  1029. }
  1030. // To be optionaly overloaded
  1031. protected function AfterUpdate()
  1032. {
  1033. }
  1034. // To be optionaly overloaded
  1035. protected function OnDelete()
  1036. {
  1037. }
  1038. // To be optionaly overloaded
  1039. protected function AfterDelete()
  1040. {
  1041. }
  1042. // Return an empty set for the parent of all
  1043. public static function GetRelationQueries($sRelCode)
  1044. {
  1045. return array();
  1046. }
  1047. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1048. {
  1049. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1050. {
  1051. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1052. $sQuery = $aQueryInfo["sQuery"];
  1053. $bPropagate = $aQueryInfo["bPropagate"];
  1054. $iDistance = $aQueryInfo["iDistance"];
  1055. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1056. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1057. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1058. while ($oObj = $oObjSet->Fetch())
  1059. {
  1060. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1061. $sObjKey = $oObj->GetKey();
  1062. if (array_key_exists($sRootClass, $aResults))
  1063. {
  1064. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1065. {
  1066. continue; // already visited, skip
  1067. }
  1068. }
  1069. $aResults[$sRootClass][$sObjKey] = $oObj;
  1070. if ($iDepth > 0)
  1071. {
  1072. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1073. }
  1074. }
  1075. }
  1076. return $aResults;
  1077. }
  1078. public function GetReferencingObjects()
  1079. {
  1080. $aDependentObjects = array();
  1081. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1082. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1083. {
  1084. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1085. {
  1086. // skip if this external key is behind an external field
  1087. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1088. $oSearch = new DBObjectSearch($sRemoteClass);
  1089. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1090. $oSet = new CMDBObjectSet($oSearch);
  1091. if ($oSet->Count() > 0)
  1092. {
  1093. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1094. 'attribute' => $oExtKeyAttDef,
  1095. 'objects' => $oSet,
  1096. );
  1097. }
  1098. }
  1099. }
  1100. return $aDependentObjects;
  1101. }
  1102. /**
  1103. * $aDeletedObjs = array(); // [class][key] => structure
  1104. * $aResetedObjs = array(); // [class][key] => object
  1105. */
  1106. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1107. {
  1108. if (array_key_exists(get_class($this), $aVisited))
  1109. {
  1110. if (in_array($this->GetKey(), $aVisited[get_class($this)]))
  1111. {
  1112. return;
  1113. }
  1114. }
  1115. $aVisited[get_class($this)] = $this->GetKey();
  1116. $aDependentObjects = $this->GetReferencingObjects();
  1117. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1118. {
  1119. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1120. {
  1121. $oAttDef = $aData['attribute'];
  1122. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1123. $oDepSet = $aData['objects'];
  1124. $oDepSet->Rewind();
  1125. while ($oDependentObj = $oDepSet->fetch())
  1126. {
  1127. $iId = $oDependentObj->GetKey();
  1128. if ($oAttDef->IsNullAllowed())
  1129. {
  1130. // Optional external key, list to reset
  1131. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1132. {
  1133. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1134. }
  1135. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1136. }
  1137. else
  1138. {
  1139. // Mandatory external key, list to delete
  1140. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1141. {
  1142. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1143. if ($iCurrentOption == DEL_AUTO)
  1144. {
  1145. // be conservative, take the new option
  1146. // (DEL_MANUAL has precedence over DEL_AUTO)
  1147. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1148. }
  1149. else
  1150. {
  1151. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1152. }
  1153. }
  1154. else
  1155. {
  1156. // First time we find the given object in the list
  1157. // (and most likely case is that no other occurence will be found)
  1158. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1159. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1160. // Recursively inspect this object
  1161. if ($iDeletePropagationOption == DEL_AUTO)
  1162. {
  1163. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. ?>