dbobject.class.php 34 KB

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