dbobject.class.php 39 KB

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