dbobject.class.php 34 KB

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