dbobject.class.php 31 KB

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