dbobject.class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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. return $this->Get($sStateAttCode);
  406. return MetaModel::GetStateLabel(get_class($this), $sStateAttCode);
  407. }
  408. }
  409. public function GetStateLabel()
  410. {
  411. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  412. if (empty($sStateAttCode))
  413. {
  414. return '';
  415. }
  416. else
  417. {
  418. $sStateValue = $this->Get($sStateAttCode);
  419. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  420. }
  421. }
  422. public function GetStateDescription()
  423. {
  424. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  425. if (empty($sStateAttCode))
  426. {
  427. return '';
  428. }
  429. else
  430. {
  431. $sStateValue = $this->Get($sStateAttCode);
  432. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  433. }
  434. }
  435. /**
  436. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  437. * for the given attribute in the current state of the object
  438. * @param string $sAttCode The code of the attribute
  439. * @return integer Flags: the binary combination of the flags applicable to this attribute
  440. */
  441. public function GetAttributeFlags($sAttCode)
  442. {
  443. $iFlags = 0; // By default (if no life cycle) no flag at all
  444. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  445. if (!empty($sStateAttCode))
  446. {
  447. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  448. }
  449. return $iFlags;
  450. }
  451. // check if the given (or current) value is suitable for the attribute
  452. public function CheckValue($sAttCode, $value = null)
  453. {
  454. if (!is_null($value))
  455. {
  456. $toCheck = $value;
  457. }
  458. else
  459. {
  460. $toCheck = $this->Get($sAttCode);
  461. }
  462. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  463. if ($oAtt->IsExternalKey())
  464. {
  465. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  466. {
  467. try
  468. {
  469. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  470. return true;
  471. }
  472. catch (CoreException $e)
  473. {
  474. return false;
  475. }
  476. }
  477. }
  478. elseif ($oAtt->IsWritable() && $oAtt->IsScalar())
  479. {
  480. $aValues = $oAtt->GetAllowedValues();
  481. if (count($aValues) > 0)
  482. {
  483. if (!array_key_exists($toCheck, $aValues))
  484. {
  485. return false;
  486. }
  487. }
  488. }
  489. return true;
  490. }
  491. // check attributes together
  492. public function CheckConsistency()
  493. {
  494. return true;
  495. }
  496. // check if it is allowed to record the new object into the database
  497. // a displayable error is returned
  498. // Note: checks the values and consistency
  499. public function CheckToInsert()
  500. {
  501. $aIssues = array();
  502. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  503. {
  504. if (!$this->CheckValue($sAttCode))
  505. {
  506. $aIssues[$sAttCode] = array(
  507. 'issue' => 'unexpected value'
  508. );
  509. }
  510. }
  511. if (count($aIssues) > 0)
  512. {
  513. return array(false, $aIssues);
  514. }
  515. if (!$this->CheckConsistency())
  516. {
  517. return array(false, $aIssues);
  518. }
  519. return array(true, $aIssues);
  520. }
  521. // check if it is allowed to update the existing object into the database
  522. // a displayable error is returned
  523. // Note: checks the values and consistency
  524. public function CheckToUpdate()
  525. {
  526. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  527. {
  528. if (!$this->CheckValue($sAttCode)) return false;
  529. }
  530. if (!$this->CheckConsistency()) return false;
  531. return true;
  532. }
  533. // check if it is allowed to delete the existing object from the database
  534. // a displayable error is returned
  535. public function CheckToDelete()
  536. {
  537. return true;
  538. }
  539. protected function ListChangedValues(array $aProposal)
  540. {
  541. $aDelta = array();
  542. foreach ($aProposal as $sAtt => $proposedValue)
  543. {
  544. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  545. {
  546. // The value was not set
  547. $aDelta[$sAtt] = $proposedValue;
  548. }
  549. elseif(is_object($proposedValue))
  550. {
  551. // The value is an object, the comparison is not strict
  552. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  553. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  554. {
  555. $aDelta[$sAtt] = $proposedValue;
  556. }
  557. }
  558. else
  559. {
  560. // The value is a scalar, the comparison must be 100% strict
  561. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  562. {
  563. //echo "$sAtt:<pre>\n";
  564. //var_dump($this->m_aOrigValues[$sAtt]);
  565. //var_dump($proposedValue);
  566. //echo "</pre>\n";
  567. $aDelta[$sAtt] = $proposedValue;
  568. }
  569. }
  570. }
  571. return $aDelta;
  572. }
  573. // List the attributes that have been changed
  574. // Returns an array of attname => currentvalue
  575. public function ListChanges()
  576. {
  577. return $this->ListChangedValues($this->m_aCurrValues);
  578. }
  579. // Tells whether or not an object was modified
  580. public function IsModified()
  581. {
  582. $aChanges = $this->ListChanges();
  583. return (count($aChanges) != 0);
  584. }
  585. // used both by insert/update
  586. private function DBWriteLinks()
  587. {
  588. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  589. {
  590. if (!$oAttDef->IsLinkSet()) continue;
  591. $oLinks = $this->Get($sAttCode);
  592. $oLinks->Rewind();
  593. while ($oLinkedObject = $oLinks->Fetch())
  594. {
  595. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  596. if ($oLinkedObject->IsModified())
  597. {
  598. $oLinkedObject->DBWrite();
  599. }
  600. }
  601. // Delete the objects that were initialy present and disappeared from the list
  602. // (if any)
  603. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  604. if ($oOriginalSet != null)
  605. {
  606. $aOriginalList = $oOriginalSet->ToArray();
  607. $aNewSet = $oLinks->ToArray();
  608. $aToDelete = array_diff($aOriginalList, $aNewSet);
  609. foreach ($aToDelete as $iKey => $oObject)
  610. {
  611. $oObject->DBDelete();
  612. }
  613. }
  614. }
  615. }
  616. private function DBInsertSingleTable($sTableClass)
  617. {
  618. $sClass = get_class($this);
  619. // fields in first array, values in the second
  620. $aFieldsToWrite = array();
  621. $aValuesToWrite = array();
  622. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  623. {
  624. // Add it to the list of fields to write
  625. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  626. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  627. }
  628. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  629. {
  630. // Skip this attribute if not defined in this table
  631. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  632. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  633. foreach($aAttColumns as $sColumn => $sValue)
  634. {
  635. $aFieldsToWrite[] = "`$sColumn`";
  636. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  637. }
  638. }
  639. if (count($aValuesToWrite) == 0) return false;
  640. $sTable = MetaModel::DBGetTable($sTableClass);
  641. $sInsertSQL = "INSERT INTO $sTable (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  642. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  643. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  644. if (empty($this->m_iKey))
  645. {
  646. // Take the autonumber
  647. $this->m_iKey = $iNewKey;
  648. }
  649. return $this->m_iKey;
  650. }
  651. // To be optionaly overloaded
  652. public function OnInsert()
  653. {
  654. }
  655. // Insert of record for the new object into the database
  656. // Returns the key of the newly created object
  657. public function DBInsertNoReload()
  658. {
  659. if ($this->m_bIsInDB)
  660. {
  661. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  662. }
  663. $sClass = get_class($this);
  664. $sRootClass = MetaModel::GetRootClass($sClass);
  665. // Ensure the update of the values (we are accessing the data directly)
  666. $this->ComputeFields();
  667. $this->OnInsert();
  668. if ($this->m_iKey < 0)
  669. {
  670. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  671. $this->m_iKey = null;
  672. }
  673. // If not automatically computed, then check that the key is given by the caller
  674. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  675. {
  676. if (empty($this->m_iKey))
  677. {
  678. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  679. }
  680. }
  681. // First query built upon on the root class, because the ID must be created first
  682. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  683. // Then do the leaf class, if different from the root class
  684. if ($sClass != $sRootClass)
  685. {
  686. $this->DBInsertSingleTable($sClass);
  687. }
  688. // Then do the other classes
  689. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  690. {
  691. if ($sParentClass == $sRootClass) continue;
  692. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  693. $this->DBInsertSingleTable($sParentClass);
  694. }
  695. $this->DBWriteLinks();
  696. $this->m_bIsInDB = true;
  697. // Activate any existing trigger
  698. $sClass = get_class($this);
  699. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  700. while ($oTrigger = $oSet->Fetch())
  701. {
  702. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  703. {
  704. $oTrigger->DoActivate($this->ToArgs('this'));
  705. }
  706. }
  707. return $this->m_iKey;
  708. }
  709. public function DBInsert()
  710. {
  711. $this->DBInsertNoReload();
  712. $this->m_bDirty = false;
  713. $this->Reload();
  714. return $this->m_iKey;
  715. }
  716. // Creates a copy of the current object into the database
  717. // Returns the id of the newly created object
  718. public function DBClone($iNewKey = null)
  719. {
  720. $this->m_bIsInDB = false;
  721. $this->m_iKey = $iNewKey;
  722. return $this->DBInsert();
  723. }
  724. // Update a record
  725. public function DBUpdate()
  726. {
  727. if (!$this->m_bIsInDB)
  728. {
  729. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  730. }
  731. $aChanges = $this->ListChanges();
  732. if (count($aChanges) == 0)
  733. {
  734. throw new CoreWarning("Attempting to update an unchanged object");
  735. return;
  736. }
  737. $bHasANewExternalKeyValue = false;
  738. foreach($aChanges as $sAttCode => $valuecurr)
  739. {
  740. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  741. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  742. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  743. }
  744. // Update scalar attributes
  745. if (count($aChanges) != 0)
  746. {
  747. $oFilter = new DBObjectSearch(get_class($this));
  748. $oFilter->AddCondition('id', $this->m_iKey, '=');
  749. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  750. CMDBSource::Query($sSQL);
  751. }
  752. $this->DBWriteLinks();
  753. $this->m_bDirty = false;
  754. // Reload to get the external attributes
  755. if ($bHasANewExternalKeyValue)
  756. {
  757. $this->Reload();
  758. }
  759. return $this->m_iKey;
  760. }
  761. // Make the current changes persistent - clever wrapper for Insert or Update
  762. public function DBWrite()
  763. {
  764. if ($this->m_bIsInDB)
  765. {
  766. return $this->DBUpdate();
  767. }
  768. else
  769. {
  770. return $this->DBInsert();
  771. }
  772. }
  773. // Delete a record
  774. public function DBDelete()
  775. {
  776. $oFilter = new DBObjectSearch(get_class($this));
  777. $oFilter->AddCondition('id', $this->m_iKey, '=');
  778. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  779. CMDBSource::Query($sSQL);
  780. $this->m_bIsInDB = false;
  781. $this->m_iKey = null;
  782. }
  783. public function EnumTransitions()
  784. {
  785. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  786. if (empty($sStateAttCode)) return array();
  787. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  788. return MetaModel::EnumTransitions(get_class($this), $sState);
  789. }
  790. public function ApplyStimulus($sStimulusCode)
  791. {
  792. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  793. if (empty($sStateAttCode)) return false;
  794. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  795. $aStateTransitions = $this->EnumTransitions();
  796. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  797. // Change the state before proceeding to the actions, this is necessary because an action might
  798. // trigger another stimuli (alternative: push the stimuli into a queue)
  799. $sPreviousState = $this->Get($sStateAttCode);
  800. $sNewState = $aTransitionDef['target_state'];
  801. $this->Set($sStateAttCode, $sNewState);
  802. // $aTransitionDef is an
  803. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  804. $bSuccess = true;
  805. foreach ($aTransitionDef['actions'] as $sActionHandler)
  806. {
  807. // std PHP spec
  808. $aActionCallSpec = array($this, $sActionHandler);
  809. if (!is_callable($aActionCallSpec))
  810. {
  811. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  812. return;
  813. }
  814. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  815. // if one call fails, the whole is considered as failed
  816. if (!$bRet) $bSuccess = false;
  817. }
  818. // Change state triggers...
  819. $sClass = get_class($this);
  820. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class='$sClass' AND t.state='$sPreviousState'"));
  821. while ($oTrigger = $oSet->Fetch())
  822. {
  823. $oTrigger->DoActivate($this->ToArgs('this'));
  824. }
  825. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class='$sClass' AND t.state='$sNewState'"));
  826. while ($oTrigger = $oSet->Fetch())
  827. {
  828. $oTrigger->DoActivate($this->ToArgs('this'));
  829. }
  830. return $bSuccess;
  831. }
  832. // Make standard context arguments
  833. public function ToArgs($sArgName = 'this')
  834. {
  835. $aScalarArgs = array();
  836. $aScalarArgs[$sArgName] = $this->GetKey();
  837. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  838. $aScalarArgs[$sArgName.'->object()'] = $this;
  839. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  840. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  841. $sClass = get_class($this);
  842. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  843. {
  844. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  845. }
  846. return $aScalarArgs;
  847. }
  848. // Return an empty set for the parent of all
  849. public static function GetRelationQueries($sRelCode)
  850. {
  851. return array();
  852. }
  853. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  854. {
  855. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  856. {
  857. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  858. $sQuery = $aQueryInfo["sQuery"];
  859. $bPropagate = $aQueryInfo["bPropagate"];
  860. $iDistance = $aQueryInfo["iDistance"];
  861. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  862. $oFlt = DBObjectSearch::FromOQL($sQuery);
  863. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  864. while ($oObj = $oObjSet->Fetch())
  865. {
  866. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  867. $sObjKey = $oObj->GetKey();
  868. if (array_key_exists($sRootClass, $aResults))
  869. {
  870. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  871. {
  872. continue; // already visited, skip
  873. }
  874. }
  875. $aResults[$sRootClass][$sObjKey] = $oObj;
  876. if ($iDepth > 0)
  877. {
  878. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  879. }
  880. }
  881. }
  882. return $aResults;
  883. }
  884. public function GetReferencingObjects()
  885. {
  886. $aDependentObjects = array();
  887. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  888. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  889. {
  890. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  891. {
  892. // skip if this external key is behind an external field
  893. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  894. $oSearch = new DBObjectSearch($sRemoteClass);
  895. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey());
  896. $oSet = new CMDBObjectSet($oSearch);
  897. if ($oSet->Count() > 0)
  898. {
  899. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  900. 'attribute' => $oExtKeyAttDef,
  901. 'objects' => $oSet,
  902. );
  903. }
  904. }
  905. }
  906. return $aDependentObjects;
  907. }
  908. public function GetDeletionScheme()
  909. {
  910. $aDependentObjects = $this->GetReferencingObjects();
  911. $aDeletedObjs = array(); // [class][key] => structure
  912. $aResetedObjs = array(); // [class][key] => object
  913. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  914. {
  915. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  916. {
  917. $oAttDef = $aData['attribute'];
  918. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  919. $oDepSet = $aData['objects'];
  920. $oDepSet->Rewind();
  921. while ($oDependentObj = $oDepSet->fetch())
  922. {
  923. $iId = $oDependentObj->GetKey();
  924. if ($oAttDef->IsNullAllowed())
  925. {
  926. // Optional external key, list to reset
  927. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  928. {
  929. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  930. }
  931. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  932. }
  933. else
  934. {
  935. // Mandatory external key, list to delete
  936. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  937. {
  938. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  939. if ($iCurrentOption == DEL_AUTO)
  940. {
  941. // be conservative, take the new option
  942. // (DEL_MANUAL has precedence over DEL_AUTO)
  943. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  944. }
  945. else
  946. {
  947. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  948. }
  949. }
  950. else
  951. {
  952. // First time we find the given object in the list
  953. // (and most likely case is that no other occurence will be found)
  954. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  955. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  956. }
  957. }
  958. }
  959. }
  960. }
  961. return array($aDeletedObjs, $aResetedObjs);
  962. }
  963. }
  964. ?>