dbobject.class.php 28 KB

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