dbobject.class.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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_bFullyLoaded = false; // Compound objects can be partially loaded
  33. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  34. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  35. public function __construct($aRow = null)
  36. {
  37. if (!empty($aRow))
  38. {
  39. $this->FromRow($aRow);
  40. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  41. return;
  42. }
  43. // Creation of brand new object
  44. //
  45. $this->m_iKey = self::GetNextTempId(get_class($this));
  46. // set default values
  47. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  48. {
  49. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  50. $this->m_aOrigValues[$sAttCode] = null;
  51. if ($oAttDef->IsExternalField())
  52. {
  53. // This field has to be read from the DB
  54. $this->m_aLoadedAtt[$sAttCode] = false;
  55. }
  56. else
  57. {
  58. // No need to trigger a reload for that attribute
  59. // Let's consider it as being already fully loaded
  60. $this->m_aLoadedAtt[$sAttCode] = true;
  61. }
  62. }
  63. }
  64. public function IsNew()
  65. {
  66. return (!$this->m_bIsInDB);
  67. }
  68. // Returns an Id for memory objects
  69. static protected function GetNextTempId($sClass)
  70. {
  71. if (!array_key_exists($sClass, self::$m_aMemoryObjectsByClass))
  72. {
  73. self::$m_aMemoryObjectsByClass[$sClass] = 0;
  74. }
  75. self::$m_aMemoryObjectsByClass[$sClass]++;
  76. return (- self::$m_aMemoryObjectsByClass[$sClass]);
  77. }
  78. public function __toString()
  79. {
  80. $sRet = '';
  81. $sClass = get_class($this);
  82. $sRootClass = MetaModel::GetRootClass($sClass);
  83. $iPKey = $this->GetKey();
  84. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  85. $sRet .= "<ul class=\"treeview\">\n";
  86. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  87. {
  88. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  89. }
  90. $sRet .= "</ul>";
  91. return $sRet;
  92. }
  93. // Restore initial values... mmmm, to be discussed
  94. public function DBRevert()
  95. {
  96. $this->Reload();
  97. }
  98. protected function IsFullyLoaded()
  99. {
  100. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  101. {
  102. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  103. if ($bIsLoaded !== true)
  104. {
  105. return false;
  106. }
  107. }
  108. return true;
  109. }
  110. protected function Reload()
  111. {
  112. assert($this->m_bIsInDB);
  113. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey);
  114. if (empty($aRow))
  115. {
  116. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  117. }
  118. $this->FromRow($aRow);
  119. // Process linked set attributes
  120. //
  121. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  122. {
  123. if (!$oAttDef->IsLinkSet()) continue;
  124. // Load the link information
  125. $sLinkClass = $oAttDef->GetLinkedClass();
  126. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  127. // The class to target is not the current class, because if this is a derived class,
  128. // it may differ from the target class, then things start to become confusing
  129. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  130. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  131. $oMyselfSearch = new DBObjectSearch($sMyClass);
  132. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  133. $oLinkSearch = new DBObjectSearch($sLinkClass);
  134. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  135. $oLinks = new DBObjectSet($oLinkSearch);
  136. $this->m_aCurrValues[$sAttCode] = $oLinks;
  137. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  138. $this->m_aLoadedAtt[$sAttCode] = true;
  139. }
  140. $this->m_bFullyLoaded = true;
  141. }
  142. protected function FromRow($aRow)
  143. {
  144. $this->m_iKey = null;
  145. $this->m_bIsInDB = true;
  146. $this->m_aCurrValues = array();
  147. $this->m_aOrigValues = array();
  148. $this->m_aLoadedAtt = array();
  149. // Get the key
  150. //
  151. $sKeyField = "id";
  152. if (!array_key_exists($sKeyField, $aRow))
  153. {
  154. // #@# Bug ?
  155. throw new CoreException("Missing key for class '".get_class($this)."'");
  156. }
  157. else
  158. {
  159. $iPKey = $aRow[$sKeyField];
  160. if (!self::IsValidPKey($iPKey))
  161. {
  162. throw new CoreWarning("An object id must be an integer value ($iPKey)");
  163. }
  164. $this->m_iKey = $iPKey;
  165. }
  166. // Build the object from an array of "attCode"=>"value")
  167. //
  168. $bFullyLoaded = true; // ... set to false if any attribute is not found
  169. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  170. {
  171. // Say something, whatever the type of attribute
  172. $this->m_aLoadedAtt[$sAttCode] = false;
  173. // Skip links (could not be loaded by the mean of this query)
  174. if ($oAttDef->IsLinkSet()) continue;
  175. if (array_key_exists($sAttCode, $aRow))
  176. {
  177. $sValue = $oAttDef->SQLValueToRealValue($aRow[$sAttCode]);
  178. $this->m_aCurrValues[$sAttCode] = $sValue;
  179. $this->m_aOrigValues[$sAttCode] = $sValue;
  180. $this->m_aLoadedAtt[$sAttCode] = true;
  181. }
  182. else
  183. {
  184. // This attribute was expected and not found in the query columns
  185. $bFullyLoaded = false;
  186. }
  187. }
  188. return $bFullyLoaded;
  189. }
  190. public function Set($sAttCode, $value)
  191. {
  192. if ($sAttCode == 'finalclass')
  193. {
  194. // Ignore it - this attribute is set upon object creation and that's it
  195. //throw new CoreWarning('Attempting to set the value for the internal attribute \"finalclass\"', array('current value'=>$this->Get('finalclass'), 'new value'=>$value));
  196. return;
  197. }
  198. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  199. {
  200. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  201. }
  202. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  203. if ($this->m_bIsInDB && !$this->m_bFullyLoaded)
  204. {
  205. // First time Set is called... ensure that the object gets fully loaded
  206. // Otherwise we would lose the values on a further Reload
  207. // + consistency does not make sense !
  208. $this->Reload();
  209. }
  210. if($oAttDef->IsScalar() && !$oAttDef->IsNullAllowed() && is_null($value))
  211. {
  212. throw new CoreWarning("null not allowed for attribute '$sAttCode', setting default value");
  213. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  214. return;
  215. }
  216. if ($oAttDef->IsExternalKey() && is_object($value))
  217. {
  218. // Setting an external key with a whole object (instead of just an ID)
  219. // let's initialize also the external fields that depend on it
  220. // (useful when building objects in memory and not from a query)
  221. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  222. {
  223. 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");
  224. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  225. }
  226. else
  227. {
  228. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  229. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  230. {
  231. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  232. {
  233. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  234. }
  235. }
  236. }
  237. return;
  238. }
  239. if(!$oAttDef->IsScalar() && !is_object($value))
  240. {
  241. throw new CoreWarning("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  242. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  243. return;
  244. }
  245. if($oAttDef->IsLinkSet())
  246. {
  247. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  248. {
  249. throw new CoreWarning("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  250. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  251. return;
  252. }
  253. $oObjectSet = $value;
  254. $sSetClass = $oObjectSet->GetClass();
  255. $sLinkClass = $oAttDef->GetLinkedClass();
  256. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  257. if ($sSetClass != $sLinkClass)
  258. {
  259. throw new CoreWarning("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  260. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  261. return;
  262. }
  263. }
  264. $this->m_aCurrValues[$sAttCode] = $oAttDef->MakeRealValue($value);
  265. }
  266. public function Get($sAttCode)
  267. {
  268. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  269. {
  270. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  271. }
  272. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode])
  273. {
  274. // #@# non-scalar attributes.... handle that differentely
  275. $this->Reload();
  276. }
  277. $this->ComputeFields();
  278. return $this->m_aCurrValues[$sAttCode];
  279. }
  280. public function GetOriginal($sAttCode)
  281. {
  282. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  283. {
  284. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  285. }
  286. return $this->m_aOrigValues[$sAttCode];
  287. }
  288. public function ComputeFields()
  289. {
  290. if (is_callable(array($this, 'ComputeValues')))
  291. {
  292. // First check that we are not currently computing the fields
  293. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  294. foreach (debug_backtrace() as $aCallInfo)
  295. {
  296. if (!array_key_exists("class", $aCallInfo)) continue;
  297. if ($aCallInfo["class"] != get_class($this)) continue;
  298. if ($aCallInfo["function"] != "ComputeValues") continue;
  299. return; //skip!
  300. }
  301. $this->ComputeValues();
  302. }
  303. }
  304. public function GetAsHTML($sAttCode)
  305. {
  306. $sClass = get_class($this);
  307. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  308. $aExtKeyFriends = MetaModel::GetExtKeyFriends($sClass, $sAttCode);
  309. if (count($aExtKeyFriends) > 0)
  310. {
  311. // This attribute is an ext key (in this class or in another class)
  312. // The corresponding value is an id of the remote object
  313. // Let's try to use the corresponding external fields for a sexy display
  314. $aAvailableFields = array();
  315. foreach ($aExtKeyFriends as $sDispAttCode => $oExtField)
  316. {
  317. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  318. }
  319. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  320. return $this->MakeHyperLink($sTargetClass, $this->Get($sAttCode), $aAvailableFields);
  321. }
  322. // That's a standard attribute (might be an ext field or a direct field, etc.)
  323. return $oAtt->GetAsHTML($this->Get($sAttCode));
  324. }
  325. public function GetAsXML($sAttCode)
  326. {
  327. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  328. return $oAtt->GetAsXML($this->Get($sAttCode));
  329. }
  330. public function GetAsCSV($sAttCode, $sSeparator = ';', $sSepEscape = ',')
  331. {
  332. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  333. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sSepEscape);
  334. }
  335. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  336. {
  337. if ($sObjKey == 0) return '<em>undefined</em>';
  338. return MetaModel::GetName($sObjClass)."::$sObjKey";
  339. }
  340. public function GetHyperlink()
  341. {
  342. $aAvailableFields[MetaModel::GetNameAttributeCode(get_class($this))] = $this->GetName();
  343. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $aAvailableFields);
  344. }
  345. // could be in the metamodel ?
  346. public static function IsValidPKey($value)
  347. {
  348. return ((string)$value === (string)(int)$value);
  349. }
  350. public function GetKey()
  351. {
  352. return $this->m_iKey;
  353. }
  354. public function SetKey($iNewKey)
  355. {
  356. if (!self::IsValidPKey($iNewKey))
  357. {
  358. throw new CoreException("An object id must be an integer value ($iNewKey)");
  359. }
  360. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  361. {
  362. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  363. }
  364. $this->m_iKey = $iNewKey;
  365. }
  366. public function GetName()
  367. {
  368. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  369. if (empty($sNameAttCode))
  370. {
  371. return $this->m_iKey;
  372. }
  373. else
  374. {
  375. return $this->Get($sNameAttCode);
  376. }
  377. }
  378. public function GetState()
  379. {
  380. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  381. if (empty($sStateAttCode))
  382. {
  383. return '';
  384. }
  385. else
  386. {
  387. $aStates = MetaModel::EnumStates(get_class($this));
  388. return $aStates[$this->Get($sStateAttCode)]['label'];
  389. }
  390. }
  391. /**
  392. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  393. * for the given attribute in the current state of the object
  394. * @param string $sAttCode The code of the attribute
  395. * @return integer Flags: the binary combination of the flags applicable to this attribute
  396. */
  397. public function GetAttributeFlags($sAttCode)
  398. {
  399. $iFlags = 0; // By default (if no life cycle) no flag at all
  400. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  401. if (!empty($sStateAttCode))
  402. {
  403. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  404. }
  405. return $iFlags;
  406. }
  407. // check if the given (or current) value is suitable for the attribute
  408. public function CheckValue($sAttCode, $value = null)
  409. {
  410. if (!is_null($value))
  411. {
  412. $toCheck = $value;
  413. }
  414. else
  415. {
  416. $toCheck = $this->Get($sAttCode);
  417. }
  418. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  419. if ($oAtt->IsExternalKey())
  420. {
  421. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  422. {
  423. try
  424. {
  425. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  426. return true;
  427. }
  428. catch (CoreException $e)
  429. {
  430. return false;
  431. }
  432. }
  433. }
  434. return true;
  435. }
  436. // check attributes together
  437. public function CheckConsistency()
  438. {
  439. return true;
  440. }
  441. // check if it is allowed to record the new object into the database
  442. // a displayable error is returned
  443. // Note: checks the values and consistency
  444. public function CheckToInsert()
  445. {
  446. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  447. {
  448. if (!$this->CheckValue($sAttCode)) return false;
  449. }
  450. if (!$this->CheckConsistency()) return false;
  451. return true;
  452. }
  453. // check if it is allowed to update the existing object into the database
  454. // a displayable error is returned
  455. // Note: checks the values and consistency
  456. public function CheckToUpdate()
  457. {
  458. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  459. {
  460. if (!$this->CheckValue($sAttCode)) return false;
  461. }
  462. if (!$this->CheckConsistency()) return false;
  463. return true;
  464. }
  465. // check if it is allowed to delete the existing object from the database
  466. // a displayable error is returned
  467. public function CheckToDelete()
  468. {
  469. return true;
  470. }
  471. protected function ListChangedValues(array $aProposal)
  472. {
  473. $aDelta = array();
  474. foreach ($aProposal as $sAtt => $proposedValue)
  475. {
  476. if (!array_key_exists($sAtt, $this->m_aOrigValues) || ($this->m_aOrigValues[$sAtt] != $proposedValue))
  477. {
  478. $aDelta[$sAtt] = $proposedValue;
  479. }
  480. }
  481. return $aDelta;
  482. }
  483. // List the attributes that have been changed
  484. // Returns an array of attname => currentvalue
  485. public function ListChanges()
  486. {
  487. return $this->ListChangedValues($this->m_aCurrValues);
  488. }
  489. // Tells whether or not an object was modified
  490. public function IsModified()
  491. {
  492. $aChanges = $this->ListChanges();
  493. return (count($aChanges) != 0);
  494. }
  495. // used both by insert/update
  496. private function DBWriteLinks()
  497. {
  498. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  499. {
  500. if (!$oAttDef->IsLinkSet()) continue;
  501. $oLinks = $this->Get($sAttCode);
  502. $oLinks->Rewind();
  503. while ($oLinkedObject = $oLinks->Fetch())
  504. {
  505. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  506. if ($oLinkedObject->IsModified())
  507. {
  508. $oLinkedObject->DBWrite();
  509. }
  510. }
  511. // Delete the objects that were initialy present and disappeared from the list
  512. // (if any)
  513. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  514. if ($oOriginalSet != null)
  515. {
  516. $aOriginalList = $oOriginalSet->ToArray();
  517. $aNewSet = $oLinks->ToArray();
  518. $aToDelete = array_diff($aOriginalList, $aNewSet);
  519. foreach ($aToDelete as $iKey => $oObject)
  520. {
  521. $oObject->DBDelete();
  522. }
  523. }
  524. }
  525. }
  526. private function DBInsertSingleTable($sTableClass)
  527. {
  528. $sClass = get_class($this);
  529. // fields in first array, values in the second
  530. $aFieldsToWrite = array();
  531. $aValuesToWrite = array();
  532. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  533. {
  534. // Add it to the list of fields to write
  535. $aFieldsToWrite[] = MetaModel::DBGetKey($sTableClass);
  536. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  537. }
  538. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  539. {
  540. // Skip this attribute if not defined in this table
  541. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  542. if ($oAttDef->IsDirectField())
  543. {
  544. $aFieldsToWrite[] = $oAttDef->GetSQLExpr();
  545. $aValuesToWrite[] = CMDBSource::Quote($oAttDef->RealValueToSQLValue($this->m_aCurrValues[$sAttCode]));
  546. }
  547. }
  548. if (count($aValuesToWrite) == 0) return false;
  549. $sTable = MetaModel::DBGetTable($sTableClass);
  550. $sInsertSQL = "INSERT INTO $sTable (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  551. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  552. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  553. if (empty($this->m_iKey))
  554. {
  555. // Take the autonumber
  556. $this->m_iKey = $iNewKey;
  557. }
  558. return $this->m_iKey;
  559. }
  560. // Insert of record for the new object into the database
  561. // Returns the key of the newly created object
  562. public function DBInsertNoReload()
  563. {
  564. if ($this->m_bIsInDB)
  565. {
  566. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  567. }
  568. $sClass = get_class($this);
  569. $sRootClass = MetaModel::GetRootClass($sClass);
  570. // Ensure the update of the values (we are accessing the data directly)
  571. $this->ComputeFields();
  572. if ($this->m_iKey < 0)
  573. {
  574. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  575. $this->m_iKey = null;
  576. }
  577. // If not automatically computed, then check that the key is given by the caller
  578. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  579. {
  580. if (empty($this->m_iKey))
  581. {
  582. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  583. }
  584. }
  585. // First query built upon on the root class, because the ID must be created first
  586. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  587. // Then do the leaf class, if different from the root class
  588. if ($sClass != $sRootClass)
  589. {
  590. $this->DBInsertSingleTable($sClass);
  591. }
  592. // Then do the other classes
  593. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  594. {
  595. if ($sParentClass == $sRootClass) continue;
  596. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  597. $this->DBInsertSingleTable($sParentClass);
  598. }
  599. $this->DBWriteLinks();
  600. // Reload to update the external attributes
  601. $this->m_bIsInDB = true;
  602. return $this->m_iKey;
  603. }
  604. public function DBInsert()
  605. {
  606. $this->DBInsertNoReload();
  607. $this->Reload();
  608. return $this->m_iKey;
  609. }
  610. // Creates a copy of the current object into the database
  611. // Returns the id of the newly created object
  612. public function DBClone($iNewKey = null)
  613. {
  614. $this->m_bIsInDB = false;
  615. $this->m_iKey = $iNewKey;
  616. return $this->DBInsert();
  617. }
  618. // Update a record
  619. public function DBUpdate()
  620. {
  621. if (!$this->m_bIsInDB)
  622. {
  623. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  624. }
  625. $aChanges = $this->ListChanges();
  626. if (count($aChanges) == 0)
  627. {
  628. throw new CoreWarning("Attempting to update an unchanged object");
  629. return;
  630. }
  631. $bHasANewExternalKeyValue = false;
  632. foreach($aChanges as $sAttCode => $valuecurr)
  633. {
  634. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  635. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  636. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  637. }
  638. // Update scalar attributes
  639. if (count($aChanges) != 0)
  640. {
  641. $oFilter = new DBObjectSearch(get_class($this));
  642. $oFilter->AddCondition('id', $this->m_iKey, '=');
  643. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  644. CMDBSource::Query($sSQL);
  645. }
  646. $this->DBWriteLinks();
  647. // Reload to get the external attributes
  648. if ($bHasANewExternalKeyValue) $this->Reload();
  649. return $this->m_iKey;
  650. }
  651. // Make the current changes persistent - clever wrapper for Insert or Update
  652. public function DBWrite()
  653. {
  654. if ($this->m_bIsInDB)
  655. {
  656. return $this->DBUpdate();
  657. }
  658. else
  659. {
  660. return $this->DBInsert();
  661. }
  662. }
  663. // Delete a record
  664. public function DBDelete()
  665. {
  666. $oFilter = new DBObjectSearch(get_class($this));
  667. $oFilter->AddCondition('id', $this->m_iKey, '=');
  668. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  669. CMDBSource::Query($sSQL);
  670. $this->m_bIsInDB = false;
  671. $this->m_iKey = null;
  672. }
  673. public function EnumTransitions()
  674. {
  675. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  676. if (empty($sStateAttCode)) return array();
  677. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  678. return MetaModel::EnumTransitions(get_class($this), $sState);
  679. }
  680. public function ApplyStimulus($sStimulusCode)
  681. {
  682. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  683. if (empty($sStateAttCode)) return false;
  684. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  685. $aStateTransitions = $this->EnumTransitions();
  686. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  687. // Change the state before proceeding to the actions, this is necessary because an action might
  688. // trigger another stimuli (alternative: push the stimuli into a queue)
  689. $this->Set($sStateAttCode, $aTransitionDef['target_state']);
  690. // $aTransitionDef is an
  691. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  692. $bSuccess = true;
  693. foreach ($aTransitionDef['actions'] as $sActionHandler)
  694. {
  695. // std PHP spec
  696. $aActionCallSpec = array($this, $sActionHandler);
  697. if (!is_callable($aActionCallSpec))
  698. {
  699. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  700. return;
  701. }
  702. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  703. // if one call fails, the whole is considered as failed
  704. if (!$bRet) $bSuccess = false;
  705. }
  706. return $bSuccess;
  707. }
  708. // Return an empty set for the parent of all
  709. public static function GetRelationQueries($sRelCode)
  710. {
  711. return array();
  712. }
  713. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  714. {
  715. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  716. {
  717. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  718. $sQuery = $aQueryInfo["sQuery"];
  719. $bPropagate = $aQueryInfo["bPropagate"];
  720. $iDistance = $aQueryInfo["iDistance"];
  721. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  722. $oFlt = DBObjectSearch::FromSibusQL($sQuery, array(), $this);
  723. $oObjSet = new DBObjectSet($oFlt);
  724. while ($oObj = $oObjSet->Fetch())
  725. {
  726. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  727. $sObjKey = $oObj->GetKey();
  728. if (array_key_exists($sRootClass, $aResults))
  729. {
  730. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  731. {
  732. continue; // already visited, skip
  733. }
  734. }
  735. $aResults[$sRootClass][$sObjKey] = $oObj;
  736. if ($iDepth > 0)
  737. {
  738. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  739. }
  740. }
  741. }
  742. return $aResults;
  743. }
  744. }
  745. ?>