dbobject.class.php 40 KB

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