dbobject.class.php 32 KB

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