dbobject.class.php 35 KB

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