dbobject.class.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  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. if (MetaModel::DBIsReadOnly())
  768. {
  769. $iNewKey = -1;
  770. }
  771. else
  772. {
  773. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  774. }
  775. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  776. if (empty($this->m_iKey))
  777. {
  778. // Take the autonumber
  779. $this->m_iKey = $iNewKey;
  780. }
  781. return $this->m_iKey;
  782. }
  783. // Insert of record for the new object into the database
  784. // Returns the key of the newly created object
  785. public function DBInsertNoReload()
  786. {
  787. if ($this->m_bIsInDB)
  788. {
  789. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  790. }
  791. $sClass = get_class($this);
  792. $sRootClass = MetaModel::GetRootClass($sClass);
  793. // Ensure the update of the values (we are accessing the data directly)
  794. $this->DoComputeValues();
  795. $this->OnInsert();
  796. if ($this->m_iKey < 0)
  797. {
  798. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  799. $this->m_iKey = null;
  800. }
  801. // If not automatically computed, then check that the key is given by the caller
  802. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  803. {
  804. if (empty($this->m_iKey))
  805. {
  806. 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));
  807. }
  808. }
  809. // Ultimate check - ensure DB integrity
  810. list($bRes, $aIssues) = $this->CheckToWrite();
  811. if (!$bRes)
  812. {
  813. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  814. }
  815. // First query built upon on the root class, because the ID must be created first
  816. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  817. // Then do the leaf class, if different from the root class
  818. if ($sClass != $sRootClass)
  819. {
  820. $this->DBInsertSingleTable($sClass);
  821. }
  822. // Then do the other classes
  823. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  824. {
  825. if ($sParentClass == $sRootClass) continue;
  826. $this->DBInsertSingleTable($sParentClass);
  827. }
  828. $this->DBWriteLinks();
  829. $this->m_bIsInDB = true;
  830. $this->m_bDirty = false;
  831. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  832. $this->m_aAsArgs = null;
  833. $this->AfterInsert();
  834. // Activate any existing trigger
  835. $sClass = get_class($this);
  836. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  837. while ($oTrigger = $oSet->Fetch())
  838. {
  839. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  840. {
  841. $oTrigger->DoActivate($this->ToArgs('this'));
  842. }
  843. }
  844. return $this->m_iKey;
  845. }
  846. public function DBInsert()
  847. {
  848. $this->DBInsertNoReload();
  849. $this->Reload();
  850. return $this->m_iKey;
  851. }
  852. public function DBInsertTracked(CMDBChange $oVoid)
  853. {
  854. return $this->DBInsert();
  855. }
  856. // Creates a copy of the current object into the database
  857. // Returns the id of the newly created object
  858. public function DBClone($iNewKey = null)
  859. {
  860. $this->m_bIsInDB = false;
  861. $this->m_iKey = $iNewKey;
  862. return $this->DBInsert();
  863. }
  864. /**
  865. * This function is automatically called after cloning an object with the "clone" PHP language construct
  866. * The purpose of this method is to reset the appropriate attributes of the object in
  867. * order to make sure that the newly cloned object is really distinct from its clone
  868. */
  869. public function __clone()
  870. {
  871. $this->m_bIsInDB = false;
  872. $this->m_bDirty = true;
  873. $this->m_iKey = self::GetNextTempId(get_class($this));
  874. }
  875. // Update a record
  876. public function DBUpdate()
  877. {
  878. if (!$this->m_bIsInDB)
  879. {
  880. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  881. }
  882. $this->DoComputeValues();
  883. $this->OnUpdate();
  884. $aChanges = $this->ListChanges();
  885. if (count($aChanges) == 0)
  886. {
  887. //throw new CoreWarning("Attempting to update an unchanged object");
  888. return;
  889. }
  890. // Ultimate check - ensure DB integrity
  891. list($bRes, $aIssues) = $this->CheckToWrite();
  892. if (!$bRes)
  893. {
  894. 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));
  895. }
  896. $bHasANewExternalKeyValue = false;
  897. foreach($aChanges as $sAttCode => $valuecurr)
  898. {
  899. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  900. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  901. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  902. }
  903. // Update scalar attributes
  904. if (count($aChanges) != 0)
  905. {
  906. $oFilter = new DBObjectSearch(get_class($this));
  907. $oFilter->AddCondition('id', $this->m_iKey, '=');
  908. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  909. if (!MetaModel::DBIsReadOnly())
  910. {
  911. CMDBSource::Query($sSQL);
  912. }
  913. }
  914. $this->DBWriteLinks();
  915. $this->m_bDirty = false;
  916. $this->AfterUpdate();
  917. // Reload to get the external attributes
  918. if ($bHasANewExternalKeyValue)
  919. {
  920. $this->Reload();
  921. }
  922. return $this->m_iKey;
  923. }
  924. public function DBUpdateTracked(CMDBChange $oVoid)
  925. {
  926. return $this->DBUpdate();
  927. }
  928. // Make the current changes persistent - clever wrapper for Insert or Update
  929. public function DBWrite()
  930. {
  931. if ($this->m_bIsInDB)
  932. {
  933. return $this->DBUpdate();
  934. }
  935. else
  936. {
  937. return $this->DBInsert();
  938. }
  939. }
  940. // Delete a record
  941. public function DBDelete()
  942. {
  943. $oFilter = new DBObjectSearch(get_class($this));
  944. $oFilter->AddCondition('id', $this->m_iKey, '=');
  945. $this->OnDelete();
  946. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  947. if (!MetaModel::DBIsReadOnly())
  948. {
  949. CMDBSource::Query($sSQL);
  950. }
  951. $this->AfterDelete();
  952. $this->m_bIsInDB = false;
  953. $this->m_iKey = null;
  954. }
  955. public function DBDeleteTracked(CMDBChange $oVoid)
  956. {
  957. $this->DBDelete();
  958. }
  959. public function EnumTransitions()
  960. {
  961. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  962. if (empty($sStateAttCode)) return array();
  963. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  964. return MetaModel::EnumTransitions(get_class($this), $sState);
  965. }
  966. public function ApplyStimulus($sStimulusCode)
  967. {
  968. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  969. if (empty($sStateAttCode)) return false;
  970. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  971. $aStateTransitions = $this->EnumTransitions();
  972. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  973. // Change the state before proceeding to the actions, this is necessary because an action might
  974. // trigger another stimuli (alternative: push the stimuli into a queue)
  975. $sPreviousState = $this->Get($sStateAttCode);
  976. $sNewState = $aTransitionDef['target_state'];
  977. $this->Set($sStateAttCode, $sNewState);
  978. // $aTransitionDef is an
  979. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  980. $bSuccess = true;
  981. foreach ($aTransitionDef['actions'] as $sActionHandler)
  982. {
  983. // std PHP spec
  984. $aActionCallSpec = array($this, $sActionHandler);
  985. if (!is_callable($aActionCallSpec))
  986. {
  987. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  988. return;
  989. }
  990. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  991. // if one call fails, the whole is considered as failed
  992. if (!$bRet) $bSuccess = false;
  993. }
  994. // Change state triggers...
  995. $sClass = get_class($this);
  996. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  997. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  998. while ($oTrigger = $oSet->Fetch())
  999. {
  1000. $oTrigger->DoActivate($this->ToArgs('this'));
  1001. }
  1002. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1003. while ($oTrigger = $oSet->Fetch())
  1004. {
  1005. $oTrigger->DoActivate($this->ToArgs('this'));
  1006. }
  1007. return $bSuccess;
  1008. }
  1009. // Make standard context arguments
  1010. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1011. // Several options here:
  1012. // 1) cache the result
  1013. // 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)
  1014. public function ToArgs($sArgName = 'this')
  1015. {
  1016. if (is_null($this->m_aAsArgs))
  1017. {
  1018. $oKPI = new ExecutionKPI();
  1019. $aScalarArgs = array();
  1020. $aScalarArgs[$sArgName] = $this->GetKey();
  1021. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1022. $aScalarArgs[$sArgName.'->object()'] = $this;
  1023. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  1024. // #@# Prototype for a user portal - to be dehardcoded later
  1025. $sToPortal = utils::GetAbsoluteUrlPath().'../portal/index.php?operation=details&id='.$this->GetKey();
  1026. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1027. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1028. $sClass = get_class($this);
  1029. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1030. {
  1031. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1032. if ($oAttDef->IsScalar())
  1033. {
  1034. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1035. $sAsHtml = $this->GetAsHtml($sAttCode);
  1036. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1037. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1038. }
  1039. }
  1040. $this->m_aAsArgs = $aScalarArgs;
  1041. $oKPI->ComputeStats('ToArgs', get_class($this));
  1042. }
  1043. return $this->m_aAsArgs;
  1044. }
  1045. // To be optionaly overloaded
  1046. protected function OnInsert()
  1047. {
  1048. }
  1049. // To be optionaly overloaded
  1050. protected function AfterInsert()
  1051. {
  1052. }
  1053. // To be optionaly overloaded
  1054. protected function OnUpdate()
  1055. {
  1056. }
  1057. // To be optionaly overloaded
  1058. protected function AfterUpdate()
  1059. {
  1060. }
  1061. // To be optionaly overloaded
  1062. protected function OnDelete()
  1063. {
  1064. }
  1065. // To be optionaly overloaded
  1066. protected function AfterDelete()
  1067. {
  1068. }
  1069. // Return an empty set for the parent of all
  1070. public static function GetRelationQueries($sRelCode)
  1071. {
  1072. return array();
  1073. }
  1074. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1075. {
  1076. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1077. {
  1078. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1079. $sQuery = $aQueryInfo["sQuery"];
  1080. $bPropagate = $aQueryInfo["bPropagate"];
  1081. $iDistance = $aQueryInfo["iDistance"];
  1082. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1083. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1084. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1085. while ($oObj = $oObjSet->Fetch())
  1086. {
  1087. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1088. $sObjKey = $oObj->GetKey();
  1089. if (array_key_exists($sRootClass, $aResults))
  1090. {
  1091. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1092. {
  1093. continue; // already visited, skip
  1094. }
  1095. }
  1096. $aResults[$sRootClass][$sObjKey] = $oObj;
  1097. if ($iDepth > 0)
  1098. {
  1099. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1100. }
  1101. }
  1102. }
  1103. return $aResults;
  1104. }
  1105. public function GetReferencingObjects()
  1106. {
  1107. $aDependentObjects = array();
  1108. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1109. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1110. {
  1111. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1112. {
  1113. // skip if this external key is behind an external field
  1114. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1115. $oSearch = new DBObjectSearch($sRemoteClass);
  1116. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1117. $oSet = new CMDBObjectSet($oSearch);
  1118. if ($oSet->Count() > 0)
  1119. {
  1120. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1121. 'attribute' => $oExtKeyAttDef,
  1122. 'objects' => $oSet,
  1123. );
  1124. }
  1125. }
  1126. }
  1127. return $aDependentObjects;
  1128. }
  1129. /**
  1130. * $aDeletedObjs = array(); // [class][key] => structure
  1131. * $aResetedObjs = array(); // [class][key] => object
  1132. */
  1133. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1134. {
  1135. if (array_key_exists(get_class($this), $aVisited))
  1136. {
  1137. if (in_array($this->GetKey(), $aVisited[get_class($this)]))
  1138. {
  1139. return;
  1140. }
  1141. }
  1142. $aVisited[get_class($this)] = $this->GetKey();
  1143. $aDependentObjects = $this->GetReferencingObjects();
  1144. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1145. {
  1146. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1147. {
  1148. $oAttDef = $aData['attribute'];
  1149. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1150. $oDepSet = $aData['objects'];
  1151. $oDepSet->Rewind();
  1152. while ($oDependentObj = $oDepSet->fetch())
  1153. {
  1154. $iId = $oDependentObj->GetKey();
  1155. if ($oAttDef->IsNullAllowed())
  1156. {
  1157. // Optional external key, list to reset
  1158. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1159. {
  1160. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1161. }
  1162. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1163. }
  1164. else
  1165. {
  1166. // Mandatory external key, list to delete
  1167. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1168. {
  1169. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1170. if ($iCurrentOption == DEL_AUTO)
  1171. {
  1172. // be conservative, take the new option
  1173. // (DEL_MANUAL has precedence over DEL_AUTO)
  1174. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1175. }
  1176. else
  1177. {
  1178. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1179. }
  1180. }
  1181. else
  1182. {
  1183. // First time we find the given object in the list
  1184. // (and most likely case is that no other occurence will be found)
  1185. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1186. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1187. // Recursively inspect this object
  1188. if ($iDeletePropagationOption == DEL_AUTO)
  1189. {
  1190. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1191. }
  1192. }
  1193. }
  1194. }
  1195. }
  1196. }
  1197. }
  1198. }
  1199. ?>