dbobject.class.php 36 KB

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