dbobject.class.php 79 KB

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