dbobject.class.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. private $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 (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  193. {
  194. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  195. }
  196. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  197. if ($this->m_bIsInDB && !$this->m_bFullyLoaded)
  198. {
  199. // First time Set is called... ensure that the object gets fully loaded
  200. // Otherwise we would lose the values on a further Reload
  201. // + consistency does not make sense !
  202. $this->Reload();
  203. }
  204. if($oAttDef->IsScalar() && !$oAttDef->IsNullAllowed() && is_null($value))
  205. {
  206. throw new CoreWarning("null not allowed for attribute '$sAttCode', setting default value");
  207. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  208. return;
  209. }
  210. if ($oAttDef->IsExternalKey() && is_object($value))
  211. {
  212. // Setting an external key with a whole object (instead of just an ID)
  213. // let's initialize also the external fields that depend on it
  214. // (useful when building objects in memory and not from a query)
  215. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  216. {
  217. 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");
  218. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  219. }
  220. else
  221. {
  222. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  223. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  224. {
  225. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  226. {
  227. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  228. }
  229. }
  230. }
  231. return;
  232. }
  233. if(!$oAttDef->IsScalar() && !is_object($value))
  234. {
  235. throw new CoreWarning("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  236. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  237. return;
  238. }
  239. if($oAttDef->IsLinkSet())
  240. {
  241. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  242. {
  243. throw new CoreWarning("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  244. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  245. return;
  246. }
  247. $oObjectSet = $value;
  248. $sSetClass = $oObjectSet->GetClass();
  249. $sLinkClass = $oAttDef->GetLinkedClass();
  250. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  251. if ($sSetClass != $sLinkClass)
  252. {
  253. throw new CoreWarning("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  254. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  255. return;
  256. }
  257. }
  258. $this->m_aCurrValues[$sAttCode] = $oAttDef->MakeRealValue($value);
  259. }
  260. public function Get($sAttCode)
  261. {
  262. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  263. {
  264. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  265. }
  266. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode])
  267. {
  268. // #@# non-scalar attributes.... handle that differentely
  269. $this->Reload();
  270. }
  271. $this->ComputeFields();
  272. return $this->m_aCurrValues[$sAttCode];
  273. }
  274. public function GetOriginal($sAttCode)
  275. {
  276. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  277. {
  278. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  279. }
  280. return $this->m_aOrigValues[$sAttCode];
  281. }
  282. public function ComputeFields()
  283. {
  284. if (is_callable(array($this, 'ComputeValues')))
  285. {
  286. // First check that we are not currently computing the fields
  287. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  288. foreach (debug_backtrace() as $aCallInfo)
  289. {
  290. if (!array_key_exists("class", $aCallInfo)) continue;
  291. if ($aCallInfo["class"] != get_class($this)) continue;
  292. if ($aCallInfo["function"] != "ComputeValues") continue;
  293. return; //skip!
  294. }
  295. $this->ComputeValues();
  296. }
  297. }
  298. public function GetAsHTML($sAttCode)
  299. {
  300. $sClass = get_class($this);
  301. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  302. $aExtKeyFriends = MetaModel::GetExtKeyFriends($sClass, $sAttCode);
  303. if (count($aExtKeyFriends) > 0)
  304. {
  305. // This attribute is an ext key (in this class or in another class)
  306. // The corresponding value is an id of the remote object
  307. // Let's try to use the corresponding external fields for a sexy display
  308. $aAvailableFields = array();
  309. foreach ($aExtKeyFriends as $sDispAttCode => $oExtField)
  310. {
  311. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  312. }
  313. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  314. $aMakeHLink = array(get_class($this), 'MakeHyperLink');
  315. if (is_callable($aMakeHLink))
  316. {
  317. return call_user_func($aMakeHLink, $sTargetClass, $this->Get($sAttCode), $aAvailableFields);
  318. }
  319. else
  320. {
  321. return $this->Get($sAttCode);
  322. }
  323. }
  324. // That's a standard attribute (might be an ext field or a direct field, etc.)
  325. return $oAtt->GetAsHTML($this->Get($sAttCode));
  326. }
  327. public function GetAsXML($sAttCode)
  328. {
  329. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  330. return $oAtt->GetAsXML($this->Get($sAttCode));
  331. }
  332. public function GetAsCSV($sAttCode, $sSeparator = ';', $sSepEscape = ',')
  333. {
  334. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  335. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sSepEscape);
  336. }
  337. // could be in the metamodel ?
  338. public static function IsValidPKey($value)
  339. {
  340. return ((string)$value === (string)(int)$value);
  341. }
  342. public function GetKey()
  343. {
  344. return $this->m_iKey;
  345. }
  346. public function SetKey($iNewKey)
  347. {
  348. if (!self::IsValidPKey($iNewKey))
  349. {
  350. throw new CoreException("An object id must be an integer value ($iNewKey)");
  351. }
  352. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  353. {
  354. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  355. }
  356. $this->m_iKey = $iNewKey;
  357. }
  358. public function GetName()
  359. {
  360. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  361. if (empty($sNameAttCode))
  362. {
  363. return $this->m_iKey;
  364. }
  365. else
  366. {
  367. return $this->Get($sNameAttCode);
  368. }
  369. }
  370. public function GetState()
  371. {
  372. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  373. if (empty($sStateAttCode))
  374. {
  375. return '';
  376. }
  377. else
  378. {
  379. $aStates = MetaModel::EnumStates(get_class($this));
  380. return $aStates[$this->Get($sStateAttCode)]['label'];
  381. }
  382. }
  383. /**
  384. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  385. * for the given attribute in the current state of the object
  386. * @param string $sAttCode The code of the attribute
  387. * @return integer Flags: the binary combination of the flags applicable to this attribute
  388. */
  389. public function GetAttributeFlags($sAttCode)
  390. {
  391. $iFlags = 0; // By default (if no life cycle) no flag at all
  392. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  393. if (!empty($sStateAttCode))
  394. {
  395. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  396. }
  397. return $iFlags;
  398. }
  399. // check if the given (or current) value is suitable for the attribute
  400. public function CheckValue($sAttCode, $value = null)
  401. {
  402. if (!is_null($value))
  403. {
  404. $toCheck = $value;
  405. }
  406. else
  407. {
  408. $toCheck = $this->Get($sAttCode);
  409. }
  410. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  411. if ($oAtt->IsExternalKey())
  412. {
  413. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  414. {
  415. try
  416. {
  417. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  418. return true;
  419. }
  420. catch (CoreException $e)
  421. {
  422. return false;
  423. }
  424. }
  425. }
  426. return true;
  427. }
  428. // check attributes together
  429. public function CheckConsistency()
  430. {
  431. return true;
  432. }
  433. // check if it is allowed to record the new object into the database
  434. // a displayable error is returned
  435. // Note: checks the values and consistency
  436. public function CheckToInsert()
  437. {
  438. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  439. {
  440. if (!$this->CheckValue($sAttCode)) return false;
  441. }
  442. if (!$this->CheckConsistency()) return false;
  443. return true;
  444. }
  445. // check if it is allowed to update the existing object into the database
  446. // a displayable error is returned
  447. // Note: checks the values and consistency
  448. public function CheckToUpdate()
  449. {
  450. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  451. {
  452. if (!$this->CheckValue($sAttCode)) return false;
  453. }
  454. if (!$this->CheckConsistency()) return false;
  455. return true;
  456. }
  457. // check if it is allowed to delete the existing object from the database
  458. // a displayable error is returned
  459. public function CheckToDelete()
  460. {
  461. return true;
  462. }
  463. protected function ListChangedValues(array $aProposal)
  464. {
  465. $aDelta = array();
  466. foreach ($aProposal as $sAtt => $proposedValue)
  467. {
  468. if (!array_key_exists($sAtt, $this->m_aOrigValues) || ($this->m_aOrigValues[$sAtt] != $proposedValue))
  469. {
  470. $aDelta[$sAtt] = $proposedValue;
  471. }
  472. }
  473. return $aDelta;
  474. }
  475. // List the attributes that have been changed
  476. // Returns an array of attname => currentvalue
  477. public function ListChanges()
  478. {
  479. return $this->ListChangedValues($this->m_aCurrValues);
  480. }
  481. // used both by insert/update
  482. private function DBWriteLinks()
  483. {
  484. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  485. {
  486. if (!$oAttDef->IsLinkSet()) continue;
  487. $oLinks = $this->Get($sAttCode);
  488. $oLinks->Rewind();
  489. while ($oLinkedObject = $oLinks->Fetch())
  490. {
  491. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  492. $oLinkedObject->DBWrite();
  493. }
  494. // Delete the objects that were initialy present and disappeared from the list
  495. // (if any)
  496. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  497. if ($oOriginalSet != null)
  498. {
  499. $aOriginalList = $oOriginalSet->ToArray();
  500. $aNewSet = $oLinks->ToArray();
  501. $aToDelete = array_diff($aOriginalList, $aNewSet);
  502. foreach ($aToDelete as $iKey => $oObject)
  503. {
  504. $oObject->DBDelete();
  505. }
  506. }
  507. }
  508. }
  509. private function DBInsertSingleTable($sTableClass)
  510. {
  511. $sClass = get_class($this);
  512. // fields in first array, values in the second
  513. $aFieldsToWrite = array();
  514. $aValuesToWrite = array();
  515. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  516. {
  517. // Add it to the list of fields to write
  518. $aFieldsToWrite[] = MetaModel::DBGetKey($sTableClass);
  519. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  520. }
  521. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  522. {
  523. // Skip this attribute if not defined in this table
  524. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  525. if ($oAttDef->IsDirectField())
  526. {
  527. $aFieldsToWrite[] = $oAttDef->GetSQLExpr();
  528. $aValuesToWrite[] = CMDBSource::Quote($oAttDef->RealValueToSQLValue($this->m_aCurrValues[$sAttCode]));
  529. }
  530. }
  531. if (count($aValuesToWrite) == 0) return false;
  532. $sTable = MetaModel::DBGetTable($sTableClass);
  533. $sInsertSQL = "INSERT INTO $sTable (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  534. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  535. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  536. if (empty($this->m_iKey))
  537. {
  538. // Take the autonumber
  539. $this->m_iKey = $iNewKey;
  540. }
  541. return $this->m_iKey;
  542. }
  543. // Insert of record for the new object into the database
  544. // Returns the key of the newly created object
  545. public function DBInsertNoReload()
  546. {
  547. if ($this->m_bIsInDB)
  548. {
  549. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  550. }
  551. $sClass = get_class($this);
  552. $sRootClass = MetaModel::GetRootClass($sClass);
  553. // Ensure the update of the values (we are accessing the data directly)
  554. $this->ComputeFields();
  555. if ($this->m_iKey < 0)
  556. {
  557. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  558. $this->m_iKey = null;
  559. }
  560. // If not automatically computed, then check that the key is given by the caller
  561. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  562. {
  563. if (empty($this->m_iKey))
  564. {
  565. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  566. }
  567. }
  568. // First query built upon on the root class, because the ID must be created first
  569. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  570. // Then do the leaf class, if different from the root class
  571. if ($sClass != $sRootClass)
  572. {
  573. $this->DBInsertSingleTable($sClass);
  574. }
  575. // Then do the other classes
  576. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  577. {
  578. if ($sParentClass == $sRootClass) continue;
  579. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  580. $this->DBInsertSingleTable($sParentClass);
  581. }
  582. $this->DBWriteLinks();
  583. // Reload to update the external attributes
  584. $this->m_bIsInDB = true;
  585. return $this->m_iKey;
  586. }
  587. public function DBInsert()
  588. {
  589. $this->DBInsertNoReload();
  590. $this->Reload();
  591. return $this->m_iKey;
  592. }
  593. // Creates a copy of the current object into the database
  594. // Returns the id of the newly created object
  595. public function DBClone($iNewKey = null)
  596. {
  597. $this->m_bIsInDB = false;
  598. $this->m_iKey = $iNewKey;
  599. return $this->DBInsert();
  600. }
  601. // Update a record
  602. public function DBUpdate()
  603. {
  604. if (!$this->m_bIsInDB)
  605. {
  606. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  607. }
  608. $aChanges = $this->ListChanges();
  609. if (count($aChanges) == 0)
  610. {
  611. throw new CoreWarning("Attempting to update an unchanged object");
  612. return;
  613. }
  614. $bHasANewExternalKeyValue = false;
  615. foreach($aChanges as $sAttCode => $valuecurr)
  616. {
  617. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  618. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  619. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  620. }
  621. // Update scalar attributes
  622. if (count($aChanges) != 0)
  623. {
  624. $oFilter = new DBObjectSearch(get_class($this));
  625. $oFilter->AddCondition('id', $this->m_iKey, '=');
  626. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  627. CMDBSource::Query($sSQL);
  628. }
  629. $this->DBWriteLinks();
  630. // Reload to get the external attributes
  631. if ($bHasANewExternalKeyValue) $this->Reload();
  632. return $this->m_iKey;
  633. }
  634. // Make the current changes persistent - clever wrapper for Insert or Update
  635. public function DBWrite()
  636. {
  637. if ($this->m_bIsInDB)
  638. {
  639. return $this->DBUpdate();
  640. }
  641. else
  642. {
  643. return $this->DBInsert();
  644. }
  645. }
  646. // Delete a record
  647. public function DBDelete()
  648. {
  649. $oFilter = new DBObjectSearch(get_class($this));
  650. $oFilter->AddCondition('id', $this->m_iKey, '=');
  651. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  652. CMDBSource::Query($sSQL);
  653. $this->m_bIsInDB = false;
  654. $this->m_iKey = null;
  655. }
  656. public function EnumTransitions()
  657. {
  658. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  659. if (empty($sStateAttCode)) return array();
  660. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  661. return MetaModel::EnumTransitions(get_class($this), $sState);
  662. }
  663. public function ApplyStimulus($sStimulusCode)
  664. {
  665. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  666. if (empty($sStateAttCode)) return false;
  667. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  668. $aStateTransitions = $this->EnumTransitions();
  669. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  670. // Change the state before proceeding to the actions, this is necessary because an action might
  671. // trigger another stimuli (alternative: push the stimuli into a queue)
  672. $this->Set($sStateAttCode, $aTransitionDef['target_state']);
  673. // $aTransitionDef is an
  674. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  675. $bSuccess = true;
  676. foreach ($aTransitionDef['actions'] as $sActionHandler)
  677. {
  678. // std PHP spec
  679. $aActionCallSpec = array($this, $sActionHandler);
  680. if (!is_callable($aActionCallSpec))
  681. {
  682. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  683. return;
  684. }
  685. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  686. // if one call fails, the whole is considered as failed
  687. if (!$bRet) $bSuccess = false;
  688. }
  689. return $bSuccess;
  690. }
  691. // Return an empty set for the parent of all
  692. public static function GetRelationQueries($sRelCode)
  693. {
  694. return array();
  695. }
  696. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  697. {
  698. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  699. {
  700. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  701. $sQuery = $aQueryInfo["sQuery"];
  702. $bPropagate = $aQueryInfo["bPropagate"];
  703. $iDistance = $aQueryInfo["iDistance"];
  704. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  705. $oFlt = DBObjectSearch::FromSibusQL($sQuery, array(), $this);
  706. $oObjSet = new DBObjectSet($oFlt);
  707. while ($oObj = $oObjSet->Fetch())
  708. {
  709. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  710. $sObjKey = $oObj->GetKey();
  711. if (array_key_exists($sRootClass, $aResults))
  712. {
  713. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  714. {
  715. continue; // already visited, skip
  716. }
  717. }
  718. $aResults[$sRootClass][$sObjKey] = $oObj;
  719. if ($iDepth > 0)
  720. {
  721. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  722. }
  723. }
  724. }
  725. return $aResults;
  726. }
  727. }
  728. ?>