dbobject.class.php 34 KB

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