dbobject.class.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. <?php
  2. /**
  3. * ???
  4. * the class a persistent object must be derived from
  5. *
  6. * @package iTopORM
  7. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  8. * @author Denis Flaven <denisflave@free.fr>
  9. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  10. * @link www.itop.com
  11. * @since 1.0
  12. * @version 1.1.1.1 $
  13. */
  14. require_once('metamodel.class.php');
  15. /**
  16. * A persistent object, as defined by the metamodel
  17. *
  18. * @package iTopORM
  19. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  20. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  21. * @link www.itop.com
  22. * @since 1.0
  23. * @version $itopversion$
  24. */
  25. abstract class DBObject
  26. {
  27. private static $m_aMemoryObjectsByClass = array();
  28. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  29. private $m_iKey = null;
  30. private $m_aCurrValues = array();
  31. protected $m_aOrigValues = array();
  32. private $m_bDirty = false; // The object may have incorrect external keys, then any attempt of reload must be avoided
  33. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  34. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  35. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  36. public function __construct($aRow = null)
  37. {
  38. if (!empty($aRow))
  39. {
  40. $this->FromRow($aRow);
  41. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  42. return;
  43. }
  44. // Creation of brand new object
  45. //
  46. $this->m_iKey = self::GetNextTempId(get_class($this));
  47. // set default values
  48. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  49. {
  50. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  51. $this->m_aOrigValues[$sAttCode] = null;
  52. if ($oAttDef->IsExternalField())
  53. {
  54. // This field has to be read from the DB
  55. $this->m_aLoadedAtt[$sAttCode] = false;
  56. }
  57. else
  58. {
  59. // No need to trigger a reload for that attribute
  60. // Let's consider it as being already fully loaded
  61. $this->m_aLoadedAtt[$sAttCode] = true;
  62. }
  63. }
  64. }
  65. public function RegisterAsDirty()
  66. {
  67. // While the object may be written to the DB, it is NOT possible to reload it
  68. // or at least not possible to reload it the same way
  69. $this->m_bDirty = true;
  70. }
  71. public function IsNew()
  72. {
  73. return (!$this->m_bIsInDB);
  74. }
  75. // Returns an Id for memory objects
  76. static protected function GetNextTempId($sClass)
  77. {
  78. if (!array_key_exists($sClass, self::$m_aMemoryObjectsByClass))
  79. {
  80. self::$m_aMemoryObjectsByClass[$sClass] = 0;
  81. }
  82. self::$m_aMemoryObjectsByClass[$sClass]++;
  83. return (- self::$m_aMemoryObjectsByClass[$sClass]);
  84. }
  85. public function __toString()
  86. {
  87. $sRet = '';
  88. $sClass = get_class($this);
  89. $sRootClass = MetaModel::GetRootClass($sClass);
  90. $iPKey = $this->GetKey();
  91. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  92. $sRet .= "<ul class=\"treeview\">\n";
  93. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  94. {
  95. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  96. }
  97. $sRet .= "</ul>";
  98. return $sRet;
  99. }
  100. // Restore initial values... mmmm, to be discussed
  101. public function DBRevert()
  102. {
  103. $this->Reload();
  104. }
  105. protected function IsFullyLoaded()
  106. {
  107. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  108. {
  109. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  110. if ($bIsLoaded !== true)
  111. {
  112. return false;
  113. }
  114. }
  115. return true;
  116. }
  117. protected function Reload()
  118. {
  119. assert($this->m_bIsInDB);
  120. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey);
  121. if (empty($aRow))
  122. {
  123. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  124. }
  125. $this->FromRow($aRow);
  126. // Process linked set attributes
  127. //
  128. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  129. {
  130. if (!$oAttDef->IsLinkSet()) continue;
  131. // Load the link information
  132. $sLinkClass = $oAttDef->GetLinkedClass();
  133. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  134. // The class to target is not the current class, because if this is a derived class,
  135. // it may differ from the target class, then things start to become confusing
  136. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  137. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  138. $oMyselfSearch = new DBObjectSearch($sMyClass);
  139. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  140. $oLinkSearch = new DBObjectSearch($sLinkClass);
  141. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  142. $oLinks = new DBObjectSet($oLinkSearch);
  143. $this->m_aCurrValues[$sAttCode] = $oLinks;
  144. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  145. $this->m_aLoadedAtt[$sAttCode] = true;
  146. }
  147. $this->m_bFullyLoaded = true;
  148. }
  149. protected function FromRow($aRow)
  150. {
  151. $this->m_iKey = null;
  152. $this->m_bIsInDB = true;
  153. $this->m_aCurrValues = array();
  154. $this->m_aOrigValues = array();
  155. $this->m_aLoadedAtt = array();
  156. // Get the key
  157. //
  158. $sKeyField = "id";
  159. if (!array_key_exists($sKeyField, $aRow))
  160. {
  161. // #@# Bug ?
  162. throw new CoreException("Missing key for class '".get_class($this)."'");
  163. }
  164. else
  165. {
  166. $iPKey = $aRow[$sKeyField];
  167. if (!self::IsValidPKey($iPKey))
  168. {
  169. throw new CoreWarning("An object id must be an integer value ($iPKey)");
  170. }
  171. $this->m_iKey = $iPKey;
  172. }
  173. // Build the object from an array of "attCode"=>"value")
  174. //
  175. $bFullyLoaded = true; // ... set to false if any attribute is not found
  176. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  177. {
  178. // Say something, whatever the type of attribute
  179. $this->m_aLoadedAtt[$sAttCode] = false;
  180. // Skip links (could not be loaded by the mean of this query)
  181. if ($oAttDef->IsLinkSet()) continue;
  182. // Note: we assume that, for a given attribute, if it can be loaded,
  183. // then one column will be found with an empty suffix, the others have a suffix
  184. // Take care: the function isset will return false in case the value is null,
  185. // which is something that could happen on open joins
  186. if (array_key_exists($sAttCode, $aRow))
  187. {
  188. $value = $oAttDef->FromSQLToValue($aRow, $sAttCode);
  189. $this->m_aCurrValues[$sAttCode] = $value;
  190. $this->m_aOrigValues[$sAttCode] = $value;
  191. $this->m_aLoadedAtt[$sAttCode] = true;
  192. }
  193. else
  194. {
  195. // This attribute was expected and not found in the query columns
  196. $bFullyLoaded = false;
  197. }
  198. }
  199. return $bFullyLoaded;
  200. }
  201. public function Set($sAttCode, $value)
  202. {
  203. if ($sAttCode == 'finalclass')
  204. {
  205. // Ignore it - this attribute is set upon object creation and that's it
  206. //throw new CoreWarning('Attempting to set the value for the internal attribute \"finalclass\"', array('current value'=>$this->Get('finalclass'), 'new value'=>$value));
  207. return;
  208. }
  209. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  210. {
  211. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  212. }
  213. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  214. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  215. {
  216. // First time Set is called... ensure that the object gets fully loaded
  217. // Otherwise we would lose the values on a further Reload
  218. // + consistency does not make sense !
  219. $this->Reload();
  220. }
  221. if($oAttDef->IsScalar() && !$oAttDef->IsNullAllowed() && is_null($value))
  222. {
  223. throw new CoreWarning("null not allowed for attribute '$sAttCode', setting default value");
  224. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  225. return;
  226. }
  227. if ($oAttDef->IsExternalKey() && is_object($value))
  228. {
  229. // Setting an external key with a whole object (instead of just an ID)
  230. // let's initialize also the external fields that depend on it
  231. // (useful when building objects in memory and not from a query)
  232. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  233. {
  234. throw new CoreWarning("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
  235. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  236. }
  237. else
  238. {
  239. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  240. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  241. {
  242. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  243. {
  244. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  245. }
  246. }
  247. }
  248. return;
  249. }
  250. if(!$oAttDef->IsScalar() && !is_object($value))
  251. {
  252. throw new CoreWarning("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  253. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  254. return;
  255. }
  256. if($oAttDef->IsLinkSet())
  257. {
  258. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  259. {
  260. throw new CoreWarning("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  261. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  262. return;
  263. }
  264. $oObjectSet = $value;
  265. $sSetClass = $oObjectSet->GetClass();
  266. $sLinkClass = $oAttDef->GetLinkedClass();
  267. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  268. if ($sSetClass != $sLinkClass)
  269. {
  270. throw new CoreWarning("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  271. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  272. return;
  273. }
  274. }
  275. $this->m_aCurrValues[$sAttCode] = $oAttDef->MakeRealValue($value);
  276. $this->RegisterAsDirty(); // Make sure we do not reload it anymore... before saving it
  277. }
  278. public function Get($sAttCode)
  279. {
  280. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  281. {
  282. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  283. }
  284. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  285. {
  286. // #@# non-scalar attributes.... handle that differentely
  287. $this->Reload();
  288. }
  289. $this->ComputeFields();
  290. return $this->m_aCurrValues[$sAttCode];
  291. }
  292. public function GetOriginal($sAttCode)
  293. {
  294. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  295. {
  296. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  297. }
  298. return $this->m_aOrigValues[$sAttCode];
  299. }
  300. public function ComputeFields()
  301. {
  302. if (is_callable(array($this, 'ComputeValues')))
  303. {
  304. // First check that we are not currently computing the fields
  305. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  306. foreach (debug_backtrace() as $aCallInfo)
  307. {
  308. if (!array_key_exists("class", $aCallInfo)) continue;
  309. if ($aCallInfo["class"] != get_class($this)) continue;
  310. if ($aCallInfo["function"] != "ComputeValues") continue;
  311. return; //skip!
  312. }
  313. $this->ComputeValues();
  314. }
  315. }
  316. public function GetAsHTML($sAttCode)
  317. {
  318. $sClass = get_class($this);
  319. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  320. $aExtKeyFriends = MetaModel::GetExtKeyFriends($sClass, $sAttCode);
  321. if (count($aExtKeyFriends) > 0)
  322. {
  323. // This attribute is an ext key (in this class or in another class)
  324. // The corresponding value is an id of the remote object
  325. // Let's try to use the corresponding external fields for a sexy display
  326. $aAvailableFields = array();
  327. foreach ($aExtKeyFriends as $sDispAttCode => $oExtField)
  328. {
  329. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  330. }
  331. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  332. return $this->MakeHyperLink($sTargetClass, $this->Get($sAttCode), $aAvailableFields);
  333. }
  334. // That's a standard attribute (might be an ext field or a direct field, etc.)
  335. return $oAtt->GetAsHTML($this->Get($sAttCode));
  336. }
  337. public function GetAsXML($sAttCode)
  338. {
  339. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  340. return $oAtt->GetAsXML($this->Get($sAttCode));
  341. }
  342. public function GetAsCSV($sAttCode, $sSeparator = ';', $sSepEscape = ',')
  343. {
  344. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  345. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sSepEscape);
  346. }
  347. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  348. {
  349. if ($sObjKey == 0) return '<em>undefined</em>';
  350. return MetaModel::GetName($sObjClass)."::$sObjKey";
  351. }
  352. public function GetHyperlink()
  353. {
  354. $aAvailableFields[MetaModel::GetNameAttributeCode(get_class($this))] = $this->GetName();
  355. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $aAvailableFields);
  356. }
  357. // could be in the metamodel ?
  358. public static function IsValidPKey($value)
  359. {
  360. return ((string)$value === (string)(int)$value);
  361. }
  362. public function GetKey()
  363. {
  364. return $this->m_iKey;
  365. }
  366. public function SetKey($iNewKey)
  367. {
  368. if (!self::IsValidPKey($iNewKey))
  369. {
  370. throw new CoreException("An object id must be an integer value ($iNewKey)");
  371. }
  372. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  373. {
  374. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  375. }
  376. $this->m_iKey = $iNewKey;
  377. }
  378. public function GetName()
  379. {
  380. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  381. if (empty($sNameAttCode))
  382. {
  383. return $this->m_iKey;
  384. }
  385. else
  386. {
  387. return $this->Get($sNameAttCode);
  388. }
  389. }
  390. public function GetState()
  391. {
  392. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  393. if (empty($sStateAttCode))
  394. {
  395. return '';
  396. }
  397. else
  398. {
  399. $aStates = MetaModel::EnumStates(get_class($this));
  400. return $aStates[$this->Get($sStateAttCode)]['label'];
  401. }
  402. }
  403. /**
  404. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  405. * for the given attribute in the current state of the object
  406. * @param string $sAttCode The code of the attribute
  407. * @return integer Flags: the binary combination of the flags applicable to this attribute
  408. */
  409. public function GetAttributeFlags($sAttCode)
  410. {
  411. $iFlags = 0; // By default (if no life cycle) no flag at all
  412. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  413. if (!empty($sStateAttCode))
  414. {
  415. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  416. }
  417. return $iFlags;
  418. }
  419. // check if the given (or current) value is suitable for the attribute
  420. public function CheckValue($sAttCode, $value = null)
  421. {
  422. if (!is_null($value))
  423. {
  424. $toCheck = $value;
  425. }
  426. else
  427. {
  428. $toCheck = $this->Get($sAttCode);
  429. }
  430. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  431. if ($oAtt->IsExternalKey())
  432. {
  433. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  434. {
  435. try
  436. {
  437. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  438. return true;
  439. }
  440. catch (CoreException $e)
  441. {
  442. return false;
  443. }
  444. }
  445. }
  446. elseif ($oAtt->IsWritable() && $oAtt->IsScalar())
  447. {
  448. $aValues = $oAtt->GetAllowedValues();
  449. if (count($aValues) > 0)
  450. {
  451. if (!array_key_exists($toCheck, $aValues))
  452. {
  453. return false;
  454. }
  455. }
  456. }
  457. return true;
  458. }
  459. // check attributes together
  460. public function CheckConsistency()
  461. {
  462. return true;
  463. }
  464. // check if it is allowed to record the new object into the database
  465. // a displayable error is returned
  466. // Note: checks the values and consistency
  467. public function CheckToInsert()
  468. {
  469. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  470. {
  471. if (!$this->CheckValue($sAttCode)) return false;
  472. }
  473. if (!$this->CheckConsistency()) return false;
  474. return true;
  475. }
  476. // check if it is allowed to update the existing object into the database
  477. // a displayable error is returned
  478. // Note: checks the values and consistency
  479. public function CheckToUpdate()
  480. {
  481. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  482. {
  483. if (!$this->CheckValue($sAttCode)) return false;
  484. }
  485. if (!$this->CheckConsistency()) return false;
  486. return true;
  487. }
  488. // check if it is allowed to delete the existing object from the database
  489. // a displayable error is returned
  490. public function CheckToDelete()
  491. {
  492. return true;
  493. }
  494. protected function ListChangedValues(array $aProposal)
  495. {
  496. $aDelta = array();
  497. foreach ($aProposal as $sAtt => $proposedValue)
  498. {
  499. if (!array_key_exists($sAtt, $this->m_aOrigValues) || ($this->m_aOrigValues[$sAtt] != $proposedValue))
  500. {
  501. $aDelta[$sAtt] = $proposedValue;
  502. }
  503. }
  504. return $aDelta;
  505. }
  506. // List the attributes that have been changed
  507. // Returns an array of attname => currentvalue
  508. public function ListChanges()
  509. {
  510. return $this->ListChangedValues($this->m_aCurrValues);
  511. }
  512. // Tells whether or not an object was modified
  513. public function IsModified()
  514. {
  515. $aChanges = $this->ListChanges();
  516. return (count($aChanges) != 0);
  517. }
  518. // used both by insert/update
  519. private function DBWriteLinks()
  520. {
  521. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  522. {
  523. if (!$oAttDef->IsLinkSet()) continue;
  524. $oLinks = $this->Get($sAttCode);
  525. $oLinks->Rewind();
  526. while ($oLinkedObject = $oLinks->Fetch())
  527. {
  528. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  529. if ($oLinkedObject->IsModified())
  530. {
  531. $oLinkedObject->DBWrite();
  532. }
  533. }
  534. // Delete the objects that were initialy present and disappeared from the list
  535. // (if any)
  536. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  537. if ($oOriginalSet != null)
  538. {
  539. $aOriginalList = $oOriginalSet->ToArray();
  540. $aNewSet = $oLinks->ToArray();
  541. $aToDelete = array_diff($aOriginalList, $aNewSet);
  542. foreach ($aToDelete as $iKey => $oObject)
  543. {
  544. $oObject->DBDelete();
  545. }
  546. }
  547. }
  548. }
  549. private function DBInsertSingleTable($sTableClass)
  550. {
  551. $sClass = get_class($this);
  552. // fields in first array, values in the second
  553. $aFieldsToWrite = array();
  554. $aValuesToWrite = array();
  555. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  556. {
  557. // Add it to the list of fields to write
  558. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  559. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  560. }
  561. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  562. {
  563. // Skip this attribute if not defined in this table
  564. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  565. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  566. foreach($aAttColumns as $sColumn => $sValue)
  567. {
  568. $aFieldsToWrite[] = "`$sColumn`";
  569. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  570. }
  571. }
  572. if (count($aValuesToWrite) == 0) return false;
  573. $sTable = MetaModel::DBGetTable($sTableClass);
  574. $sInsertSQL = "INSERT INTO $sTable (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  575. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  576. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  577. if (empty($this->m_iKey))
  578. {
  579. // Take the autonumber
  580. $this->m_iKey = $iNewKey;
  581. }
  582. return $this->m_iKey;
  583. }
  584. // Insert of record for the new object into the database
  585. // Returns the key of the newly created object
  586. public function DBInsertNoReload()
  587. {
  588. if ($this->m_bIsInDB)
  589. {
  590. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  591. }
  592. $sClass = get_class($this);
  593. $sRootClass = MetaModel::GetRootClass($sClass);
  594. // Ensure the update of the values (we are accessing the data directly)
  595. $this->ComputeFields();
  596. if ($this->m_iKey < 0)
  597. {
  598. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  599. $this->m_iKey = null;
  600. }
  601. // If not automatically computed, then check that the key is given by the caller
  602. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  603. {
  604. if (empty($this->m_iKey))
  605. {
  606. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  607. }
  608. }
  609. // First query built upon on the root class, because the ID must be created first
  610. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  611. // Then do the leaf class, if different from the root class
  612. if ($sClass != $sRootClass)
  613. {
  614. $this->DBInsertSingleTable($sClass);
  615. }
  616. // Then do the other classes
  617. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  618. {
  619. if ($sParentClass == $sRootClass) continue;
  620. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  621. $this->DBInsertSingleTable($sParentClass);
  622. }
  623. $this->DBWriteLinks();
  624. $this->m_bIsInDB = true;
  625. // Activate any existing trigger
  626. $sClass = get_class($this);
  627. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  628. while ($oTrigger = $oSet->Fetch())
  629. {
  630. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  631. {
  632. $oTrigger->DoActivate($this->ToArgs('this'));
  633. }
  634. }
  635. return $this->m_iKey;
  636. }
  637. public function DBInsert()
  638. {
  639. $this->DBInsertNoReload();
  640. $this->m_bDirty = false;
  641. $this->Reload();
  642. return $this->m_iKey;
  643. }
  644. // Creates a copy of the current object into the database
  645. // Returns the id of the newly created object
  646. public function DBClone($iNewKey = null)
  647. {
  648. $this->m_bIsInDB = false;
  649. $this->m_iKey = $iNewKey;
  650. return $this->DBInsert();
  651. }
  652. // Update a record
  653. public function DBUpdate()
  654. {
  655. if (!$this->m_bIsInDB)
  656. {
  657. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  658. }
  659. $aChanges = $this->ListChanges();
  660. if (count($aChanges) == 0)
  661. {
  662. throw new CoreWarning("Attempting to update an unchanged object");
  663. return;
  664. }
  665. $bHasANewExternalKeyValue = false;
  666. foreach($aChanges as $sAttCode => $valuecurr)
  667. {
  668. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  669. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  670. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  671. }
  672. // Update scalar attributes
  673. if (count($aChanges) != 0)
  674. {
  675. $oFilter = new DBObjectSearch(get_class($this));
  676. $oFilter->AddCondition('id', $this->m_iKey, '=');
  677. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  678. CMDBSource::Query($sSQL);
  679. }
  680. $this->DBWriteLinks();
  681. $this->m_bDirty = false;
  682. // Reload to get the external attributes
  683. if ($bHasANewExternalKeyValue)
  684. {
  685. $this->Reload();
  686. }
  687. return $this->m_iKey;
  688. }
  689. // Make the current changes persistent - clever wrapper for Insert or Update
  690. public function DBWrite()
  691. {
  692. if ($this->m_bIsInDB)
  693. {
  694. return $this->DBUpdate();
  695. }
  696. else
  697. {
  698. return $this->DBInsert();
  699. }
  700. }
  701. // Delete a record
  702. public function DBDelete()
  703. {
  704. $oFilter = new DBObjectSearch(get_class($this));
  705. $oFilter->AddCondition('id', $this->m_iKey, '=');
  706. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  707. CMDBSource::Query($sSQL);
  708. $this->m_bIsInDB = false;
  709. $this->m_iKey = null;
  710. }
  711. public function EnumTransitions()
  712. {
  713. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  714. if (empty($sStateAttCode)) return array();
  715. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  716. return MetaModel::EnumTransitions(get_class($this), $sState);
  717. }
  718. public function ApplyStimulus($sStimulusCode)
  719. {
  720. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  721. if (empty($sStateAttCode)) return false;
  722. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  723. $aStateTransitions = $this->EnumTransitions();
  724. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  725. // Change the state before proceeding to the actions, this is necessary because an action might
  726. // trigger another stimuli (alternative: push the stimuli into a queue)
  727. $sPreviousState = $this->Get($sStateAttCode);
  728. $sNewState = $aTransitionDef['target_state'];
  729. $this->Set($sStateAttCode, $sNewState);
  730. // $aTransitionDef is an
  731. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  732. $bSuccess = true;
  733. foreach ($aTransitionDef['actions'] as $sActionHandler)
  734. {
  735. // std PHP spec
  736. $aActionCallSpec = array($this, $sActionHandler);
  737. if (!is_callable($aActionCallSpec))
  738. {
  739. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  740. return;
  741. }
  742. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  743. // if one call fails, the whole is considered as failed
  744. if (!$bRet) $bSuccess = false;
  745. }
  746. // Change state triggers...
  747. $sClass = get_class($this);
  748. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class='$sClass' AND t.state='$sPreviousState'"));
  749. while ($oTrigger = $oSet->Fetch())
  750. {
  751. $oTrigger->DoActivate($this->ToArgs('this'));
  752. }
  753. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class='$sClass' AND t.state='$sNewState'"));
  754. while ($oTrigger = $oSet->Fetch())
  755. {
  756. $oTrigger->DoActivate($this->ToArgs('this'));
  757. }
  758. return $bSuccess;
  759. }
  760. // Make standard context arguments
  761. public function ToArgs($sArgName)
  762. {
  763. $aScalarArgs = array();
  764. $aScalarArgs[$sArgName] = $this->GetKey();
  765. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  766. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  767. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  768. $sClass = get_class($this);
  769. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  770. {
  771. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  772. }
  773. return $aScalarArgs;
  774. }
  775. // Return an empty set for the parent of all
  776. public static function GetRelationQueries($sRelCode)
  777. {
  778. return array();
  779. }
  780. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  781. {
  782. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  783. {
  784. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  785. $sQuery = $aQueryInfo["sQuery"];
  786. $bPropagate = $aQueryInfo["bPropagate"];
  787. $iDistance = $aQueryInfo["iDistance"];
  788. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  789. $oFlt = DBObjectSearch::FromSibusQL($sQuery, array(), $this);
  790. $oObjSet = new DBObjectSet($oFlt);
  791. while ($oObj = $oObjSet->Fetch())
  792. {
  793. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  794. $sObjKey = $oObj->GetKey();
  795. if (array_key_exists($sRootClass, $aResults))
  796. {
  797. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  798. {
  799. continue; // already visited, skip
  800. }
  801. }
  802. $aResults[$sRootClass][$sObjKey] = $oObj;
  803. if ($iDepth > 0)
  804. {
  805. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  806. }
  807. }
  808. }
  809. return $aResults;
  810. }
  811. public function GetReferencingObjects()
  812. {
  813. $aDependentObjects = array();
  814. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  815. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  816. {
  817. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  818. {
  819. // skip if this external key is behind an external field
  820. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  821. $oSearch = new DBObjectSearch($sRemoteClass);
  822. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey());
  823. $oSet = new CMDBObjectSet($oSearch);
  824. if ($oSet->Count() > 0)
  825. {
  826. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  827. 'attribute' => $oExtKeyAttDef,
  828. 'objects' => $oSet,
  829. );
  830. }
  831. }
  832. }
  833. return $aDependentObjects;
  834. }
  835. public function GetDeletionScheme()
  836. {
  837. $aDependentObjects = $this->GetReferencingObjects();
  838. $aDeletedObjs = array(); // [class][key] => structure
  839. $aResetedObjs = array(); // [class][key] => object
  840. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  841. {
  842. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  843. {
  844. $oAttDef = $aData['attribute'];
  845. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  846. $oDepSet = $aData['objects'];
  847. $oDepSet->Rewind();
  848. while ($oDependentObj = $oDepSet->fetch())
  849. {
  850. $iId = $oDependentObj->GetKey();
  851. if ($oAttDef->IsNullAllowed())
  852. {
  853. // Optional external key, list to reset
  854. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  855. {
  856. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  857. }
  858. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  859. }
  860. else
  861. {
  862. // Mandatory external key, list to delete
  863. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  864. {
  865. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  866. if ($iCurrentOption == DEL_AUTO)
  867. {
  868. // be conservative, take the new option
  869. // (DEL_MANUAL has precedence over DEL_AUTO)
  870. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  871. }
  872. else
  873. {
  874. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  875. }
  876. }
  877. else
  878. {
  879. // First time we find the given object in the list
  880. // (and most likely case is that no other occurence will be found)
  881. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  882. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  883. }
  884. }
  885. }
  886. }
  887. }
  888. return array($aDeletedObjs, $aResetedObjs);
  889. }
  890. }
  891. ?>