dbobject.class.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  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. protected $m_aExtendedData = null;
  38. private $m_bDirty = false; // Means: "a modification is ongoing"
  39. // The object may have incorrect external keys, then any attempt of reload must be avoided
  40. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  41. // if null, then the check has to be performed again to know the status
  42. protected $m_aCheckIssues = null;
  43. protected $m_aDeleteIssues = null;
  44. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  45. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  46. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  47. protected $m_oMasterReplicaSet = null; // Set of SynchroReplica related to this object
  48. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  49. public function __construct($aRow = null, $sClassAlias = '', $aExtendedDataSpec = null)
  50. {
  51. if (!empty($aRow))
  52. {
  53. $this->FromRow($aRow, $sClassAlias, $aExtendedDataSpec);
  54. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  55. return;
  56. }
  57. // Creation of brand new object
  58. //
  59. $this->m_iKey = self::GetNextTempId(get_class($this));
  60. // set default values
  61. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  62. {
  63. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  64. $this->m_aOrigValues[$sAttCode] = null;
  65. if ($oAttDef->IsExternalField())
  66. {
  67. // This field has to be read from the DB
  68. $this->m_aLoadedAtt[$sAttCode] = false;
  69. }
  70. else
  71. {
  72. // No need to trigger a reload for that attribute
  73. // Let's consider it as being already fully loaded
  74. $this->m_aLoadedAtt[$sAttCode] = true;
  75. }
  76. }
  77. }
  78. // Read-only <=> Written once (archive)
  79. public function RegisterAsDirty()
  80. {
  81. // While the object may be written to the DB, it is NOT possible to reload it
  82. // or at least not possible to reload it the same way
  83. $this->m_bDirty = true;
  84. }
  85. public function IsNew()
  86. {
  87. return (!$this->m_bIsInDB);
  88. }
  89. // Returns an Id for memory objects
  90. static protected function GetNextTempId($sClass)
  91. {
  92. if (!array_key_exists($sClass, self::$m_aMemoryObjectsByClass))
  93. {
  94. self::$m_aMemoryObjectsByClass[$sClass] = 0;
  95. }
  96. self::$m_aMemoryObjectsByClass[$sClass]++;
  97. return (- self::$m_aMemoryObjectsByClass[$sClass]);
  98. }
  99. public function __toString()
  100. {
  101. $sRet = '';
  102. $sClass = get_class($this);
  103. $sRootClass = MetaModel::GetRootClass($sClass);
  104. $iPKey = $this->GetKey();
  105. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  106. $sRet .= "<ul class=\"treeview\">\n";
  107. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  108. {
  109. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  110. }
  111. $sRet .= "</ul>";
  112. return $sRet;
  113. }
  114. // Restore initial values... mmmm, to be discussed
  115. public function DBRevert()
  116. {
  117. $this->Reload();
  118. }
  119. protected function IsFullyLoaded()
  120. {
  121. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  122. {
  123. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  124. if ($bIsLoaded !== true)
  125. {
  126. return false;
  127. }
  128. }
  129. return true;
  130. }
  131. protected function Reload()
  132. {
  133. assert($this->m_bIsInDB);
  134. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey);
  135. if (empty($aRow))
  136. {
  137. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  138. }
  139. $this->FromRow($aRow);
  140. // Process linked set attributes
  141. //
  142. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  143. {
  144. if (!$oAttDef->IsLinkSet()) continue;
  145. // Load the link information
  146. $sLinkClass = $oAttDef->GetLinkedClass();
  147. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  148. // The class to target is not the current class, because if this is a derived class,
  149. // it may differ from the target class, then things start to become confusing
  150. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  151. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  152. $oMyselfSearch = new DBObjectSearch($sMyClass);
  153. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  154. $oLinkSearch = new DBObjectSearch($sLinkClass);
  155. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  156. $oLinks = new DBObjectSet($oLinkSearch);
  157. $this->m_aCurrValues[$sAttCode] = $oLinks;
  158. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  159. $this->m_aLoadedAtt[$sAttCode] = true;
  160. }
  161. $this->m_bFullyLoaded = true;
  162. }
  163. protected function FromRow($aRow, $sClassAlias = '', $aExtendedDataSpec = null)
  164. {
  165. if (strlen($sClassAlias) == 0)
  166. {
  167. // Default to the current class
  168. $sClassAlias = get_class($this);
  169. }
  170. $this->m_iKey = null;
  171. $this->m_bIsInDB = true;
  172. $this->m_aCurrValues = array();
  173. $this->m_aOrigValues = array();
  174. $this->m_aLoadedAtt = array();
  175. $this->m_bCheckStatus = true;
  176. // Get the key
  177. //
  178. $sKeyField = $sClassAlias."id";
  179. if (!array_key_exists($sKeyField, $aRow))
  180. {
  181. // #@# Bug ?
  182. throw new CoreException("Missing key for class '".get_class($this)."'");
  183. }
  184. $iPKey = $aRow[$sKeyField];
  185. if (!self::IsValidPKey($iPKey))
  186. {
  187. if (is_null($iPKey))
  188. {
  189. throw new CoreException("Missing object id in query result (found null)");
  190. }
  191. else
  192. {
  193. throw new CoreException("An object id must be an integer value ($iPKey)");
  194. }
  195. }
  196. $this->m_iKey = $iPKey;
  197. // Build the object from an array of "attCode"=>"value")
  198. //
  199. $bFullyLoaded = true; // ... set to false if any attribute is not found
  200. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  201. {
  202. // Say something, whatever the type of attribute
  203. $this->m_aLoadedAtt[$sAttCode] = false;
  204. // Skip links (could not be loaded by the mean of this query)
  205. if ($oAttDef->IsLinkSet()) continue;
  206. // Note: we assume that, for a given attribute, if it can be loaded,
  207. // then one column will be found with an empty suffix, the others have a suffix
  208. // Take care: the function isset will return false in case the value is null,
  209. // which is something that could happen on open joins
  210. $sAttRef = $sClassAlias.$sAttCode;
  211. if (array_key_exists($sAttRef, $aRow))
  212. {
  213. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  214. $this->m_aCurrValues[$sAttCode] = $value;
  215. $this->m_aOrigValues[$sAttCode] = $value;
  216. $this->m_aLoadedAtt[$sAttCode] = true;
  217. }
  218. else
  219. {
  220. // This attribute was expected and not found in the query columns
  221. $bFullyLoaded = false;
  222. }
  223. }
  224. // Load extended data
  225. if ($aExtendedDataSpec != null)
  226. {
  227. $aExtendedDataSpec['table'];
  228. foreach($aExtendedDataSpec['fields'] as $sColumn)
  229. {
  230. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  231. if (array_key_exists($sColRef, $aRow))
  232. {
  233. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  234. }
  235. }
  236. }
  237. return $bFullyLoaded;
  238. }
  239. public function Set($sAttCode, $value)
  240. {
  241. if ($sAttCode == 'finalclass')
  242. {
  243. // Ignore it - this attribute is set upon object creation and that's it
  244. return;
  245. }
  246. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  247. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  248. {
  249. // First time Set is called... ensure that the object gets fully loaded
  250. // Otherwise we would lose the values on a further Reload
  251. // + consistency does not make sense !
  252. $this->Reload();
  253. }
  254. if ($oAttDef->IsExternalKey() && is_object($value))
  255. {
  256. // Setting an external key with a whole object (instead of just an ID)
  257. // let's initialize also the external fields that depend on it
  258. // (useful when building objects in memory and not from a query)
  259. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  260. {
  261. throw new CoreUnexpectedValue("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
  262. }
  263. else
  264. {
  265. // The object has changed, reset caches
  266. $this->m_bCheckStatus = null;
  267. $this->m_aAsArgs = null;
  268. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  269. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  270. {
  271. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  272. {
  273. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  274. }
  275. }
  276. }
  277. return;
  278. }
  279. if(!$oAttDef->IsScalar() && !is_object($value))
  280. {
  281. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  282. }
  283. if($oAttDef->IsLinkSet())
  284. {
  285. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  286. {
  287. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  288. }
  289. $oObjectSet = $value;
  290. $sSetClass = $oObjectSet->GetClass();
  291. $sLinkClass = $oAttDef->GetLinkedClass();
  292. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  293. if ($sSetClass != $sLinkClass)
  294. {
  295. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  296. }
  297. }
  298. $realvalue = $oAttDef->MakeRealValue($value);
  299. $this->m_aCurrValues[$sAttCode] = $realvalue;
  300. // The object has changed, reset caches
  301. $this->m_bCheckStatus = null;
  302. $this->m_aAsArgs = null;
  303. // Make sure we do not reload it anymore... before saving it
  304. $this->RegisterAsDirty();
  305. }
  306. public function Get($sAttCode)
  307. {
  308. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  309. {
  310. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  311. }
  312. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  313. {
  314. // #@# non-scalar attributes.... handle that differently
  315. $this->Reload();
  316. }
  317. $value = $this->m_aCurrValues[$sAttCode];
  318. if ($value instanceof DBObjectSet)
  319. {
  320. $value->Rewind();
  321. }
  322. return $value;
  323. }
  324. public function GetOriginal($sAttCode)
  325. {
  326. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  327. {
  328. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  329. }
  330. return $this->m_aOrigValues[$sAttCode];
  331. }
  332. /**
  333. * Returns data loaded by the mean of a dynamic and explicit JOIN
  334. */
  335. public function GetExtendedData()
  336. {
  337. return $this->m_aExtendedData;
  338. }
  339. /**
  340. * Updates the value of an external field by (re)loading the object
  341. * corresponding to the external key and getting the value from it
  342. * @param string $sAttCode Attribute code of the external field to update
  343. * @return void
  344. */
  345. protected function UpdateExternalField($sAttCode)
  346. {
  347. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  348. if ($oAttDef->IsExternalField())
  349. {
  350. $sTargetClass = $oAttDef->GetTargetClass();
  351. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  352. $oObj = MetaModel::GetObject($sTargetClass, $objkey);
  353. if (is_object($oObj))
  354. {
  355. $value = $oObj->Get($oAttDef->GetExtAttCode());
  356. $this->Set($sAttCode, $value);
  357. }
  358. }
  359. }
  360. public function ComputeValues()
  361. {
  362. }
  363. // Compute scalar attributes that depend on any other type of attribute
  364. final public function DoComputeValues()
  365. {
  366. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  367. // First check that we are not currently computing the fields
  368. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  369. foreach (debug_backtrace() as $aCallInfo)
  370. {
  371. if (!array_key_exists("class", $aCallInfo)) continue;
  372. if ($aCallInfo["class"] != get_class($this)) continue;
  373. if ($aCallInfo["function"] != "ComputeValues") continue;
  374. return; //skip!
  375. }
  376. $this->ComputeValues();
  377. }
  378. public function GetAsHTML($sAttCode)
  379. {
  380. $sClass = get_class($this);
  381. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  382. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  383. {
  384. //return $this->Get($sAttCode.'_friendlyname');
  385. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  386. $iTargetKey = $this->Get($sAttCode);
  387. $sLabel = $this->Get($sAttCode.'_friendlyname');
  388. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  389. }
  390. // That's a standard attribute (might be an ext field or a direct field, etc.)
  391. return $oAtt->GetAsHTML($this->Get($sAttCode));
  392. }
  393. public function GetEditValue($sAttCode)
  394. {
  395. $sClass = get_class($this);
  396. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  397. if ($oAtt->IsExternalKey())
  398. {
  399. $sTargetClass = $oAtt->GetTargetClass();
  400. if ($this->IsNew())
  401. {
  402. // The current object exists only in memory, don't try to query it in the DB !
  403. // instead let's query for the object pointed by the external key, and get its name
  404. $targetObjId = $this->Get($sAttCode);
  405. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  406. if (is_object($oTargetObj))
  407. {
  408. $sEditValue = $oTargetObj->GetName();
  409. }
  410. else
  411. {
  412. $sEditValue = 0;
  413. }
  414. }
  415. else
  416. {
  417. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  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), $this);
  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, $this);
  435. }
  436. public function GetOriginalAsHTML($sAttCode)
  437. {
  438. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  439. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this);
  440. }
  441. public function GetOriginalAsXML($sAttCode)
  442. {
  443. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  444. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this);
  445. }
  446. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  447. {
  448. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  449. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this);
  450. }
  451. protected static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '')
  452. {
  453. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  454. $oAppContext = new ApplicationContext();
  455. $sPage = self::ComputeUIPage($sObjClass);
  456. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  457. // Safety net
  458. //
  459. if (empty($sLabel))
  460. {
  461. $sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  462. }
  463. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  464. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  465. }
  466. public function GetHyperlink()
  467. {
  468. if ($this->IsNew()) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  469. $oAppContext = new ApplicationContext();
  470. $sPage = $this->GetUIPage();
  471. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  472. $sObjClass = get_class($this);
  473. $sObjKey = $this->GetKey();
  474. $sLabel = $this->GetName();
  475. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  476. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  477. }
  478. public static function ComputeUIPage($sClass)
  479. {
  480. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  481. if (!isset($aUIPagesCache[$sClass]))
  482. {
  483. $UIPage = false;
  484. if (is_callable("$sClass::GetUIPage"))
  485. {
  486. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  487. }
  488. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  489. }
  490. $sPage = $aUIPagesCache[$sClass];
  491. return $sPage;
  492. }
  493. public static function GetUIPage()
  494. {
  495. return 'UI.php';
  496. }
  497. // could be in the metamodel ?
  498. public static function IsValidPKey($value)
  499. {
  500. return ((string)$value === (string)(int)$value);
  501. }
  502. public function GetKey()
  503. {
  504. return $this->m_iKey;
  505. }
  506. public function SetKey($iNewKey)
  507. {
  508. if (!self::IsValidPKey($iNewKey))
  509. {
  510. throw new CoreException("An object id must be an integer value ($iNewKey)");
  511. }
  512. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  513. {
  514. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  515. }
  516. $this->m_iKey = $iNewKey;
  517. }
  518. /**
  519. * Get the icon representing this object
  520. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  521. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  522. */
  523. public function GetIcon($bImgTag = true)
  524. {
  525. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  526. }
  527. public function GetName()
  528. {
  529. $aNameSpec = MetaModel::GetNameSpec(get_class($this));
  530. $sFormat = $aNameSpec[0];
  531. $aAttributes = $aNameSpec[1];
  532. $aValues = array();
  533. foreach ($aAttributes as $sAttCode)
  534. {
  535. if (empty($sAttCode))
  536. {
  537. $aValues[] = $this->m_iKey;
  538. }
  539. else
  540. {
  541. $aValues[] = $this->Get($sAttCode);
  542. }
  543. }
  544. return vsprintf($sFormat, $aValues);
  545. }
  546. public function GetState()
  547. {
  548. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  549. if (empty($sStateAttCode))
  550. {
  551. return '';
  552. }
  553. else
  554. {
  555. return $this->Get($sStateAttCode);
  556. }
  557. }
  558. public function GetStateLabel()
  559. {
  560. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  561. if (empty($sStateAttCode))
  562. {
  563. return '';
  564. }
  565. else
  566. {
  567. $sStateValue = $this->Get($sStateAttCode);
  568. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  569. }
  570. }
  571. public function GetStateDescription()
  572. {
  573. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  574. if (empty($sStateAttCode))
  575. {
  576. return '';
  577. }
  578. else
  579. {
  580. $sStateValue = $this->Get($sStateAttCode);
  581. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  582. }
  583. }
  584. /**
  585. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  586. * for the given attribute in the current state of the object
  587. * @param string $sAttCode The code of the attribute
  588. * @return integer Flags: the binary combination of the flags applicable to this attribute
  589. */
  590. public function GetAttributeFlags($sAttCode)
  591. {
  592. $iFlags = 0; // By default (if no life cycle) no flag at all
  593. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  594. if (!empty($sStateAttCode))
  595. {
  596. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  597. }
  598. $aReasons = array();
  599. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  600. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  601. }
  602. // check if the given (or current) value is suitable for the attribute
  603. // return true if successfull
  604. // return the error desciption otherwise
  605. public function CheckValue($sAttCode, $value = null)
  606. {
  607. if (!is_null($value))
  608. {
  609. $toCheck = $value;
  610. }
  611. else
  612. {
  613. $toCheck = $this->Get($sAttCode);
  614. }
  615. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  616. if (!$oAtt->IsWritable())
  617. {
  618. return true;
  619. }
  620. elseif ($oAtt->IsNull($toCheck))
  621. {
  622. if ($oAtt->IsNullAllowed())
  623. {
  624. return true;
  625. }
  626. else
  627. {
  628. return "Null not allowed";
  629. }
  630. }
  631. elseif ($oAtt->IsExternalKey())
  632. {
  633. if (!MetaModel::SkipCheckExtKeys())
  634. {
  635. $sTargetClass = $oAtt->GetTargetClass();
  636. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  637. if (is_null($oTargetObj))
  638. {
  639. return "Target object not found ($sTargetClass::$toCheck)";
  640. }
  641. }
  642. }
  643. elseif ($oAtt->IsScalar())
  644. {
  645. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  646. if (count($aValues) > 0)
  647. {
  648. if (!array_key_exists($toCheck, $aValues))
  649. {
  650. return "Value not allowed [$toCheck]";
  651. }
  652. }
  653. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  654. {
  655. $iLen = strlen($toCheck);
  656. if ($iLen > $iMaxSize)
  657. {
  658. return "String too long (found $iLen, limited to $iMaxSize)";
  659. }
  660. }
  661. if (!$oAtt->CheckFormat($toCheck))
  662. {
  663. return "Wrong format [$toCheck]";
  664. }
  665. }
  666. return true;
  667. }
  668. // check attributes together
  669. public function CheckConsistency()
  670. {
  671. return true;
  672. }
  673. // check integrity rules (before inserting or updating the object)
  674. // a displayable error is returned
  675. public function DoCheckToWrite()
  676. {
  677. $this->DoComputeValues();
  678. $this->m_aCheckIssues = array();
  679. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  680. {
  681. $res = $this->CheckValue($sAttCode);
  682. if ($res !== true)
  683. {
  684. // $res contains the error description
  685. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  686. }
  687. }
  688. if (count($this->m_aCheckIssues) > 0)
  689. {
  690. // No need to check consistency between attributes if any of them has
  691. // an unexpected value
  692. return;
  693. }
  694. $res = $this->CheckConsistency();
  695. if ($res !== true)
  696. {
  697. // $res contains the error description
  698. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  699. }
  700. }
  701. final public function CheckToWrite()
  702. {
  703. if (MetaModel::SkipCheckToWrite())
  704. {
  705. return array(true, array());
  706. }
  707. if (is_null($this->m_bCheckStatus))
  708. {
  709. $oKPI = new ExecutionKPI();
  710. $this->DoCheckToWrite();
  711. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  712. if (count($this->m_aCheckIssues) == 0)
  713. {
  714. $this->m_bCheckStatus = true;
  715. }
  716. else
  717. {
  718. $this->m_bCheckStatus = false;
  719. }
  720. }
  721. return array($this->m_bCheckStatus, $this->m_aCheckIssues);
  722. }
  723. // check if it is allowed to delete the existing object from the database
  724. // a displayable error is returned
  725. protected function DoCheckToDelete()
  726. {
  727. $this->m_aDeleteIssues = array(); // Ok
  728. }
  729. // final public function CheckToDelete() - THE EQUIVALENT OF CheckToWrite IS NOT AVAILABLE
  730. // Todo - split the "DeleteObject()" function (UI.php) and move the generic part in cmdbAbstractObject, etc.
  731. protected function ListChangedValues(array $aProposal)
  732. {
  733. $aDelta = array();
  734. foreach ($aProposal as $sAtt => $proposedValue)
  735. {
  736. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  737. {
  738. // The value was not set
  739. $aDelta[$sAtt] = $proposedValue;
  740. }
  741. elseif(is_object($proposedValue))
  742. {
  743. // The value is an object, the comparison is not strict
  744. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  745. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  746. {
  747. $aDelta[$sAtt] = $proposedValue;
  748. }
  749. }
  750. else
  751. {
  752. // The value is a scalar, the comparison must be 100% strict
  753. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  754. {
  755. //echo "$sAtt:<pre>\n";
  756. //var_dump($this->m_aOrigValues[$sAtt]);
  757. //var_dump($proposedValue);
  758. //echo "</pre>\n";
  759. $aDelta[$sAtt] = $proposedValue;
  760. }
  761. }
  762. }
  763. return $aDelta;
  764. }
  765. // List the attributes that have been changed
  766. // Returns an array of attname => currentvalue
  767. public function ListChanges()
  768. {
  769. return $this->ListChangedValues($this->m_aCurrValues);
  770. }
  771. // Tells whether or not an object was modified
  772. public function IsModified()
  773. {
  774. $aChanges = $this->ListChanges();
  775. return (count($aChanges) != 0);
  776. }
  777. // used both by insert/update
  778. private function DBWriteLinks()
  779. {
  780. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  781. {
  782. if (!$oAttDef->IsLinkSet()) continue;
  783. $oLinks = $this->Get($sAttCode);
  784. $oLinks->Rewind();
  785. while ($oLinkedObject = $oLinks->Fetch())
  786. {
  787. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  788. if ($oLinkedObject->IsModified())
  789. {
  790. $oLinkedObject->DBWrite();
  791. }
  792. }
  793. // Delete the objects that were initialy present and disappeared from the list
  794. // (if any)
  795. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  796. if ($oOriginalSet != null)
  797. {
  798. $aOriginalList = $oOriginalSet->ToArray();
  799. $aNewSet = $oLinks->ToArray();
  800. foreach($aOriginalList as $iId => $oObject)
  801. {
  802. if (!array_key_exists($iId, $aNewSet))
  803. {
  804. // It disappeared from the list
  805. $oObject->DBDelete();
  806. }
  807. }
  808. }
  809. }
  810. }
  811. private function DBInsertSingleTable($sTableClass)
  812. {
  813. $sTable = MetaModel::DBGetTable($sTableClass);
  814. // Abstract classes or classes having no specific attribute do not have an associated table
  815. if ($sTable == '') return;
  816. $sClass = get_class($this);
  817. // fields in first array, values in the second
  818. $aFieldsToWrite = array();
  819. $aValuesToWrite = array();
  820. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  821. {
  822. // Add it to the list of fields to write
  823. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  824. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  825. }
  826. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  827. {
  828. // Skip this attribute if not defined in this table
  829. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  830. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  831. foreach($aAttColumns as $sColumn => $sValue)
  832. {
  833. $aFieldsToWrite[] = "`$sColumn`";
  834. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  835. }
  836. }
  837. if (count($aValuesToWrite) == 0) return false;
  838. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  839. if (MetaModel::DBIsReadOnly())
  840. {
  841. $iNewKey = -1;
  842. }
  843. else
  844. {
  845. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  846. }
  847. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  848. if (empty($this->m_iKey))
  849. {
  850. // Take the autonumber
  851. $this->m_iKey = $iNewKey;
  852. }
  853. return $this->m_iKey;
  854. }
  855. // Insert of record for the new object into the database
  856. // Returns the key of the newly created object
  857. public function DBInsertNoReload()
  858. {
  859. if ($this->m_bIsInDB)
  860. {
  861. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  862. }
  863. $sClass = get_class($this);
  864. $sRootClass = MetaModel::GetRootClass($sClass);
  865. // Ensure the update of the values (we are accessing the data directly)
  866. $this->DoComputeValues();
  867. $this->OnInsert();
  868. if ($this->m_iKey < 0)
  869. {
  870. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  871. $this->m_iKey = null;
  872. }
  873. // If not automatically computed, then check that the key is given by the caller
  874. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  875. {
  876. if (empty($this->m_iKey))
  877. {
  878. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber", array('class' => $sRootClass));
  879. }
  880. }
  881. // Ultimate check - ensure DB integrity
  882. list($bRes, $aIssues) = $this->CheckToWrite();
  883. if (!$bRes)
  884. {
  885. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  886. }
  887. // First query built upon on the root class, because the ID must be created first
  888. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  889. // Then do the leaf class, if different from the root class
  890. if ($sClass != $sRootClass)
  891. {
  892. $this->DBInsertSingleTable($sClass);
  893. }
  894. // Then do the other classes
  895. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  896. {
  897. if ($sParentClass == $sRootClass) continue;
  898. $this->DBInsertSingleTable($sParentClass);
  899. }
  900. $this->DBWriteLinks();
  901. $this->m_bIsInDB = true;
  902. $this->m_bDirty = false;
  903. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  904. $this->m_aAsArgs = null;
  905. $this->AfterInsert();
  906. // Activate any existing trigger
  907. $sClass = get_class($this);
  908. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  909. while ($oTrigger = $oSet->Fetch())
  910. {
  911. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  912. {
  913. $oTrigger->DoActivate($this->ToArgs('this'));
  914. }
  915. }
  916. return $this->m_iKey;
  917. }
  918. public function DBInsert()
  919. {
  920. $this->DBInsertNoReload();
  921. $this->Reload();
  922. return $this->m_iKey;
  923. }
  924. public function DBInsertTracked(CMDBChange $oVoid)
  925. {
  926. return $this->DBInsert();
  927. }
  928. // Creates a copy of the current object into the database
  929. // Returns the id of the newly created object
  930. public function DBClone($iNewKey = null)
  931. {
  932. $this->m_bIsInDB = false;
  933. $this->m_iKey = $iNewKey;
  934. return $this->DBInsert();
  935. }
  936. /**
  937. * This function is automatically called after cloning an object with the "clone" PHP language construct
  938. * The purpose of this method is to reset the appropriate attributes of the object in
  939. * order to make sure that the newly cloned object is really distinct from its clone
  940. */
  941. public function __clone()
  942. {
  943. $this->m_bIsInDB = false;
  944. $this->m_bDirty = true;
  945. $this->m_iKey = self::GetNextTempId(get_class($this));
  946. }
  947. // Update a record
  948. public function DBUpdate()
  949. {
  950. if (!$this->m_bIsInDB)
  951. {
  952. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  953. }
  954. $this->DoComputeValues();
  955. $this->OnUpdate();
  956. $aChanges = $this->ListChanges();
  957. if (count($aChanges) == 0)
  958. {
  959. //throw new CoreWarning("Attempting to update an unchanged object");
  960. return;
  961. }
  962. // Ultimate check - ensure DB integrity
  963. list($bRes, $aIssues) = $this->CheckToWrite();
  964. if (!$bRes)
  965. {
  966. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => get_class($this), 'id' => $this->GetKey(), 'issues' => $aIssues));
  967. }
  968. $bHasANewExternalKeyValue = false;
  969. foreach($aChanges as $sAttCode => $valuecurr)
  970. {
  971. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  972. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  973. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  974. }
  975. // Update scalar attributes
  976. if (count($aChanges) != 0)
  977. {
  978. $oFilter = new DBObjectSearch(get_class($this));
  979. $oFilter->AddCondition('id', $this->m_iKey, '=');
  980. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  981. if (!MetaModel::DBIsReadOnly())
  982. {
  983. CMDBSource::Query($sSQL);
  984. }
  985. }
  986. $this->DBWriteLinks();
  987. $this->m_bDirty = false;
  988. $this->AfterUpdate();
  989. // Reload to get the external attributes
  990. if ($bHasANewExternalKeyValue)
  991. {
  992. $this->Reload();
  993. }
  994. return $this->m_iKey;
  995. }
  996. public function DBUpdateTracked(CMDBChange $oVoid)
  997. {
  998. return $this->DBUpdate();
  999. }
  1000. // Make the current changes persistent - clever wrapper for Insert or Update
  1001. public function DBWrite()
  1002. {
  1003. if ($this->m_bIsInDB)
  1004. {
  1005. return $this->DBUpdate();
  1006. }
  1007. else
  1008. {
  1009. return $this->DBInsert();
  1010. }
  1011. }
  1012. // Delete a record
  1013. public function DBDelete()
  1014. {
  1015. $oFilter = new DBObjectSearch(get_class($this));
  1016. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1017. $this->OnDelete();
  1018. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  1019. if (!MetaModel::DBIsReadOnly())
  1020. {
  1021. CMDBSource::Query($sSQL);
  1022. }
  1023. $this->AfterDelete();
  1024. $this->m_bIsInDB = false;
  1025. $this->m_iKey = null;
  1026. }
  1027. public function DBDeleteTracked(CMDBChange $oVoid)
  1028. {
  1029. $this->DBDelete();
  1030. }
  1031. public function EnumTransitions()
  1032. {
  1033. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1034. if (empty($sStateAttCode)) return array();
  1035. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1036. return MetaModel::EnumTransitions(get_class($this), $sState);
  1037. }
  1038. public function ApplyStimulus($sStimulusCode)
  1039. {
  1040. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1041. if (empty($sStateAttCode)) return false;
  1042. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1043. $aStateTransitions = $this->EnumTransitions();
  1044. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1045. // Change the state before proceeding to the actions, this is necessary because an action might
  1046. // trigger another stimuli (alternative: push the stimuli into a queue)
  1047. $sPreviousState = $this->Get($sStateAttCode);
  1048. $sNewState = $aTransitionDef['target_state'];
  1049. $this->Set($sStateAttCode, $sNewState);
  1050. // $aTransitionDef is an
  1051. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1052. $bSuccess = true;
  1053. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1054. {
  1055. // std PHP spec
  1056. $aActionCallSpec = array($this, $sActionHandler);
  1057. if (!is_callable($aActionCallSpec))
  1058. {
  1059. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1060. return;
  1061. }
  1062. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1063. // if one call fails, the whole is considered as failed
  1064. if (!$bRet) $bSuccess = false;
  1065. }
  1066. // Change state triggers...
  1067. $sClass = get_class($this);
  1068. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1069. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1070. while ($oTrigger = $oSet->Fetch())
  1071. {
  1072. $oTrigger->DoActivate($this->ToArgs('this'));
  1073. }
  1074. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1075. while ($oTrigger = $oSet->Fetch())
  1076. {
  1077. $oTrigger->DoActivate($this->ToArgs('this'));
  1078. }
  1079. return $bSuccess;
  1080. }
  1081. // Make standard context arguments
  1082. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1083. // Several options here:
  1084. // 1) cache the result
  1085. // 2) set only the object ref and resolve the values iif needed from contextual templates and queries (easy for the queries, not for the templates)
  1086. public function ToArgs($sArgName = 'this')
  1087. {
  1088. if (is_null($this->m_aAsArgs))
  1089. {
  1090. $oKPI = new ExecutionKPI();
  1091. $aScalarArgs = array();
  1092. $aScalarArgs[$sArgName] = $this->GetKey();
  1093. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1094. $aScalarArgs[$sArgName.'->object()'] = $this;
  1095. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  1096. // #@# Prototype for a user portal - to be dehardcoded later
  1097. $sToPortal = utils::GetAbsoluteUrlPath().'../portal/index.php?operation=details&id='.$this->GetKey();
  1098. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1099. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1100. $sClass = get_class($this);
  1101. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1102. {
  1103. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1104. if ($oAttDef->IsScalar())
  1105. {
  1106. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1107. $sAsHtml = $this->GetAsHtml($sAttCode);
  1108. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1109. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1110. }
  1111. }
  1112. $this->m_aAsArgs = $aScalarArgs;
  1113. $oKPI->ComputeStats('ToArgs', get_class($this));
  1114. }
  1115. return $this->m_aAsArgs;
  1116. }
  1117. // To be optionaly overloaded
  1118. protected function OnInsert()
  1119. {
  1120. }
  1121. // To be optionaly overloaded
  1122. protected function AfterInsert()
  1123. {
  1124. }
  1125. // To be optionaly overloaded
  1126. protected function OnUpdate()
  1127. {
  1128. }
  1129. // To be optionaly overloaded
  1130. protected function AfterUpdate()
  1131. {
  1132. }
  1133. // To be optionaly overloaded
  1134. protected function OnDelete()
  1135. {
  1136. }
  1137. // To be optionaly overloaded
  1138. protected function AfterDelete()
  1139. {
  1140. }
  1141. // Return an empty set for the parent of all
  1142. public static function GetRelationQueries($sRelCode)
  1143. {
  1144. return array();
  1145. }
  1146. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1147. {
  1148. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1149. {
  1150. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1151. $sQuery = $aQueryInfo["sQuery"];
  1152. $bPropagate = $aQueryInfo["bPropagate"];
  1153. $iDistance = $aQueryInfo["iDistance"];
  1154. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1155. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1156. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1157. while ($oObj = $oObjSet->Fetch())
  1158. {
  1159. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1160. $sObjKey = $oObj->GetKey();
  1161. if (array_key_exists($sRootClass, $aResults))
  1162. {
  1163. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1164. {
  1165. continue; // already visited, skip
  1166. }
  1167. }
  1168. $aResults[$sRootClass][$sObjKey] = $oObj;
  1169. if ($iDepth > 0)
  1170. {
  1171. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1172. }
  1173. }
  1174. }
  1175. return $aResults;
  1176. }
  1177. public function GetReferencingObjects()
  1178. {
  1179. $aDependentObjects = array();
  1180. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1181. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1182. {
  1183. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1184. {
  1185. // skip if this external key is behind an external field
  1186. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1187. $oSearch = new DBObjectSearch($sRemoteClass);
  1188. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1189. $oSet = new CMDBObjectSet($oSearch);
  1190. if ($oSet->Count() > 0)
  1191. {
  1192. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1193. 'attribute' => $oExtKeyAttDef,
  1194. 'objects' => $oSet,
  1195. );
  1196. }
  1197. }
  1198. }
  1199. return $aDependentObjects;
  1200. }
  1201. /**
  1202. * $aDeletedObjs = array(); // [class][key] => structure
  1203. * $aResetedObjs = array(); // [class][key] => object
  1204. */
  1205. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1206. {
  1207. $sClass = get_class($this);
  1208. $iThisId = $this->GetKey();
  1209. if (array_key_exists($sClass, $aVisited))
  1210. {
  1211. if (in_array($iThisId, $aVisited[$sClass]))
  1212. {
  1213. return;
  1214. }
  1215. }
  1216. $aVisited[$sClass] = $iThisId;
  1217. $aDeletedObjs[$sClass][$iThisId]['to_delete'] = $this;
  1218. $aDeletedObjs[$sClass][$iThisId]['auto_delete'] = true;
  1219. // Check the node itself
  1220. $this->DoCheckToDelete();
  1221. $aDeletedObjs[$sClass][$iThisId]['issues'] = $this->m_aDeleteIssues;
  1222. $aDependentObjects = $this->GetReferencingObjects();
  1223. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1224. {
  1225. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1226. {
  1227. $oAttDef = $aData['attribute'];
  1228. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1229. $oDepSet = $aData['objects'];
  1230. $oDepSet->Rewind();
  1231. while ($oDependentObj = $oDepSet->fetch())
  1232. {
  1233. $iId = $oDependentObj->GetKey();
  1234. if ($oAttDef->IsNullAllowed())
  1235. {
  1236. // Optional external key, list to reset
  1237. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1238. {
  1239. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1240. }
  1241. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1242. }
  1243. else
  1244. {
  1245. // Mandatory external key, list to delete
  1246. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1247. {
  1248. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1249. if ($iCurrentOption == DEL_AUTO)
  1250. {
  1251. // be conservative, take the new option
  1252. // (DEL_MANUAL has precedence over DEL_AUTO)
  1253. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1254. }
  1255. else
  1256. {
  1257. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1258. }
  1259. }
  1260. else
  1261. {
  1262. // First time we find the given object in the list
  1263. // (and most likely case is that no other occurence will be found)
  1264. if ($iDeletePropagationOption == DEL_AUTO)
  1265. {
  1266. // Recursively inspect this object
  1267. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1268. }
  1269. else
  1270. {
  1271. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1272. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = false;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. }
  1280. /**
  1281. * Get all the synchro replica related to this object
  1282. * @param none
  1283. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  1284. */
  1285. public function GetMasterReplica()
  1286. {
  1287. if ($this->m_oMasterReplicaSet == null)
  1288. {
  1289. $aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  1290. $sClassesList = "'".implode("','", $aParentClasses)."'";
  1291. $sOQL = "SELECT replica,datasource FROM SynchroReplica AS replica JOIN SynchroDataSource AS datasource ON replica.sync_source_id=datasource.id WHERE datasource.scope_class IN ($sClassesList) AND replica.dest_id = :dest_id";
  1292. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_id' => $this->GetKey()));
  1293. $this->m_oMasterReplicaSet = $oReplicaSet;
  1294. }
  1295. else
  1296. {
  1297. $this->m_oMasterReplicaSet->Rewind();
  1298. }
  1299. return $this->m_oMasterReplicaSet;
  1300. }
  1301. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  1302. {
  1303. $iFlags = OPT_ATT_NORMAL;
  1304. $oSet = $this->GetMasterReplica();
  1305. while($aData = $oSet->FetchAssoc())
  1306. {
  1307. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  1308. $oReplica = $aData['replica'];
  1309. $oSource = $aData['datasource'];
  1310. $oAttrSet = $oSource->Get('attribute_list');
  1311. while($oSyncAttr = $oAttrSet->Fetch())
  1312. {
  1313. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  1314. {
  1315. $iFlags |= OPT_ATT_READONLY;
  1316. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  1317. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  1318. }
  1319. }
  1320. }
  1321. return $iFlags;
  1322. }
  1323. }
  1324. ?>