dbobject.class.php 60 KB

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