dbobject.class.php 84 KB

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