dbobject.class.php 75 KB

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