dbobject.class.php 36 KB

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