dbobject.class.php 38 KB

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