dbobject.class.php 40 KB

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