dbobject.class.php 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Class dbObject: the root of persistent classes
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('metamodel.class.php');
  25. require_once('deletionplan.class.inc.php');
  26. /**
  27. * A persistent object, as defined by the metamodel
  28. *
  29. * @package iTopORM
  30. */
  31. abstract class DBObject
  32. {
  33. private static $m_aMemoryObjectsByClass = array();
  34. private static $m_aBulkInsertItems = array(); // class => array of ('table' => array of (array of <sql_value>))
  35. private static $m_aBulkInsertCols = array(); // class => array of ('table' => array of <sql_column>)
  36. private static $m_bBulkInsert = false;
  37. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  38. private $m_iKey = null;
  39. private $m_aCurrValues = array();
  40. protected $m_aOrigValues = array();
  41. protected $m_aExtendedData = null;
  42. private $m_bDirty = false; // Means: "a modification is ongoing"
  43. // The object may have incorrect external keys, then any attempt of reload must be avoided
  44. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  45. // if null, then the check has to be performed again to know the status
  46. protected $m_bSecurityIssue = null;
  47. protected $m_aCheckIssues = null;
  48. protected $m_aDeleteIssues = null;
  49. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  50. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  51. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  52. protected $m_oMasterReplicaSet = null; // Set of SynchroReplica related to this object
  53. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  54. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  55. {
  56. if (!empty($aRow))
  57. {
  58. $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  59. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  60. return;
  61. }
  62. // Creation of a brand new object
  63. //
  64. $this->m_iKey = self::GetNextTempId(get_class($this));
  65. // set default values
  66. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  67. {
  68. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  69. $this->m_aOrigValues[$sAttCode] = null;
  70. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  71. {
  72. // This field has to be read from the DB
  73. // Leave the flag unset (optimization)
  74. }
  75. else
  76. {
  77. // No need to trigger a reload for that attribute
  78. // Let's consider it as being already fully loaded
  79. $this->m_aLoadedAtt[$sAttCode] = true;
  80. }
  81. }
  82. }
  83. // Read-only <=> Written once (archive)
  84. public function RegisterAsDirty()
  85. {
  86. // While the object may be written to the DB, it is NOT possible to reload it
  87. // or at least not possible to reload it the same way
  88. $this->m_bDirty = true;
  89. }
  90. public function IsNew()
  91. {
  92. return (!$this->m_bIsInDB);
  93. }
  94. // Returns an Id for memory objects
  95. static protected function GetNextTempId($sClass)
  96. {
  97. $sRootClass = MetaModel::GetRootClass($sClass);
  98. if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
  99. {
  100. self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
  101. }
  102. self::$m_aMemoryObjectsByClass[$sRootClass]++;
  103. return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
  104. }
  105. public function __toString()
  106. {
  107. $sRet = '';
  108. $sClass = get_class($this);
  109. $sRootClass = MetaModel::GetRootClass($sClass);
  110. $iPKey = $this->GetKey();
  111. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  112. $sRet .= "<ul class=\"treeview\">\n";
  113. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  114. {
  115. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  116. }
  117. $sRet .= "</ul>";
  118. return $sRet;
  119. }
  120. // Restore initial values... mmmm, to be discussed
  121. public function DBRevert()
  122. {
  123. $this->Reload();
  124. }
  125. protected function IsFullyLoaded()
  126. {
  127. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  128. {
  129. if (!$oAttDef->LoadInObject()) continue;
  130. if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
  131. {
  132. return false;
  133. }
  134. }
  135. return true;
  136. }
  137. public function Reload()
  138. {
  139. assert($this->m_bIsInDB);
  140. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false/*, $this->m_bAllowAllData*/);
  141. if (empty($aRow))
  142. {
  143. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  144. }
  145. $this->FromRow($aRow);
  146. // Process linked set attributes
  147. //
  148. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  149. {
  150. if (!$oAttDef->IsLinkSet()) continue;
  151. // Load the link information
  152. $sLinkClass = $oAttDef->GetLinkedClass();
  153. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  154. // The class to target is not the current class, because if this is a derived class,
  155. // it may differ from the target class, then things start to become confusing
  156. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  157. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  158. $oMyselfSearch = new DBObjectSearch($sMyClass);
  159. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  160. $oLinkSearch = new DBObjectSearch($sLinkClass);
  161. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  162. $oLinks = new DBObjectSet($oLinkSearch);
  163. $this->m_aCurrValues[$sAttCode] = $oLinks;
  164. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  165. $this->m_aLoadedAtt[$sAttCode] = true;
  166. }
  167. $this->m_bFullyLoaded = true;
  168. }
  169. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  170. {
  171. if (strlen($sClassAlias) == 0)
  172. {
  173. // Default to the current class
  174. $sClassAlias = get_class($this);
  175. }
  176. $this->m_iKey = null;
  177. $this->m_bIsInDB = true;
  178. $this->m_aCurrValues = array();
  179. $this->m_aOrigValues = array();
  180. $this->m_aLoadedAtt = array();
  181. $this->m_bCheckStatus = true;
  182. // Get the key
  183. //
  184. $sKeyField = $sClassAlias."id";
  185. if (!array_key_exists($sKeyField, $aRow))
  186. {
  187. // #@# Bug ?
  188. throw new CoreException("Missing key for class '".get_class($this)."'");
  189. }
  190. $iPKey = $aRow[$sKeyField];
  191. if (!self::IsValidPKey($iPKey))
  192. {
  193. if (is_null($iPKey))
  194. {
  195. throw new CoreException("Missing object id in query result (found null)");
  196. }
  197. else
  198. {
  199. throw new CoreException("An object id must be an integer value ($iPKey)");
  200. }
  201. }
  202. $this->m_iKey = $iPKey;
  203. // Build the object from an array of "attCode"=>"value")
  204. //
  205. $bFullyLoaded = true; // ... set to false if any attribute is not found
  206. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  207. {
  208. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  209. }
  210. else
  211. {
  212. $aAttList = $aAttToLoad[$sClassAlias];
  213. }
  214. foreach($aAttList as $sAttCode=>$oAttDef)
  215. {
  216. // Skip links (could not be loaded by the mean of this query)
  217. if ($oAttDef->IsLinkSet()) continue;
  218. if (!$oAttDef->LoadInObject()) continue;
  219. // Note: we assume that, for a given attribute, if it can be loaded,
  220. // then one column will be found with an empty suffix, the others have a suffix
  221. // Take care: the function isset will return false in case the value is null,
  222. // which is something that could happen on open joins
  223. $sAttRef = $sClassAlias.$sAttCode;
  224. if (array_key_exists($sAttRef, $aRow))
  225. {
  226. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  227. $this->m_aCurrValues[$sAttCode] = $value;
  228. if (is_object($value))
  229. {
  230. $this->m_aOrigValues[$sAttCode] = clone $value;
  231. }
  232. else
  233. {
  234. $this->m_aOrigValues[$sAttCode] = $value;
  235. }
  236. $this->m_aLoadedAtt[$sAttCode] = true;
  237. }
  238. else
  239. {
  240. // This attribute was expected and not found in the query columns
  241. $bFullyLoaded = false;
  242. }
  243. }
  244. // Load extended data
  245. if ($aExtendedDataSpec != null)
  246. {
  247. $aExtendedDataSpec['table'];
  248. foreach($aExtendedDataSpec['fields'] as $sColumn)
  249. {
  250. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  251. if (array_key_exists($sColRef, $aRow))
  252. {
  253. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  254. }
  255. }
  256. }
  257. return $bFullyLoaded;
  258. }
  259. public function Set($sAttCode, $value)
  260. {
  261. if ($sAttCode == 'finalclass')
  262. {
  263. // Ignore it - this attribute is set upon object creation and that's it
  264. return;
  265. }
  266. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  267. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  268. {
  269. // First time Set is called... ensure that the object gets fully loaded
  270. // Otherwise we would lose the values on a further Reload
  271. // + consistency does not make sense !
  272. $this->Reload();
  273. }
  274. if ($oAttDef->IsExternalKey())
  275. {
  276. if (is_object($value))
  277. {
  278. // Setting an external key with a whole object (instead of just an ID)
  279. // let's initialize also the external fields that depend on it
  280. // (useful when building objects in memory and not from a query)
  281. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  282. {
  283. 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");
  284. }
  285. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  286. {
  287. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  288. {
  289. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  290. }
  291. }
  292. }
  293. else if ($this->m_aCurrValues[$sAttCode] != $value)
  294. {
  295. // Setting an external key, but no any other information is available...
  296. // Invalidate the corresponding fields so that they get reloaded in case they are needed (See Get())
  297. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  298. {
  299. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  300. {
  301. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  302. unset($this->m_aLoadedAtt[$sCode]);
  303. }
  304. }
  305. }
  306. }
  307. if(!$oAttDef->IsScalar() && !is_object($value))
  308. {
  309. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  310. }
  311. if($oAttDef->IsLinkSet())
  312. {
  313. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  314. {
  315. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  316. }
  317. $oObjectSet = $value;
  318. $sSetClass = $oObjectSet->GetClass();
  319. $sLinkClass = $oAttDef->GetLinkedClass();
  320. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  321. if ($sSetClass != $sLinkClass)
  322. {
  323. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  324. }
  325. }
  326. $realvalue = $oAttDef->MakeRealValue($value, $this);
  327. $this->m_aCurrValues[$sAttCode] = $realvalue;
  328. // The object has changed, reset caches
  329. $this->m_bCheckStatus = null;
  330. $this->m_aAsArgs = null;
  331. // Make sure we do not reload it anymore... before saving it
  332. $this->RegisterAsDirty();
  333. }
  334. public function GetLabel($sAttCode)
  335. {
  336. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  337. return $oAttDef->GetLabel();
  338. }
  339. public function Get($sAttCode)
  340. {
  341. if (($iPos = strpos($sAttCode, '->')) === false)
  342. {
  343. return $this->GetStrict($sAttCode);
  344. }
  345. else
  346. {
  347. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  348. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  349. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  350. {
  351. throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
  352. }
  353. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  354. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  355. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  356. if (is_null($oRemoteObj))
  357. {
  358. return '';
  359. }
  360. else
  361. {
  362. return $oRemoteObj->Get($sRemoteAttCode);
  363. }
  364. }
  365. }
  366. public function GetStrict($sAttCode)
  367. {
  368. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  369. if (!$oAttDef->LoadInObject())
  370. {
  371. $sParentAttCode = $oAttDef->GetParentAttCode();
  372. $parentValue = $this->GetStrict($sParentAttCode);
  373. $value = $oAttDef->GetValue($parentValue, $this);
  374. }
  375. else
  376. {
  377. if (isset($this->m_aLoadedAtt[$sAttCode]))
  378. {
  379. // Standard case... we have the information directly
  380. }
  381. elseif ($this->m_bIsInDB && !$this->m_bDirty)
  382. {
  383. // Lazy load (polymorphism): complete by reloading the entire object
  384. // #@# non-scalar attributes.... handle that differently?
  385. $this->Reload();
  386. }
  387. elseif ($sAttCode == 'friendlyname')
  388. {
  389. // The friendly name is not computed and the object is dirty
  390. // Todo: implement the computation of the friendly name based on sprintf()
  391. //
  392. $this->m_aCurrValues[$sAttCode] = '';
  393. }
  394. else
  395. {
  396. // Not loaded... is it related to an external key?
  397. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  398. {
  399. // Let's get the object and compute all of the corresponding attributes
  400. // (i.e not only the requested attribute)
  401. //
  402. $sExtKeyAttCode = $oAttDef->GetKeyAttCode();
  403. if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
  404. {
  405. $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  406. // Note: "allow all data" must be enabled because the external fields are always visible
  407. // to the current user even if this is not the case for the remote object
  408. // This is consistent with the behavior of the lists
  409. $oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
  410. }
  411. else
  412. {
  413. $oRemote = null;
  414. }
  415. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  416. {
  417. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sExtKeyAttCode))
  418. {
  419. if ($oRemote)
  420. {
  421. $this->m_aCurrValues[$sCode] = $oRemote->Get($oDef->GetExtAttCode());
  422. }
  423. else
  424. {
  425. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  426. }
  427. $this->m_aLoadedAtt[$sCode] = true;
  428. }
  429. }
  430. }
  431. }
  432. $value = $this->m_aCurrValues[$sAttCode];
  433. }
  434. if ($value instanceof DBObjectSet)
  435. {
  436. $value->Rewind();
  437. }
  438. return $value;
  439. }
  440. public function GetOriginal($sAttCode)
  441. {
  442. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  443. {
  444. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  445. }
  446. return $this->m_aOrigValues[$sAttCode];
  447. }
  448. /**
  449. * Returns data loaded by the mean of a dynamic and explicit JOIN
  450. */
  451. public function GetExtendedData()
  452. {
  453. return $this->m_aExtendedData;
  454. }
  455. /**
  456. * Updates the value of an external field by (re)loading the object
  457. * corresponding to the external key and getting the value from it
  458. *
  459. * UNUSED ?
  460. *
  461. * @param string $sAttCode Attribute code of the external field to update
  462. * @return void
  463. */
  464. protected function UpdateExternalField($sAttCode)
  465. {
  466. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  467. if ($oAttDef->IsExternalField())
  468. {
  469. $sTargetClass = $oAttDef->GetTargetClass();
  470. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  471. // Note: "allow all data" must be enabled because the external fields are always visible
  472. // to the current user even if this is not the case for the remote object
  473. // This is consistent with the behavior of the lists
  474. $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
  475. if (is_object($oObj))
  476. {
  477. $value = $oObj->Get($oAttDef->GetExtAttCode());
  478. $this->Set($sAttCode, $value);
  479. }
  480. }
  481. }
  482. public function ComputeValues()
  483. {
  484. }
  485. // Compute scalar attributes that depend on any other type of attribute
  486. final public function DoComputeValues()
  487. {
  488. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  489. // First check that we are not currently computing the fields
  490. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  491. foreach (debug_backtrace() as $aCallInfo)
  492. {
  493. if (!array_key_exists("class", $aCallInfo)) continue;
  494. if ($aCallInfo["class"] != get_class($this)) continue;
  495. if ($aCallInfo["function"] != "ComputeValues") continue;
  496. return; //skip!
  497. }
  498. $this->ComputeValues();
  499. }
  500. public function GetAsHTML($sAttCode, $bLocalize = true)
  501. {
  502. $sClass = get_class($this);
  503. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  504. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  505. {
  506. //return $this->Get($sAttCode.'_friendlyname');
  507. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  508. $iTargetKey = $this->Get($sAttCode);
  509. if ($iTargetKey < 0)
  510. {
  511. // the key points to an object that exists only in memory... no hyperlink points to it yet
  512. return '';
  513. }
  514. else
  515. {
  516. $sLabel = $this->Get($sAttCode.'_friendlyname');
  517. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  518. }
  519. }
  520. // That's a standard attribute (might be an ext field or a direct field, etc.)
  521. return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
  522. }
  523. public function GetEditValue($sAttCode)
  524. {
  525. $sClass = get_class($this);
  526. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  527. if ($oAtt->IsExternalKey())
  528. {
  529. $sTargetClass = $oAtt->GetTargetClass();
  530. if ($this->IsNew())
  531. {
  532. // The current object exists only in memory, don't try to query it in the DB !
  533. // instead let's query for the object pointed by the external key, and get its name
  534. $targetObjId = $this->Get($sAttCode);
  535. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  536. if (is_object($oTargetObj))
  537. {
  538. $sEditValue = $oTargetObj->GetName();
  539. }
  540. else
  541. {
  542. $sEditValue = 0;
  543. }
  544. }
  545. else
  546. {
  547. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  548. }
  549. }
  550. else
  551. {
  552. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
  553. }
  554. return $sEditValue;
  555. }
  556. public function GetAsXML($sAttCode, $bLocalize = true)
  557. {
  558. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  559. return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
  560. }
  561. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  562. {
  563. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  564. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  565. }
  566. public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
  567. {
  568. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  569. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
  570. }
  571. public function GetOriginalAsXML($sAttCode, $bLocalize = true)
  572. {
  573. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  574. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
  575. }
  576. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  577. {
  578. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  579. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  580. }
  581. public static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true)
  582. {
  583. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  584. // Safety net
  585. //
  586. if (empty($sLabel))
  587. {
  588. // If the object if not issued from a query but constructed programmatically
  589. // the label may be empty. In this case run a query to get the object's friendly name
  590. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
  591. if (is_object($oTmpObj))
  592. {
  593. $sLabel = $oTmpObj->GetName();
  594. }
  595. else
  596. {
  597. // May happen in case the target object is not in the list of allowed values for this attribute
  598. $sLabel = "<em>$sObjClass::$sObjKey</em>";
  599. }
  600. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  601. }
  602. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  603. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  604. if (strlen($sUrl) > 0)
  605. {
  606. return "<a href=\"$sUrl\" title=\"$sHint\">$sLabel</a>";
  607. }
  608. else
  609. {
  610. return $sLabel;
  611. }
  612. }
  613. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  614. {
  615. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext);
  616. }
  617. public static function ComputeStandardUIPage($sClass)
  618. {
  619. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  620. if (!isset($aUIPagesCache[$sClass]))
  621. {
  622. $UIPage = false;
  623. if (is_callable("$sClass::GetUIPage"))
  624. {
  625. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  626. }
  627. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  628. }
  629. $sPage = $aUIPagesCache[$sClass];
  630. return $sPage;
  631. }
  632. public static function GetUIPage()
  633. {
  634. return 'UI.php';
  635. }
  636. // could be in the metamodel ?
  637. public static function IsValidPKey($value)
  638. {
  639. return ((string)$value === (string)(int)$value);
  640. }
  641. public function GetKey()
  642. {
  643. return $this->m_iKey;
  644. }
  645. public function SetKey($iNewKey)
  646. {
  647. if (!self::IsValidPKey($iNewKey))
  648. {
  649. throw new CoreException("An object id must be an integer value ($iNewKey)");
  650. }
  651. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  652. {
  653. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  654. }
  655. $this->m_iKey = $iNewKey;
  656. }
  657. /**
  658. * Get the icon representing this object
  659. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  660. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  661. */
  662. public function GetIcon($bImgTag = true)
  663. {
  664. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  665. }
  666. /**
  667. * Gets the name of an object in a safe manner for displaying inside a web page
  668. * @return string
  669. */
  670. public function GetName()
  671. {
  672. return htmlentities($this->GetRawName(), ENT_QUOTES, 'UTF-8');
  673. }
  674. /**
  675. * Gets the raw name of an object, this is not safe for displaying inside a web page
  676. * since the " < > characters are not escaped and the name may contain some XSS script
  677. * instructions.
  678. * Use this function only for internal computations or for an output to a non-HTML destination
  679. * @return string
  680. */
  681. public function GetRawName()
  682. {
  683. return $this->Get('friendlyname');
  684. }
  685. public function GetState()
  686. {
  687. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  688. if (empty($sStateAttCode))
  689. {
  690. return '';
  691. }
  692. else
  693. {
  694. return $this->Get($sStateAttCode);
  695. }
  696. }
  697. public function GetStateLabel()
  698. {
  699. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  700. if (empty($sStateAttCode))
  701. {
  702. return '';
  703. }
  704. else
  705. {
  706. $sStateValue = $this->Get($sStateAttCode);
  707. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  708. }
  709. }
  710. public function GetStateDescription()
  711. {
  712. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  713. if (empty($sStateAttCode))
  714. {
  715. return '';
  716. }
  717. else
  718. {
  719. $sStateValue = $this->Get($sStateAttCode);
  720. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  721. }
  722. }
  723. /**
  724. * Overridable - Define attributes read-only from the end-user perspective
  725. *
  726. * @return array List of attcodes
  727. */
  728. public static function GetReadOnlyAttributes()
  729. {
  730. return null;
  731. }
  732. /**
  733. * Overridable - Get predefined objects (could be hardcoded)
  734. * The predefined objects will be synchronized with the DB at each install/upgrade
  735. * As soon as a class has predefined objects, then nobody can create nor delete objects
  736. * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
  737. */
  738. public static function GetPredefinedObjects()
  739. {
  740. return null;
  741. }
  742. /**
  743. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  744. * for the given attribute in the current state of the object
  745. * @param $sAttCode string $sAttCode The code of the attribute
  746. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  747. * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
  748. * @return integer Flags: the binary combination of the flags applicable to this attribute
  749. */
  750. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  751. {
  752. $iFlags = 0; // By default (if no life cycle) no flag at all
  753. $aReadOnlyAtts = $this->GetReadOnlyAttributes();
  754. if ($aReadOnlyAtts != null)
  755. {
  756. if (in_array($sAttCode, $aReadOnlyAtts))
  757. {
  758. return OPT_ATT_READONLY;
  759. }
  760. }
  761. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  762. if (!empty($sStateAttCode))
  763. {
  764. if ($sTargetState != '')
  765. {
  766. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  767. }
  768. else
  769. {
  770. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  771. }
  772. }
  773. $aReasons = array();
  774. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  775. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  776. }
  777. /**
  778. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  779. * for the given attribute for the current state of the object considered as an INITIAL state
  780. * @param string $sAttCode The code of the attribute
  781. * @return integer Flags: the binary combination of the flags applicable to this attribute
  782. */
  783. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  784. {
  785. $iFlags = 0;
  786. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  787. if (!empty($sStateAttCode))
  788. {
  789. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  790. }
  791. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  792. }
  793. // check if the given (or current) value is suitable for the attribute
  794. // return true if successfull
  795. // return the error desciption otherwise
  796. public function CheckValue($sAttCode, $value = null)
  797. {
  798. if (!is_null($value))
  799. {
  800. $toCheck = $value;
  801. }
  802. else
  803. {
  804. $toCheck = $this->Get($sAttCode);
  805. }
  806. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  807. if (!$oAtt->IsWritable())
  808. {
  809. return true;
  810. }
  811. elseif ($oAtt->IsNull($toCheck))
  812. {
  813. if ($oAtt->IsNullAllowed())
  814. {
  815. return true;
  816. }
  817. else
  818. {
  819. return "Null not allowed";
  820. }
  821. }
  822. elseif ($oAtt->IsExternalKey())
  823. {
  824. if (!MetaModel::SkipCheckExtKeys())
  825. {
  826. $sTargetClass = $oAtt->GetTargetClass();
  827. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  828. if (is_null($oTargetObj))
  829. {
  830. return "Target object not found ($sTargetClass::$toCheck)";
  831. }
  832. }
  833. if ($oAtt->IsHierarchicalKey())
  834. {
  835. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  836. if ($toCheck == $this->GetKey())
  837. {
  838. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  839. }
  840. }
  841. }
  842. elseif ($oAtt->IsScalar())
  843. {
  844. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  845. if (count($aValues) > 0)
  846. {
  847. if (!array_key_exists($toCheck, $aValues))
  848. {
  849. return "Value not allowed [$toCheck]";
  850. }
  851. }
  852. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  853. {
  854. $iLen = strlen($toCheck);
  855. if ($iLen > $iMaxSize)
  856. {
  857. return "String too long (found $iLen, limited to $iMaxSize)";
  858. }
  859. }
  860. if (!$oAtt->CheckFormat($toCheck))
  861. {
  862. return "Wrong format [$toCheck]";
  863. }
  864. }
  865. return true;
  866. }
  867. // check attributes together
  868. public function CheckConsistency()
  869. {
  870. return true;
  871. }
  872. // check integrity rules (before inserting or updating the object)
  873. // a displayable error is returned
  874. public function DoCheckToWrite()
  875. {
  876. $this->DoComputeValues();
  877. $this->m_aCheckIssues = array();
  878. $aChanges = $this->ListChanges();
  879. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  880. {
  881. $res = $this->CheckValue($sAttCode);
  882. if ($res !== true)
  883. {
  884. // $res contains the error description
  885. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  886. }
  887. }
  888. if (count($this->m_aCheckIssues) > 0)
  889. {
  890. // No need to check consistency between attributes if any of them has
  891. // an unexpected value
  892. return;
  893. }
  894. $res = $this->CheckConsistency();
  895. if ($res !== true)
  896. {
  897. // $res contains the error description
  898. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  899. }
  900. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  901. //
  902. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  903. {
  904. foreach($aChanges as $sAttCode => $value)
  905. {
  906. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  907. if ($iFlags & OPT_ATT_SLAVE)
  908. {
  909. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  910. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  911. $sAttLabel = $oAttDef->GetLabel();
  912. foreach($aReasons as $aReasonInfo)
  913. {
  914. // Todo: associate the attribute code with the error
  915. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  916. }
  917. }
  918. }
  919. }
  920. }
  921. final public function CheckToWrite()
  922. {
  923. if (MetaModel::SkipCheckToWrite())
  924. {
  925. return array(true, array());
  926. }
  927. if (is_null($this->m_bCheckStatus))
  928. {
  929. $oKPI = new ExecutionKPI();
  930. $this->DoCheckToWrite();
  931. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  932. if (count($this->m_aCheckIssues) == 0)
  933. {
  934. $this->m_bCheckStatus = true;
  935. }
  936. else
  937. {
  938. $this->m_bCheckStatus = false;
  939. }
  940. }
  941. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  942. }
  943. // check if it is allowed to delete the existing object from the database
  944. // a displayable error is returned
  945. protected function DoCheckToDelete(&$oDeletionPlan)
  946. {
  947. $this->m_aDeleteIssues = array(); // Ok
  948. if ($this->InSyncScope())
  949. {
  950. $oReplicaSet = $this->GetMasterReplica();
  951. if ($oReplicaSet->Count() > 0)
  952. {
  953. while($aData = $oReplicaSet->FetchAssoc())
  954. {
  955. $oDataSource = $aData['datasource'];
  956. $oReplica = $aData['replica'];
  957. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  958. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  959. {
  960. // The current task has the right to delete the object
  961. continue;
  962. }
  963. if ($oReplica->Get('status_dest_creator') != 1)
  964. {
  965. // The object is not owned by the task
  966. continue;
  967. }
  968. $sLink = $oDataSource->GetName();
  969. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  970. switch($sUserDeletePolicy)
  971. {
  972. case 'nobody':
  973. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  974. break;
  975. case 'administrators':
  976. if (!UserRights::IsAdministrator())
  977. {
  978. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  979. }
  980. break;
  981. case 'everybody':
  982. default:
  983. // Ok
  984. break;
  985. }
  986. }
  987. }
  988. }
  989. }
  990. final public function CheckToDelete(&$oDeletionPlan)
  991. {
  992. $this->MakeDeletionPlan($oDeletionPlan);
  993. $oDeletionPlan->ComputeResults();
  994. return (!$oDeletionPlan->FoundStopper());
  995. }
  996. protected function ListChangedValues(array $aProposal)
  997. {
  998. $aDelta = array();
  999. foreach ($aProposal as $sAtt => $proposedValue)
  1000. {
  1001. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1002. {
  1003. // The value was not set
  1004. $aDelta[$sAtt] = $proposedValue;
  1005. }
  1006. elseif(is_object($proposedValue))
  1007. {
  1008. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1009. // The value is an object, the comparison is not strict
  1010. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  1011. {
  1012. $aDelta[$sAtt] = $proposedValue;
  1013. }
  1014. }
  1015. else
  1016. {
  1017. // The value is a scalar, the comparison must be 100% strict
  1018. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1019. {
  1020. //echo "$sAtt:<pre>\n";
  1021. //var_dump($this->m_aOrigValues[$sAtt]);
  1022. //var_dump($proposedValue);
  1023. //echo "</pre>\n";
  1024. $aDelta[$sAtt] = $proposedValue;
  1025. }
  1026. }
  1027. }
  1028. return $aDelta;
  1029. }
  1030. // List the attributes that have been changed
  1031. // Returns an array of attname => currentvalue
  1032. public function ListChanges()
  1033. {
  1034. if ($this->m_bIsInDB)
  1035. {
  1036. return $this->ListChangedValues($this->m_aCurrValues);
  1037. }
  1038. else
  1039. {
  1040. return $this->m_aCurrValues;
  1041. }
  1042. }
  1043. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1044. public function IsModified()
  1045. {
  1046. $aChanges = $this->ListChanges();
  1047. return (count($aChanges) != 0);
  1048. }
  1049. public function Equals($oSibling)
  1050. {
  1051. if (get_class($oSibling) != get_class($this))
  1052. {
  1053. return false;
  1054. }
  1055. if ($this->GetKey() != $oSibling->GetKey())
  1056. {
  1057. return false;
  1058. }
  1059. if ($this->m_bIsInDB)
  1060. {
  1061. // If one has changed, then consider them as being different
  1062. if ($this->IsModified() || $oSibling->IsModified())
  1063. {
  1064. return false;
  1065. }
  1066. }
  1067. else
  1068. {
  1069. // Todo - implement this case (loop on every attribute)
  1070. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1071. //{
  1072. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1073. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1074. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1075. //{
  1076. //return false;
  1077. //}
  1078. //}
  1079. return false;
  1080. }
  1081. return true;
  1082. }
  1083. // used both by insert/update
  1084. private function DBWriteLinks()
  1085. {
  1086. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1087. {
  1088. if (!$oAttDef->IsLinkSet()) continue;
  1089. $oLinks = $this->Get($sAttCode);
  1090. $oLinks->Rewind();
  1091. while ($oLinkedObject = $oLinks->Fetch())
  1092. {
  1093. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1094. if ($oLinkedObject->IsModified())
  1095. {
  1096. $oLinkedObject->DBWrite();
  1097. }
  1098. }
  1099. // Delete the objects that were initialy present and disappeared from the list
  1100. // (if any)
  1101. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  1102. if ($oOriginalSet != null)
  1103. {
  1104. $aOriginalList = $oOriginalSet->ToArray();
  1105. $aNewSet = $oLinks->ToArray();
  1106. foreach($aOriginalList as $iId => $oObject)
  1107. {
  1108. if (!array_key_exists($iId, $aNewSet))
  1109. {
  1110. // It disappeared from the list
  1111. $oObject->DBDelete();
  1112. }
  1113. }
  1114. }
  1115. }
  1116. }
  1117. // Note: this is experimental - it was designed to speed up the setup of iTop
  1118. // Known limitations:
  1119. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1120. // - the id of the object is not updated
  1121. static public final function BulkInsertStart()
  1122. {
  1123. self::$m_bBulkInsert = true;
  1124. }
  1125. static public final function BulkInsertFlush()
  1126. {
  1127. if (!self::$m_bBulkInsert) return;
  1128. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1129. {
  1130. foreach ($aTables as $sTable => $sColumns)
  1131. {
  1132. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1133. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1134. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1135. }
  1136. }
  1137. // Reset
  1138. self::$m_aBulkInsertItems = array();
  1139. self::$m_aBulkInsertCols = array();
  1140. self::$m_bBulkInsert = false;
  1141. }
  1142. private function DBInsertSingleTable($sTableClass)
  1143. {
  1144. $sTable = MetaModel::DBGetTable($sTableClass);
  1145. // Abstract classes or classes having no specific attribute do not have an associated table
  1146. if ($sTable == '') return;
  1147. $sClass = get_class($this);
  1148. // fields in first array, values in the second
  1149. $aFieldsToWrite = array();
  1150. $aValuesToWrite = array();
  1151. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1152. {
  1153. // Add it to the list of fields to write
  1154. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1155. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1156. }
  1157. $aHierarchicalKeys = array();
  1158. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1159. {
  1160. // Skip this attribute if not defined in this table
  1161. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1162. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1163. foreach($aAttColumns as $sColumn => $sValue)
  1164. {
  1165. $aFieldsToWrite[] = "`$sColumn`";
  1166. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1167. }
  1168. if ($oAttDef->IsHierarchicalKey())
  1169. {
  1170. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1171. }
  1172. }
  1173. if (count($aValuesToWrite) == 0) return false;
  1174. if (MetaModel::DBIsReadOnly())
  1175. {
  1176. $iNewKey = -1;
  1177. }
  1178. else
  1179. {
  1180. if (self::$m_bBulkInsert)
  1181. {
  1182. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1183. {
  1184. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1185. }
  1186. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1187. $iNewKey = 999999; // TODO - compute next id....
  1188. }
  1189. else
  1190. {
  1191. if (count($aHierarchicalKeys) > 0)
  1192. {
  1193. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1194. {
  1195. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1196. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1197. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1198. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1199. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1200. }
  1201. }
  1202. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1203. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1204. }
  1205. }
  1206. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1207. if (empty($this->m_iKey))
  1208. {
  1209. // Take the autonumber
  1210. $this->m_iKey = $iNewKey;
  1211. }
  1212. return $this->m_iKey;
  1213. }
  1214. // Insert of record for the new object into the database
  1215. // Returns the key of the newly created object
  1216. public function DBInsertNoReload()
  1217. {
  1218. if ($this->m_bIsInDB)
  1219. {
  1220. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1221. }
  1222. $sClass = get_class($this);
  1223. $sRootClass = MetaModel::GetRootClass($sClass);
  1224. // Ensure the update of the values (we are accessing the data directly)
  1225. $this->DoComputeValues();
  1226. $this->OnInsert();
  1227. if ($this->m_iKey < 0)
  1228. {
  1229. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1230. $this->m_iKey = null;
  1231. }
  1232. // If not automatically computed, then check that the key is given by the caller
  1233. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1234. {
  1235. if (empty($this->m_iKey))
  1236. {
  1237. 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));
  1238. }
  1239. }
  1240. // Ultimate check - ensure DB integrity
  1241. list($bRes, $aIssues) = $this->CheckToWrite();
  1242. if (!$bRes)
  1243. {
  1244. $sIssues = implode(', ', $aIssues);
  1245. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1246. }
  1247. // Stop watches
  1248. $sState = $this->GetState();
  1249. if ($sState != '')
  1250. {
  1251. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1252. {
  1253. if ($oAttDef instanceof AttributeStopWatch)
  1254. {
  1255. if (in_array($sState, $oAttDef->GetStates()))
  1256. {
  1257. // Start the stop watch and compute the deadlines
  1258. $oSW = $this->Get($sAttCode);
  1259. $oSW->Start($this, $oAttDef);
  1260. $oSW->ComputeDeadlines($this, $oAttDef);
  1261. $this->Set($sAttCode, $oSW);
  1262. }
  1263. }
  1264. }
  1265. }
  1266. // First query built upon on the root class, because the ID must be created first
  1267. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1268. // Then do the leaf class, if different from the root class
  1269. if ($sClass != $sRootClass)
  1270. {
  1271. $this->DBInsertSingleTable($sClass);
  1272. }
  1273. // Then do the other classes
  1274. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1275. {
  1276. if ($sParentClass == $sRootClass) continue;
  1277. $this->DBInsertSingleTable($sParentClass);
  1278. }
  1279. $this->DBWriteLinks();
  1280. $this->m_bIsInDB = true;
  1281. $this->m_bDirty = false;
  1282. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  1283. $this->m_aAsArgs = null;
  1284. $this->AfterInsert();
  1285. // Activate any existing trigger
  1286. $sClass = get_class($this);
  1287. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1288. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1289. while ($oTrigger = $oSet->Fetch())
  1290. {
  1291. $oTrigger->DoActivate($this->ToArgs('this'));
  1292. }
  1293. $this->RecordObjCreation();
  1294. return $this->m_iKey;
  1295. }
  1296. public function DBInsert()
  1297. {
  1298. $this->DBInsertNoReload();
  1299. $this->Reload();
  1300. return $this->m_iKey;
  1301. }
  1302. public function DBInsertTracked(CMDBChange $oChange)
  1303. {
  1304. CMDBObject::SetCurrentChange($oChange);
  1305. return $this->DBInsert();
  1306. }
  1307. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1308. {
  1309. CMDBObject::SetCurrentChange($oChange);
  1310. return $this->DBInsertNoReload();
  1311. }
  1312. // Creates a copy of the current object into the database
  1313. // Returns the id of the newly created object
  1314. public function DBClone($iNewKey = null)
  1315. {
  1316. $this->m_bIsInDB = false;
  1317. $this->m_iKey = $iNewKey;
  1318. $ret = $this->DBInsert();
  1319. $this->RecordObjCreation();
  1320. return $ret;
  1321. }
  1322. /**
  1323. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1324. * The purpose of this method is to reset the appropriate attributes of the object in
  1325. * order to make sure that the newly cloned object is really distinct from its clone
  1326. */
  1327. public function __clone()
  1328. {
  1329. $this->m_bIsInDB = false;
  1330. $this->m_bDirty = true;
  1331. $this->m_iKey = self::GetNextTempId(get_class($this));
  1332. }
  1333. // Update a record
  1334. public function DBUpdate()
  1335. {
  1336. if (!$this->m_bIsInDB)
  1337. {
  1338. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1339. }
  1340. // Stop watches
  1341. $sState = $this->GetState();
  1342. if ($sState != '')
  1343. {
  1344. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1345. {
  1346. if ($oAttDef instanceof AttributeStopWatch)
  1347. {
  1348. if (in_array($sState, $oAttDef->GetStates()))
  1349. {
  1350. // Compute or recompute the deadlines
  1351. $oSW = $this->Get($sAttCode);
  1352. $oSW->ComputeDeadlines($this, $oAttDef);
  1353. $this->Set($sAttCode, $oSW);
  1354. }
  1355. }
  1356. }
  1357. }
  1358. $this->DoComputeValues();
  1359. $this->OnUpdate();
  1360. $aChanges = $this->ListChanges();
  1361. if (count($aChanges) == 0)
  1362. {
  1363. // Attempting to update an unchanged object
  1364. return;
  1365. }
  1366. // Ultimate check - ensure DB integrity
  1367. list($bRes, $aIssues) = $this->CheckToWrite();
  1368. if (!$bRes)
  1369. {
  1370. $sIssues = implode(', ', $aIssues);
  1371. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1372. }
  1373. // Save the original values (will be reset to the new values when the object get written to the DB)
  1374. $aOriginalValues = $this->m_aOrigValues;
  1375. $bHasANewExternalKeyValue = false;
  1376. $aHierarchicalKeys = array();
  1377. foreach($aChanges as $sAttCode => $valuecurr)
  1378. {
  1379. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1380. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1381. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1382. if ($oAttDef->IsHierarchicalKey())
  1383. {
  1384. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1385. }
  1386. }
  1387. if (!MetaModel::DBIsReadOnly())
  1388. {
  1389. // Update the left & right indexes for each hierarchical key
  1390. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1391. {
  1392. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1393. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1394. $aRes = CMDBSource::QueryToArray($sSQL);
  1395. $iMyLeft = $aRes[0]['left'];
  1396. $iMyRight = $aRes[0]['right'];
  1397. $iDelta =$iMyRight - $iMyLeft + 1;
  1398. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1399. if ($aChanges[$sAttCode] == 0)
  1400. {
  1401. // No new parent, insert completely at the right of the tree
  1402. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1403. $aRes = CMDBSource::QueryToArray($sSQL);
  1404. if (count($aRes) == 0)
  1405. {
  1406. $iNewLeft = 1;
  1407. }
  1408. else
  1409. {
  1410. $iNewLeft = $aRes[0]['max']+1;
  1411. }
  1412. }
  1413. else
  1414. {
  1415. // Insert at the right of the specified parent
  1416. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aChanges[$sAttCode]);
  1417. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1418. }
  1419. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1420. $aHKChanges = array();
  1421. $aHKChanges[$sAttCode] = $aChanges[$sAttCode];
  1422. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1423. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1424. $aChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1425. }
  1426. // Update scalar attributes
  1427. if (count($aChanges) != 0)
  1428. {
  1429. $oFilter = new DBObjectSearch(get_class($this));
  1430. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1431. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1432. CMDBSource::Query($sSQL);
  1433. }
  1434. }
  1435. $this->DBWriteLinks();
  1436. $this->m_bDirty = false;
  1437. $this->AfterUpdate();
  1438. // Reload to get the external attributes
  1439. if ($bHasANewExternalKeyValue)
  1440. {
  1441. $this->Reload();
  1442. }
  1443. else
  1444. {
  1445. // Reset original values although the object has not been reloaded
  1446. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1447. {
  1448. if ($bLoaded)
  1449. {
  1450. $value = $this->m_aCurrValues[$sAttCode];
  1451. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1452. }
  1453. }
  1454. }
  1455. if (count($aChanges) != 0)
  1456. {
  1457. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1458. }
  1459. return $this->m_iKey;
  1460. }
  1461. public function DBUpdateTracked(CMDBChange $oChange)
  1462. {
  1463. CMDBObject::SetCurrentChange($oChange);
  1464. return $this->DBUpdate();
  1465. }
  1466. // Make the current changes persistent - clever wrapper for Insert or Update
  1467. public function DBWrite()
  1468. {
  1469. if ($this->m_bIsInDB)
  1470. {
  1471. return $this->DBUpdate();
  1472. }
  1473. else
  1474. {
  1475. return $this->DBInsert();
  1476. }
  1477. }
  1478. private function DBDeleteSingleTable($sTableClass)
  1479. {
  1480. $sTable = MetaModel::DBGetTable($sTableClass);
  1481. // Abstract classes or classes having no specific attribute do not have an associated table
  1482. if ($sTable == '') return;
  1483. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1484. $sKey = CMDBSource::Quote($this->m_iKey);
  1485. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1486. CMDBSource::DeleteFrom($sDeleteSQL);
  1487. }
  1488. protected function DBDeleteSingleObject()
  1489. {
  1490. if (!MetaModel::DBIsReadOnly())
  1491. {
  1492. $this->OnDelete();
  1493. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1494. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1495. {
  1496. if ($oAttDef->IsHierarchicalKey())
  1497. {
  1498. // Update the left & right indexes for each hierarchical key
  1499. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1500. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1501. $aRes = CMDBSource::QueryToArray($sSQL);
  1502. $iMyLeft = $aRes[0]['left'];
  1503. $iMyRight = $aRes[0]['right'];
  1504. $iDelta =$iMyRight - $iMyLeft + 1;
  1505. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1506. // No new parent for now, insert completely at the right of the tree
  1507. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1508. $aRes = CMDBSource::QueryToArray($sSQL);
  1509. if (count($aRes) == 0)
  1510. {
  1511. $iNewLeft = 1;
  1512. }
  1513. else
  1514. {
  1515. $iNewLeft = $aRes[0]['max']+1;
  1516. }
  1517. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1518. }
  1519. }
  1520. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1521. {
  1522. $this->DBDeleteSingleTable($sParentClass);
  1523. }
  1524. $this->AfterDelete();
  1525. $this->m_bIsInDB = false;
  1526. $this->m_iKey = null;
  1527. }
  1528. }
  1529. // Delete an object... and guarantee data integrity
  1530. //
  1531. public function DBDelete(&$oDeletionPlan = null)
  1532. {
  1533. if (is_null($oDeletionPlan))
  1534. {
  1535. $oDeletionPlan = new DeletionPlan();
  1536. }
  1537. $this->MakeDeletionPlan($oDeletionPlan);
  1538. $oDeletionPlan->ComputeResults();
  1539. if ($oDeletionPlan->FoundStopper())
  1540. {
  1541. $aIssues = $oDeletionPlan->GetIssues();
  1542. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1543. }
  1544. else
  1545. {
  1546. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1547. {
  1548. foreach ($aToDelete as $iId => $aData)
  1549. {
  1550. $oToDelete = $aData['to_delete'];
  1551. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1552. // because for each object we would try to update all the preceding ones... that are already deleted
  1553. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1554. // As a temporary fix: delete only the objects that are still to be deleted...
  1555. if ($oToDelete->m_bIsInDB)
  1556. {
  1557. $oToDelete->DBDeleteSingleObject();
  1558. }
  1559. }
  1560. }
  1561. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1562. {
  1563. foreach ($aToUpdate as $iId => $aData)
  1564. {
  1565. $oToUpdate = $aData['to_reset'];
  1566. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1567. {
  1568. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1569. $oToUpdate->DBUpdate();
  1570. }
  1571. }
  1572. }
  1573. }
  1574. return $oDeletionPlan;
  1575. }
  1576. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1577. {
  1578. CMDBObject::SetCurrentChange($oChange);
  1579. $this->DBDelete($oDeletionPlan);
  1580. }
  1581. public function EnumTransitions()
  1582. {
  1583. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1584. if (empty($sStateAttCode)) return array();
  1585. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1586. return MetaModel::EnumTransitions(get_class($this), $sState);
  1587. }
  1588. /**
  1589. * Designed as an action to be called when a stop watch threshold times out
  1590. * or from within the framework
  1591. */
  1592. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  1593. {
  1594. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1595. if (empty($sStateAttCode)) return false;
  1596. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1597. $aStateTransitions = $this->EnumTransitions();
  1598. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  1599. {
  1600. // This simulus has no effect in the current state... do nothing
  1601. return;
  1602. }
  1603. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1604. // Change the state before proceeding to the actions, this is necessary because an action might
  1605. // trigger another stimuli (alternative: push the stimuli into a queue)
  1606. $sPreviousState = $this->Get($sStateAttCode);
  1607. $sNewState = $aTransitionDef['target_state'];
  1608. $this->Set($sStateAttCode, $sNewState);
  1609. // $aTransitionDef is an
  1610. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1611. $bSuccess = true;
  1612. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1613. {
  1614. // std PHP spec
  1615. $aActionCallSpec = array($this, $sActionHandler);
  1616. if (!is_callable($aActionCallSpec))
  1617. {
  1618. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1619. return;
  1620. }
  1621. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1622. // if one call fails, the whole is considered as failed
  1623. if (!$bRet) $bSuccess = false;
  1624. }
  1625. if ($bSuccess)
  1626. {
  1627. $sClass = get_class($this);
  1628. // Stop watches
  1629. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1630. {
  1631. if ($oAttDef instanceof AttributeStopWatch)
  1632. {
  1633. $oSW = $this->Get($sAttCode);
  1634. if (in_array($sNewState, $oAttDef->GetStates()))
  1635. {
  1636. $oSW->Start($this, $oAttDef);
  1637. }
  1638. else
  1639. {
  1640. $oSW->Stop($this, $oAttDef);
  1641. }
  1642. $this->Set($sAttCode, $oSW);
  1643. }
  1644. }
  1645. if (!$bDoNotWrite)
  1646. {
  1647. $this->DBWrite();
  1648. }
  1649. // Change state triggers...
  1650. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1651. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1652. while ($oTrigger = $oSet->Fetch())
  1653. {
  1654. $oTrigger->DoActivate($this->ToArgs('this'));
  1655. }
  1656. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1657. while ($oTrigger = $oSet->Fetch())
  1658. {
  1659. $oTrigger->DoActivate($this->ToArgs('this'));
  1660. }
  1661. }
  1662. return $bSuccess;
  1663. }
  1664. /**
  1665. * Designed as an action to be called when a stop watch threshold times out
  1666. */
  1667. public function ResetStopWatch($sAttCode)
  1668. {
  1669. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1670. if (!$oAttDef instanceof AttributeStopWatch)
  1671. {
  1672. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  1673. }
  1674. $oSW = $this->Get($sAttCode);
  1675. $oSW->Reset($this, $oAttDef);
  1676. $this->Set($sAttCode, $oSW);
  1677. }
  1678. // Make standard context arguments
  1679. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1680. // Several options here:
  1681. // 1) cache the result
  1682. // 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)
  1683. public function ToArgs($sArgName = 'this')
  1684. {
  1685. if (is_null($this->m_aAsArgs))
  1686. {
  1687. $oKPI = new ExecutionKPI();
  1688. $aScalarArgs = array();
  1689. $aScalarArgs[$sArgName] = $this->GetKey();
  1690. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1691. $aScalarArgs[$sArgName.'->object()'] = $this;
  1692. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink('iTopStandardURLMaker', false);
  1693. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = $this->GetHyperlink('PortalURLMaker', false);
  1694. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1695. $sClass = get_class($this);
  1696. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1697. {
  1698. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1699. if ($oAttDef->IsScalar())
  1700. {
  1701. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1702. $sAsHtml = $this->GetAsHtml($sAttCode);
  1703. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1704. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = $this->GetEditValue($sAttCode); // "Nice" display value, but without HTML tags and entities
  1705. }
  1706. // Do something for case logs... quick N' dirty...
  1707. if ($aScalarArgs[$sArgName.'->'.$sAttCode] instanceof ormCaseLog)
  1708. {
  1709. $oCaseLog = $aScalarArgs[$sArgName.'->'.$sAttCode];
  1710. $aScalarArgs[$sArgName.'->'.$sAttCode] = $oCaseLog->GetText();
  1711. $aScalarArgs[$sArgName.'->head('.$sAttCode.')'] = $oCaseLog->GetLatestEntry();
  1712. }
  1713. }
  1714. $this->m_aAsArgs = $aScalarArgs;
  1715. $oKPI->ComputeStats('ToArgs', get_class($this));
  1716. }
  1717. return $this->m_aAsArgs;
  1718. }
  1719. // To be optionaly overloaded
  1720. protected function OnInsert()
  1721. {
  1722. }
  1723. // To be optionaly overloaded
  1724. protected function AfterInsert()
  1725. {
  1726. }
  1727. // To be optionaly overloaded
  1728. protected function OnUpdate()
  1729. {
  1730. }
  1731. // To be optionaly overloaded
  1732. protected function AfterUpdate()
  1733. {
  1734. }
  1735. // To be optionaly overloaded
  1736. protected function OnDelete()
  1737. {
  1738. }
  1739. // To be optionaly overloaded
  1740. protected function AfterDelete()
  1741. {
  1742. }
  1743. /**
  1744. * Common to the recording of link set changes (add/remove/modify)
  1745. */
  1746. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  1747. {
  1748. if ($iLinkSetOwnerId <= 0)
  1749. {
  1750. return null;
  1751. }
  1752. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  1753. {
  1754. // The link set owner class does not keep track of its history
  1755. return null;
  1756. }
  1757. // Determine the linked item class and id
  1758. //
  1759. if ($oLinkSet->IsIndirect())
  1760. {
  1761. // The "item" is on the other end (N-N links)
  1762. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  1763. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  1764. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  1765. if ($aOriginalValues)
  1766. {
  1767. // Get the value from the original values
  1768. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  1769. }
  1770. else
  1771. {
  1772. $iItemId = $this->Get($sExtKeyToRemote);
  1773. }
  1774. }
  1775. else
  1776. {
  1777. // I am the "item" (1-N links)
  1778. $sItemClass = get_class($this);
  1779. $iItemId = $this->GetKey();
  1780. }
  1781. // Get the remote object, to determine its exact class
  1782. // Possible optimization: implement a tool in MetaModel, to get the final class of an object (not always querying + query reduced to a select on the root table!
  1783. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  1784. if ($oOwner)
  1785. {
  1786. $sLinkSetOwnerClass = get_class($oOwner);
  1787. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  1788. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  1789. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  1790. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  1791. $oMyChangeOp->Set("item_class", $sItemClass);
  1792. $oMyChangeOp->Set("item_id", $iItemId);
  1793. return $oMyChangeOp;
  1794. }
  1795. else
  1796. {
  1797. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  1798. return null;
  1799. }
  1800. }
  1801. /**
  1802. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  1803. */
  1804. private function RecordLinkSetListChange($bAdd = true)
  1805. {
  1806. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1807. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1808. {
  1809. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1810. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  1811. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  1812. if ($oMyChangeOp)
  1813. {
  1814. if ($bAdd)
  1815. {
  1816. $oMyChangeOp->Set("type", "added");
  1817. }
  1818. else
  1819. {
  1820. $oMyChangeOp->Set("type", "removed");
  1821. }
  1822. $iId = $oMyChangeOp->DBInsertNoReload();
  1823. }
  1824. }
  1825. }
  1826. protected function RecordObjCreation()
  1827. {
  1828. $this->RecordLinkSetListChange(true);
  1829. }
  1830. protected function RecordObjDeletion($objkey)
  1831. {
  1832. $this->RecordLinkSetListChange(false);
  1833. }
  1834. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  1835. {
  1836. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1837. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1838. {
  1839. if (array_key_exists($sExtKeyAttCode, $aValues))
  1840. {
  1841. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1842. // Keep track of link added/removed
  1843. //
  1844. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  1845. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  1846. if ($oMyChangeOp)
  1847. {
  1848. $oMyChangeOp->Set("type", "added");
  1849. $oMyChangeOp->DBInsertNoReload();
  1850. }
  1851. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  1852. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  1853. if ($oMyChangeOp)
  1854. {
  1855. $oMyChangeOp->Set("type", "removed");
  1856. $oMyChangeOp->DBInsertNoReload();
  1857. }
  1858. }
  1859. else
  1860. {
  1861. // Keep track of link changes
  1862. //
  1863. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  1864. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  1865. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  1866. if ($oMyChangeOp)
  1867. {
  1868. $oMyChangeOp->Set("link_id", $this->GetKey());
  1869. $iId = $oMyChangeOp->DBInsertNoReload();
  1870. }
  1871. }
  1872. }
  1873. }
  1874. // Return an empty set for the parent of all
  1875. public static function GetRelationQueries($sRelCode)
  1876. {
  1877. return array();
  1878. }
  1879. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1880. {
  1881. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1882. {
  1883. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1884. $sQuery = $aQueryInfo["sQuery"];
  1885. $bPropagate = $aQueryInfo["bPropagate"];
  1886. $iDistance = $aQueryInfo["iDistance"];
  1887. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1888. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1889. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1890. while ($oObj = $oObjSet->Fetch())
  1891. {
  1892. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1893. $sObjKey = $oObj->GetKey();
  1894. if (array_key_exists($sRootClass, $aResults))
  1895. {
  1896. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1897. {
  1898. continue; // already visited, skip
  1899. }
  1900. }
  1901. $aResults[$sRootClass][$sObjKey] = $oObj;
  1902. if ($iDepth > 0)
  1903. {
  1904. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1905. }
  1906. }
  1907. }
  1908. return $aResults;
  1909. }
  1910. public function GetReferencingObjects($bAllowAllData = false)
  1911. {
  1912. $aDependentObjects = array();
  1913. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1914. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1915. {
  1916. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1917. {
  1918. // skip if this external key is behind an external field
  1919. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1920. $oSearch = new DBObjectSearch($sRemoteClass);
  1921. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1922. if ($bAllowAllData)
  1923. {
  1924. $oSearch->AllowAllData();
  1925. }
  1926. $oSet = new CMDBObjectSet($oSearch);
  1927. if ($oSet->Count() > 0)
  1928. {
  1929. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1930. 'attribute' => $oExtKeyAttDef,
  1931. 'objects' => $oSet,
  1932. );
  1933. }
  1934. }
  1935. }
  1936. return $aDependentObjects;
  1937. }
  1938. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  1939. {
  1940. $sClass = get_class($this);
  1941. $iThisId = $this->GetKey();
  1942. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  1943. if (array_key_exists($sClass, $aVisited))
  1944. {
  1945. if (in_array($iThisId, $aVisited[$sClass]))
  1946. {
  1947. return;
  1948. }
  1949. }
  1950. $aVisited[$sClass] = $iThisId;
  1951. if ($iDeleteOption == DEL_MANUAL)
  1952. {
  1953. // Stop the recursion here
  1954. return;
  1955. }
  1956. // Check the node itself
  1957. $this->DoCheckToDelete($oDeletionPlan);
  1958. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  1959. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  1960. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1961. {
  1962. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1963. {
  1964. $oAttDef = $aData['attribute'];
  1965. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1966. $oDepSet = $aData['objects'];
  1967. $oDepSet->Rewind();
  1968. while ($oDependentObj = $oDepSet->fetch())
  1969. {
  1970. $iId = $oDependentObj->GetKey();
  1971. if ($oAttDef->IsNullAllowed())
  1972. {
  1973. // Optional external key, list to reset
  1974. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  1975. {
  1976. // Move the child up one level i.e. set the same parent as the current object
  1977. $iParentId = $this->Get($oAttDef->GetCode());
  1978. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  1979. }
  1980. else
  1981. {
  1982. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  1983. }
  1984. }
  1985. else
  1986. {
  1987. // Mandatory external key, list to delete
  1988. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  1989. }
  1990. }
  1991. }
  1992. }
  1993. }
  1994. /**
  1995. * Get all the synchro replica related to this object
  1996. * @param none
  1997. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  1998. */
  1999. public function GetMasterReplica()
  2000. {
  2001. if ($this->m_oMasterReplicaSet == null)
  2002. {
  2003. //$aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  2004. //$sClassesList = "'".implode("','", $aParentClasses)."'";
  2005. $sOQL = "SELECT replica,datasource FROM SynchroReplica AS replica JOIN SynchroDataSource AS datasource ON replica.sync_source_id=datasource.id WHERE replica.dest_class = :dest_class AND replica.dest_id = :dest_id";
  2006. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2007. $this->m_oMasterReplicaSet = $oReplicaSet;
  2008. }
  2009. else
  2010. {
  2011. $this->m_oMasterReplicaSet->Rewind();
  2012. }
  2013. return $this->m_oMasterReplicaSet;
  2014. }
  2015. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2016. {
  2017. $iFlags = OPT_ATT_NORMAL;
  2018. $oSet = $this->GetMasterReplica();
  2019. while($aData = $oSet->FetchAssoc())
  2020. {
  2021. if ($aData['datasource']->GetKey() == SynchroExecution::GetCurrentTaskId())
  2022. {
  2023. // Ignore the current task (check to write => ok)
  2024. continue;
  2025. }
  2026. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2027. $oReplica = $aData['replica'];
  2028. $oSource = $aData['datasource'];
  2029. $oAttrSet = $oSource->Get('attribute_list');
  2030. while($oSyncAttr = $oAttrSet->Fetch())
  2031. {
  2032. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2033. {
  2034. $iFlags |= OPT_ATT_SLAVE;
  2035. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2036. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2037. }
  2038. }
  2039. }
  2040. return $iFlags;
  2041. }
  2042. public function InSyncScope()
  2043. {
  2044. return true;
  2045. // TODO - FINALIZE THIS OPTIMIZATION
  2046. //
  2047. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2048. //
  2049. static $aSynchroClasses = null;
  2050. if (is_null($aSynchroClasses))
  2051. {
  2052. $aSynchroClasses = array();
  2053. $sOQL = "SELECT SynchroDataSource AS datasource";
  2054. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2055. while($oSource = $oSourceSet->Fetch())
  2056. {
  2057. $sTarget = $oSource->Get('scope_class');
  2058. $aSynchroClasses[] = $oSource;
  2059. }
  2060. }
  2061. // to be continued...
  2062. }
  2063. }
  2064. ?>