dbobject.class.php 34 KB

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