dbobject.class.php 30 KB

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