dbobject.class.php 57 KB

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