dbobject.class.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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. if ($oAttDef->CheckValue($value))
  292. {
  293. $this->m_aCurrValues[$sAttCode] = $oAttDef->MakeRealValue($value);
  294. $this->RegisterAsDirty(); // Make sure we do not reload it anymore... before saving it
  295. }
  296. }
  297. public function Get($sAttCode)
  298. {
  299. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  300. {
  301. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  302. }
  303. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  304. {
  305. // #@# non-scalar attributes.... handle that differentely
  306. $this->Reload();
  307. }
  308. return $this->m_aCurrValues[$sAttCode];
  309. }
  310. public function GetOriginal($sAttCode)
  311. {
  312. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  313. {
  314. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  315. }
  316. return $this->m_aOrigValues[$sAttCode];
  317. }
  318. // Compute scalar attributes that depend on any other type of attribute
  319. public function DoComputeValues()
  320. {
  321. if (is_callable(array($this, 'ComputeValues')))
  322. {
  323. // First check that we are not currently computing the fields
  324. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  325. foreach (debug_backtrace() as $aCallInfo)
  326. {
  327. if (!array_key_exists("class", $aCallInfo)) continue;
  328. if ($aCallInfo["class"] != get_class($this)) continue;
  329. if ($aCallInfo["function"] != "ComputeValues") continue;
  330. return; //skip!
  331. }
  332. $this->ComputeValues();
  333. }
  334. }
  335. public function GetAsHTML($sAttCode)
  336. {
  337. $sClass = get_class($this);
  338. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  339. $aExtKeyFriends = MetaModel::GetExtKeyFriends($sClass, $sAttCode);
  340. if (count($aExtKeyFriends) > 0)
  341. {
  342. // This attribute is an ext key (in this class or in another class)
  343. // The corresponding value is an id of the remote object
  344. // Let's try to use the corresponding external fields for a sexy display
  345. $aAvailableFields = array();
  346. foreach ($aExtKeyFriends as $sDispAttCode => $oExtField)
  347. {
  348. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  349. }
  350. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  351. return $this->MakeHyperLink($sTargetClass, $this->Get($sAttCode), $aAvailableFields);
  352. }
  353. // That's a standard attribute (might be an ext field or a direct field, etc.)
  354. return $oAtt->GetAsHTML($this->Get($sAttCode));
  355. }
  356. public function GetEditValue($sAttCode)
  357. {
  358. $sClass = get_class($this);
  359. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  360. if ($oAtt->IsExternalKey())
  361. {
  362. $sTargetClass = $oAtt->GetTargetClass();
  363. if ($this->IsNew())
  364. {
  365. // The current object exists only in memory, don't try to query it in the DB !
  366. // instead let's query for the object pointed by the external key, and get its name
  367. $targetObjId = $this->Get($sAttCode);
  368. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  369. if (is_object($oTargetObj))
  370. {
  371. $sEditValue = $oTargetObj->GetName();
  372. }
  373. else
  374. {
  375. $sEditValue = 0;
  376. }
  377. }
  378. else
  379. {
  380. $aAvailableFields = array();
  381. // retrieve the "external fields" linked to this external key
  382. foreach (MetaModel::GetExternalFields(get_class($this), $sAttCode) as $oExtField)
  383. {
  384. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  385. }
  386. // Use the "name" of the target class as the label of the hyperlink
  387. // unless it's not available in the external fields...
  388. $sExtClassNameAtt = MetaModel::GetNameAttributeCode($sTargetClass);
  389. if (isset($aAvailableFields[$sExtClassNameAtt]))
  390. {
  391. $sEditValue = $aAvailableFields[$sExtClassNameAtt];
  392. }
  393. else
  394. {
  395. $sEditValue = implode(' / ', $aAvailableFields);
  396. }
  397. }
  398. }
  399. else
  400. {
  401. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  402. }
  403. return $sEditValue;
  404. }
  405. public function GetAsXML($sAttCode)
  406. {
  407. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  408. return $oAtt->GetAsXML($this->Get($sAttCode));
  409. }
  410. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  411. {
  412. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  413. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  414. }
  415. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  416. {
  417. if ($sObjKey == 0) return '<em>undefined</em>';
  418. return MetaModel::GetName($sObjClass)."::$sObjKey";
  419. }
  420. public function GetHyperlink()
  421. {
  422. $aAvailableFields[MetaModel::GetNameAttributeCode(get_class($this))] = $this->GetName();
  423. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $aAvailableFields);
  424. }
  425. // could be in the metamodel ?
  426. public static function IsValidPKey($value)
  427. {
  428. return ((string)$value === (string)(int)$value);
  429. }
  430. public function GetKey()
  431. {
  432. return $this->m_iKey;
  433. }
  434. public function SetKey($iNewKey)
  435. {
  436. if (!self::IsValidPKey($iNewKey))
  437. {
  438. throw new CoreException("An object id must be an integer value ($iNewKey)");
  439. }
  440. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  441. {
  442. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  443. }
  444. $this->m_iKey = $iNewKey;
  445. }
  446. public function GetIcon()
  447. {
  448. return MetaModel::GetClassIcon(get_class($this));
  449. }
  450. public function GetName()
  451. {
  452. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  453. if (empty($sNameAttCode))
  454. {
  455. return $this->m_iKey;
  456. }
  457. else
  458. {
  459. return $this->Get($sNameAttCode);
  460. }
  461. }
  462. public function GetState()
  463. {
  464. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  465. if (empty($sStateAttCode))
  466. {
  467. return '';
  468. }
  469. else
  470. {
  471. return $this->Get($sStateAttCode);
  472. }
  473. }
  474. public function GetStateLabel()
  475. {
  476. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  477. if (empty($sStateAttCode))
  478. {
  479. return '';
  480. }
  481. else
  482. {
  483. $sStateValue = $this->Get($sStateAttCode);
  484. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  485. }
  486. }
  487. public function GetStateDescription()
  488. {
  489. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  490. if (empty($sStateAttCode))
  491. {
  492. return '';
  493. }
  494. else
  495. {
  496. $sStateValue = $this->Get($sStateAttCode);
  497. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  498. }
  499. }
  500. /**
  501. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  502. * for the given attribute in the current state of the object
  503. * @param string $sAttCode The code of the attribute
  504. * @return integer Flags: the binary combination of the flags applicable to this attribute
  505. */
  506. public function GetAttributeFlags($sAttCode)
  507. {
  508. $iFlags = 0; // By default (if no life cycle) no flag at all
  509. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  510. if (!empty($sStateAttCode))
  511. {
  512. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  513. }
  514. return $iFlags;
  515. }
  516. // check if the given (or current) value is suitable for the attribute
  517. public function CheckValue($sAttCode, $value = null)
  518. {
  519. if (!is_null($value))
  520. {
  521. $toCheck = $value;
  522. }
  523. else
  524. {
  525. $toCheck = $this->Get($sAttCode);
  526. }
  527. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  528. if ($oAtt->IsExternalKey())
  529. {
  530. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  531. {
  532. try
  533. {
  534. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  535. return true;
  536. }
  537. catch (CoreException $e)
  538. {
  539. return false;
  540. }
  541. }
  542. }
  543. elseif ($oAtt->IsWritable() && $oAtt->IsScalar())
  544. {
  545. if (is_null($toCheck))
  546. {
  547. if ($oAtt->IsNullAllowed())
  548. {
  549. return true;
  550. }
  551. else
  552. {
  553. return false;
  554. }
  555. }
  556. $aValues = $oAtt->GetAllowedValues();
  557. if (count($aValues) > 0)
  558. {
  559. if (!array_key_exists($toCheck, $aValues))
  560. {
  561. return false;
  562. }
  563. }
  564. }
  565. return true;
  566. }
  567. // check attributes together
  568. public function CheckConsistency()
  569. {
  570. return true;
  571. }
  572. // check if it is allowed to record the new object into the database
  573. // a displayable error is returned
  574. // Note: checks the values and consistency
  575. public function CheckToInsert()
  576. {
  577. $aIssues = array();
  578. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  579. {
  580. if (!$this->CheckValue($sAttCode))
  581. {
  582. $aIssues[$sAttCode] = array(
  583. 'issue' => 'unexpected value'
  584. );
  585. }
  586. }
  587. if (count($aIssues) > 0)
  588. {
  589. return array(false, $aIssues);
  590. }
  591. if (!$this->CheckConsistency())
  592. {
  593. return array(false, $aIssues);
  594. }
  595. return array(true, $aIssues);
  596. }
  597. // check if it is allowed to update the existing object into the database
  598. // a displayable error is returned
  599. // Note: checks the values and consistency
  600. public function CheckToUpdate()
  601. {
  602. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  603. {
  604. if (!$this->CheckValue($sAttCode)) return false;
  605. }
  606. if (!$this->CheckConsistency()) return false;
  607. return true;
  608. }
  609. // check if it is allowed to delete the existing object from the database
  610. // a displayable error is returned
  611. public function CheckToDelete()
  612. {
  613. return true;
  614. }
  615. protected function ListChangedValues(array $aProposal)
  616. {
  617. $aDelta = array();
  618. foreach ($aProposal as $sAtt => $proposedValue)
  619. {
  620. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  621. {
  622. // The value was not set
  623. $aDelta[$sAtt] = $proposedValue;
  624. }
  625. elseif(is_object($proposedValue))
  626. {
  627. // The value is an object, the comparison is not strict
  628. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  629. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  630. {
  631. $aDelta[$sAtt] = $proposedValue;
  632. }
  633. }
  634. else
  635. {
  636. // The value is a scalar, the comparison must be 100% strict
  637. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  638. {
  639. //echo "$sAtt:<pre>\n";
  640. //var_dump($this->m_aOrigValues[$sAtt]);
  641. //var_dump($proposedValue);
  642. //echo "</pre>\n";
  643. $aDelta[$sAtt] = $proposedValue;
  644. }
  645. }
  646. }
  647. return $aDelta;
  648. }
  649. // List the attributes that have been changed
  650. // Returns an array of attname => currentvalue
  651. public function ListChanges()
  652. {
  653. return $this->ListChangedValues($this->m_aCurrValues);
  654. }
  655. // Tells whether or not an object was modified
  656. public function IsModified()
  657. {
  658. $aChanges = $this->ListChanges();
  659. return (count($aChanges) != 0);
  660. }
  661. // used both by insert/update
  662. private function DBWriteLinks()
  663. {
  664. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  665. {
  666. if (!$oAttDef->IsLinkSet()) continue;
  667. $oLinks = $this->Get($sAttCode);
  668. $oLinks->Rewind();
  669. while ($oLinkedObject = $oLinks->Fetch())
  670. {
  671. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  672. if ($oLinkedObject->IsModified())
  673. {
  674. $oLinkedObject->DBWrite();
  675. }
  676. }
  677. // Delete the objects that were initialy present and disappeared from the list
  678. // (if any)
  679. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  680. if ($oOriginalSet != null)
  681. {
  682. $aOriginalList = $oOriginalSet->ToArray();
  683. $aNewSet = $oLinks->ToArray();
  684. $aToDelete = array_diff($aOriginalList, $aNewSet);
  685. foreach ($aToDelete as $iKey => $oObject)
  686. {
  687. $oObject->DBDelete();
  688. }
  689. }
  690. }
  691. }
  692. private function DBInsertSingleTable($sTableClass)
  693. {
  694. $sTable = MetaModel::DBGetTable($sTableClass);
  695. // Abstract classes or classes having no specific attribute do not have an associated table
  696. if ($sTable == '') return;
  697. $sClass = get_class($this);
  698. // fields in first array, values in the second
  699. $aFieldsToWrite = array();
  700. $aValuesToWrite = array();
  701. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  702. {
  703. // Add it to the list of fields to write
  704. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  705. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  706. }
  707. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  708. {
  709. // Skip this attribute if not defined in this table
  710. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  711. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  712. foreach($aAttColumns as $sColumn => $sValue)
  713. {
  714. $aFieldsToWrite[] = "`$sColumn`";
  715. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  716. }
  717. }
  718. if (count($aValuesToWrite) == 0) return false;
  719. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  720. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  721. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  722. if (empty($this->m_iKey))
  723. {
  724. // Take the autonumber
  725. $this->m_iKey = $iNewKey;
  726. }
  727. return $this->m_iKey;
  728. }
  729. // To be optionaly overloaded
  730. protected function OnInsert()
  731. {
  732. }
  733. // Insert of record for the new object into the database
  734. // Returns the key of the newly created object
  735. public function DBInsertNoReload()
  736. {
  737. if ($this->m_bIsInDB)
  738. {
  739. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  740. }
  741. $sClass = get_class($this);
  742. $sRootClass = MetaModel::GetRootClass($sClass);
  743. // Ensure the update of the values (we are accessing the data directly)
  744. $this->DoComputeValues();
  745. $this->OnInsert();
  746. if ($this->m_iKey < 0)
  747. {
  748. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  749. $this->m_iKey = null;
  750. }
  751. // If not automatically computed, then check that the key is given by the caller
  752. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  753. {
  754. if (empty($this->m_iKey))
  755. {
  756. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  757. }
  758. }
  759. // First query built upon on the root class, because the ID must be created first
  760. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  761. // Then do the leaf class, if different from the root class
  762. if ($sClass != $sRootClass)
  763. {
  764. $this->DBInsertSingleTable($sClass);
  765. }
  766. // Then do the other classes
  767. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  768. {
  769. if ($sParentClass == $sRootClass) continue;
  770. $this->DBInsertSingleTable($sParentClass);
  771. }
  772. $this->DBWriteLinks();
  773. $this->m_bIsInDB = true;
  774. // Activate any existing trigger
  775. $sClass = get_class($this);
  776. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  777. while ($oTrigger = $oSet->Fetch())
  778. {
  779. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  780. {
  781. $oTrigger->DoActivate($this->ToArgs('this'));
  782. }
  783. }
  784. return $this->m_iKey;
  785. }
  786. public function DBInsert()
  787. {
  788. $this->DBInsertNoReload();
  789. $this->m_bDirty = false;
  790. $this->Reload();
  791. return $this->m_iKey;
  792. }
  793. // Creates a copy of the current object into the database
  794. // Returns the id of the newly created object
  795. public function DBClone($iNewKey = null)
  796. {
  797. $this->m_bIsInDB = false;
  798. $this->m_iKey = $iNewKey;
  799. return $this->DBInsert();
  800. }
  801. // To be optionaly overloaded
  802. protected function OnUpdate()
  803. {
  804. }
  805. // Update a record
  806. public function DBUpdate()
  807. {
  808. if (!$this->m_bIsInDB)
  809. {
  810. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  811. }
  812. $this->DoComputeValues();
  813. $this->OnUpdate();
  814. $aChanges = $this->ListChanges();
  815. if (count($aChanges) == 0)
  816. {
  817. throw new CoreWarning("Attempting to update an unchanged object");
  818. return;
  819. }
  820. $bHasANewExternalKeyValue = false;
  821. foreach($aChanges as $sAttCode => $valuecurr)
  822. {
  823. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  824. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  825. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  826. }
  827. // Update scalar attributes
  828. if (count($aChanges) != 0)
  829. {
  830. $oFilter = new DBObjectSearch(get_class($this));
  831. $oFilter->AddCondition('id', $this->m_iKey, '=');
  832. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  833. CMDBSource::Query($sSQL);
  834. }
  835. $this->DBWriteLinks();
  836. $this->m_bDirty = false;
  837. // Reload to get the external attributes
  838. if ($bHasANewExternalKeyValue)
  839. {
  840. $this->Reload();
  841. }
  842. return $this->m_iKey;
  843. }
  844. // Make the current changes persistent - clever wrapper for Insert or Update
  845. public function DBWrite()
  846. {
  847. if ($this->m_bIsInDB)
  848. {
  849. return $this->DBUpdate();
  850. }
  851. else
  852. {
  853. return $this->DBInsert();
  854. }
  855. }
  856. // Delete a record
  857. public function DBDelete()
  858. {
  859. $oFilter = new DBObjectSearch(get_class($this));
  860. $oFilter->AddCondition('id', $this->m_iKey, '=');
  861. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  862. CMDBSource::Query($sSQL);
  863. $this->m_bIsInDB = false;
  864. $this->m_iKey = null;
  865. }
  866. public function EnumTransitions()
  867. {
  868. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  869. if (empty($sStateAttCode)) return array();
  870. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  871. return MetaModel::EnumTransitions(get_class($this), $sState);
  872. }
  873. public function ApplyStimulus($sStimulusCode)
  874. {
  875. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  876. if (empty($sStateAttCode)) return false;
  877. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  878. $aStateTransitions = $this->EnumTransitions();
  879. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  880. // Change the state before proceeding to the actions, this is necessary because an action might
  881. // trigger another stimuli (alternative: push the stimuli into a queue)
  882. $sPreviousState = $this->Get($sStateAttCode);
  883. $sNewState = $aTransitionDef['target_state'];
  884. $this->Set($sStateAttCode, $sNewState);
  885. // $aTransitionDef is an
  886. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  887. $bSuccess = true;
  888. foreach ($aTransitionDef['actions'] as $sActionHandler)
  889. {
  890. // std PHP spec
  891. $aActionCallSpec = array($this, $sActionHandler);
  892. if (!is_callable($aActionCallSpec))
  893. {
  894. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  895. return;
  896. }
  897. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  898. // if one call fails, the whole is considered as failed
  899. if (!$bRet) $bSuccess = false;
  900. }
  901. // Change state triggers...
  902. $sClass = get_class($this);
  903. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class='$sClass' AND t.state='$sPreviousState'"));
  904. while ($oTrigger = $oSet->Fetch())
  905. {
  906. $oTrigger->DoActivate($this->ToArgs('this'));
  907. }
  908. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class='$sClass' AND t.state='$sNewState'"));
  909. while ($oTrigger = $oSet->Fetch())
  910. {
  911. $oTrigger->DoActivate($this->ToArgs('this'));
  912. }
  913. return $bSuccess;
  914. }
  915. // Make standard context arguments
  916. public function ToArgs($sArgName = 'this')
  917. {
  918. $aScalarArgs = array();
  919. $aScalarArgs[$sArgName] = $this->GetKey();
  920. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  921. $aScalarArgs[$sArgName.'->object()'] = $this;
  922. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  923. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  924. $sClass = get_class($this);
  925. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  926. {
  927. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  928. }
  929. return $aScalarArgs;
  930. }
  931. // Return an empty set for the parent of all
  932. public static function GetRelationQueries($sRelCode)
  933. {
  934. return array();
  935. }
  936. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  937. {
  938. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  939. {
  940. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  941. $sQuery = $aQueryInfo["sQuery"];
  942. $bPropagate = $aQueryInfo["bPropagate"];
  943. $iDistance = $aQueryInfo["iDistance"];
  944. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  945. $oFlt = DBObjectSearch::FromOQL($sQuery);
  946. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  947. while ($oObj = $oObjSet->Fetch())
  948. {
  949. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  950. $sObjKey = $oObj->GetKey();
  951. if (array_key_exists($sRootClass, $aResults))
  952. {
  953. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  954. {
  955. continue; // already visited, skip
  956. }
  957. }
  958. $aResults[$sRootClass][$sObjKey] = $oObj;
  959. if ($iDepth > 0)
  960. {
  961. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  962. }
  963. }
  964. }
  965. return $aResults;
  966. }
  967. public function GetReferencingObjects()
  968. {
  969. $aDependentObjects = array();
  970. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  971. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  972. {
  973. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  974. {
  975. // skip if this external key is behind an external field
  976. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  977. $oSearch = new DBObjectSearch($sRemoteClass);
  978. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  979. $oSet = new CMDBObjectSet($oSearch);
  980. if ($oSet->Count() > 0)
  981. {
  982. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  983. 'attribute' => $oExtKeyAttDef,
  984. 'objects' => $oSet,
  985. );
  986. }
  987. }
  988. }
  989. return $aDependentObjects;
  990. }
  991. public function GetDeletionScheme()
  992. {
  993. $aDependentObjects = $this->GetReferencingObjects();
  994. $aDeletedObjs = array(); // [class][key] => structure
  995. $aResetedObjs = array(); // [class][key] => object
  996. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  997. {
  998. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  999. {
  1000. $oAttDef = $aData['attribute'];
  1001. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1002. $oDepSet = $aData['objects'];
  1003. $oDepSet->Rewind();
  1004. while ($oDependentObj = $oDepSet->fetch())
  1005. {
  1006. $iId = $oDependentObj->GetKey();
  1007. if ($oAttDef->IsNullAllowed())
  1008. {
  1009. // Optional external key, list to reset
  1010. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1011. {
  1012. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1013. }
  1014. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1015. }
  1016. else
  1017. {
  1018. // Mandatory external key, list to delete
  1019. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1020. {
  1021. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1022. if ($iCurrentOption == DEL_AUTO)
  1023. {
  1024. // be conservative, take the new option
  1025. // (DEL_MANUAL has precedence over DEL_AUTO)
  1026. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1027. }
  1028. else
  1029. {
  1030. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1031. }
  1032. }
  1033. else
  1034. {
  1035. // First time we find the given object in the list
  1036. // (and most likely case is that no other occurence will be found)
  1037. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1038. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. }
  1044. return array($aDeletedObjs, $aResetedObjs);
  1045. }
  1046. }
  1047. ?>