dbobject.class.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  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);
  478. $sLabel = $oTmpObj->GetName();
  479. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  480. }
  481. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  482. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  483. if (strlen($sUrl) > 0)
  484. {
  485. return "<a href=\"$sUrl\" title=\"$sHint\">$sLabel</a>";
  486. }
  487. else
  488. {
  489. return $sLabel;
  490. }
  491. }
  492. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  493. {
  494. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext);
  495. }
  496. public static function ComputeStandardUIPage($sClass)
  497. {
  498. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  499. if (!isset($aUIPagesCache[$sClass]))
  500. {
  501. $UIPage = false;
  502. if (is_callable("$sClass::GetUIPage"))
  503. {
  504. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  505. }
  506. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  507. }
  508. $sPage = $aUIPagesCache[$sClass];
  509. return $sPage;
  510. }
  511. public static function GetUIPage()
  512. {
  513. return 'UI.php';
  514. }
  515. // could be in the metamodel ?
  516. public static function IsValidPKey($value)
  517. {
  518. return ((string)$value === (string)(int)$value);
  519. }
  520. public function GetKey()
  521. {
  522. return $this->m_iKey;
  523. }
  524. public function SetKey($iNewKey)
  525. {
  526. if (!self::IsValidPKey($iNewKey))
  527. {
  528. throw new CoreException("An object id must be an integer value ($iNewKey)");
  529. }
  530. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  531. {
  532. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  533. }
  534. $this->m_iKey = $iNewKey;
  535. }
  536. /**
  537. * Get the icon representing this object
  538. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  539. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  540. */
  541. public function GetIcon($bImgTag = true)
  542. {
  543. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  544. }
  545. public function GetName()
  546. {
  547. return $this->Get('friendlyname');
  548. }
  549. public function GetState()
  550. {
  551. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  552. if (empty($sStateAttCode))
  553. {
  554. return '';
  555. }
  556. else
  557. {
  558. return $this->Get($sStateAttCode);
  559. }
  560. }
  561. public function GetStateLabel()
  562. {
  563. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  564. if (empty($sStateAttCode))
  565. {
  566. return '';
  567. }
  568. else
  569. {
  570. $sStateValue = $this->Get($sStateAttCode);
  571. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  572. }
  573. }
  574. public function GetStateDescription()
  575. {
  576. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  577. if (empty($sStateAttCode))
  578. {
  579. return '';
  580. }
  581. else
  582. {
  583. $sStateValue = $this->Get($sStateAttCode);
  584. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  585. }
  586. }
  587. /**
  588. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  589. * for the given attribute in the current state of the object
  590. * @param string $sAttCode The code of the attribute
  591. * @return integer Flags: the binary combination of the flags applicable to this attribute
  592. */
  593. public function GetAttributeFlags($sAttCode, &$aReasons = array())
  594. {
  595. $iFlags = 0; // By default (if no life cycle) no flag at all
  596. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  597. if (!empty($sStateAttCode))
  598. {
  599. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  600. }
  601. $aReasons = array();
  602. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  603. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  604. }
  605. // check if the given (or current) value is suitable for the attribute
  606. // return true if successfull
  607. // return the error desciption otherwise
  608. public function CheckValue($sAttCode, $value = null)
  609. {
  610. if (!is_null($value))
  611. {
  612. $toCheck = $value;
  613. }
  614. else
  615. {
  616. $toCheck = $this->Get($sAttCode);
  617. }
  618. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  619. if (!$oAtt->IsWritable())
  620. {
  621. return true;
  622. }
  623. elseif ($oAtt->IsNull($toCheck))
  624. {
  625. if ($oAtt->IsNullAllowed())
  626. {
  627. return true;
  628. }
  629. else
  630. {
  631. return "Null not allowed";
  632. }
  633. }
  634. elseif ($oAtt->IsExternalKey())
  635. {
  636. if (!MetaModel::SkipCheckExtKeys())
  637. {
  638. $sTargetClass = $oAtt->GetTargetClass();
  639. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  640. if (is_null($oTargetObj))
  641. {
  642. return "Target object not found ($sTargetClass::$toCheck)";
  643. }
  644. }
  645. if ($oAtt->IsHierarchicalKey())
  646. {
  647. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  648. if ($toCheck == $this->GetKey())
  649. {
  650. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  651. }
  652. }
  653. }
  654. elseif ($oAtt->IsScalar())
  655. {
  656. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  657. if (count($aValues) > 0)
  658. {
  659. if (!array_key_exists($toCheck, $aValues))
  660. {
  661. return "Value not allowed [$toCheck]";
  662. }
  663. }
  664. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  665. {
  666. $iLen = strlen($toCheck);
  667. if ($iLen > $iMaxSize)
  668. {
  669. return "String too long (found $iLen, limited to $iMaxSize)";
  670. }
  671. }
  672. if (!$oAtt->CheckFormat($toCheck))
  673. {
  674. return "Wrong format [$toCheck]";
  675. }
  676. }
  677. return true;
  678. }
  679. // check attributes together
  680. public function CheckConsistency()
  681. {
  682. return true;
  683. }
  684. // check integrity rules (before inserting or updating the object)
  685. // a displayable error is returned
  686. public function DoCheckToWrite()
  687. {
  688. $this->DoComputeValues();
  689. $this->m_aCheckIssues = array();
  690. $aChanges = $this->ListChanges();
  691. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  692. {
  693. $res = $this->CheckValue($sAttCode);
  694. if ($res !== true)
  695. {
  696. // $res contains the error description
  697. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  698. }
  699. }
  700. if (count($this->m_aCheckIssues) > 0)
  701. {
  702. // No need to check consistency between attributes if any of them has
  703. // an unexpected value
  704. return;
  705. }
  706. $res = $this->CheckConsistency();
  707. if ($res !== true)
  708. {
  709. // $res contains the error description
  710. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  711. }
  712. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  713. //
  714. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  715. {
  716. foreach($aChanges as $sAttCode => $value)
  717. {
  718. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  719. if ($iFlags & OPT_ATT_SLAVE)
  720. {
  721. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  722. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  723. $sAttLabel = $oAttDef->GetLabel();
  724. foreach($aReasons as $aReasonInfo)
  725. {
  726. // Todo: associate the attribute code with the error
  727. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  728. }
  729. }
  730. }
  731. }
  732. }
  733. final public function CheckToWrite()
  734. {
  735. if (MetaModel::SkipCheckToWrite())
  736. {
  737. return array(true, array());
  738. }
  739. if (is_null($this->m_bCheckStatus))
  740. {
  741. $oKPI = new ExecutionKPI();
  742. $this->DoCheckToWrite();
  743. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  744. if (count($this->m_aCheckIssues) == 0)
  745. {
  746. $this->m_bCheckStatus = true;
  747. }
  748. else
  749. {
  750. $this->m_bCheckStatus = false;
  751. }
  752. }
  753. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  754. }
  755. // check if it is allowed to delete the existing object from the database
  756. // a displayable error is returned
  757. protected function DoCheckToDelete(&$oDeletionPlan)
  758. {
  759. $this->m_aDeleteIssues = array(); // Ok
  760. if ($this->InSyncScope())
  761. {
  762. $oReplicaSet = $this->GetMasterReplica();
  763. if ($oReplicaSet->Count() > 0)
  764. {
  765. while($aData = $oReplicaSet->FetchAssoc())
  766. {
  767. $oDataSource = $aData['datasource'];
  768. $oReplica = $aData['replica'];
  769. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  770. if ($oDataSource->GetKey() == SynchroDataSource::GetCurrentTaskId())
  771. {
  772. // The current task has the right to delete the object
  773. continue;
  774. }
  775. if ($oReplica->Get('status_dest_creator') != 1)
  776. {
  777. // The object is not owned by the task
  778. continue;
  779. }
  780. $sLink = $oDataSource->GetName();
  781. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  782. switch($sUserDeletePolicy)
  783. {
  784. case 'nobody':
  785. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  786. break;
  787. case 'administrators':
  788. if (!UserRights::IsAdministrator())
  789. {
  790. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  791. }
  792. break;
  793. case 'everybody':
  794. default:
  795. // Ok
  796. break;
  797. }
  798. }
  799. }
  800. }
  801. }
  802. final public function CheckToDelete(&$oDeletionPlan)
  803. {
  804. $this->MakeDeletionPlan($oDeletionPlan);
  805. $oDeletionPlan->ComputeResults();
  806. return (!$oDeletionPlan->FoundStopper());
  807. }
  808. protected function ListChangedValues(array $aProposal)
  809. {
  810. $aDelta = array();
  811. foreach ($aProposal as $sAtt => $proposedValue)
  812. {
  813. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  814. {
  815. // The value was not set
  816. $aDelta[$sAtt] = $proposedValue;
  817. }
  818. elseif(is_object($proposedValue))
  819. {
  820. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  821. // The value is an object, the comparison is not strict
  822. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  823. {
  824. $aDelta[$sAtt] = $proposedValue;
  825. }
  826. }
  827. else
  828. {
  829. // The value is a scalar, the comparison must be 100% strict
  830. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  831. {
  832. //echo "$sAtt:<pre>\n";
  833. //var_dump($this->m_aOrigValues[$sAtt]);
  834. //var_dump($proposedValue);
  835. //echo "</pre>\n";
  836. $aDelta[$sAtt] = $proposedValue;
  837. }
  838. }
  839. }
  840. return $aDelta;
  841. }
  842. // List the attributes that have been changed
  843. // Returns an array of attname => currentvalue
  844. public function ListChanges()
  845. {
  846. if ($this->m_bIsInDB)
  847. {
  848. return $this->ListChangedValues($this->m_aCurrValues);
  849. }
  850. else
  851. {
  852. return $this->m_aCurrValues;
  853. }
  854. }
  855. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  856. public function IsModified()
  857. {
  858. $aChanges = $this->ListChanges();
  859. return (count($aChanges) != 0);
  860. }
  861. public function Equals($oSibling)
  862. {
  863. if (get_class($oSibling) != get_class($this))
  864. {
  865. return false;
  866. }
  867. if ($this->GetKey() != $oSibling->GetKey())
  868. {
  869. return false;
  870. }
  871. if ($this->m_bIsInDB)
  872. {
  873. // If one has changed, then consider them as being different
  874. if ($this->IsModified() || $oSibling->IsModified())
  875. {
  876. return false;
  877. }
  878. }
  879. else
  880. {
  881. // Todo - implement this case (loop on every attribute)
  882. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  883. //{
  884. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  885. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  886. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  887. //{
  888. //return false;
  889. //}
  890. //}
  891. return false;
  892. }
  893. return true;
  894. }
  895. // used both by insert/update
  896. private function DBWriteLinks()
  897. {
  898. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  899. {
  900. if (!$oAttDef->IsLinkSet()) continue;
  901. $oLinks = $this->Get($sAttCode);
  902. $oLinks->Rewind();
  903. while ($oLinkedObject = $oLinks->Fetch())
  904. {
  905. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  906. if ($oLinkedObject->IsModified())
  907. {
  908. $oLinkedObject->DBWrite();
  909. }
  910. }
  911. // Delete the objects that were initialy present and disappeared from the list
  912. // (if any)
  913. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  914. if ($oOriginalSet != null)
  915. {
  916. $aOriginalList = $oOriginalSet->ToArray();
  917. $aNewSet = $oLinks->ToArray();
  918. foreach($aOriginalList as $iId => $oObject)
  919. {
  920. if (!array_key_exists($iId, $aNewSet))
  921. {
  922. // It disappeared from the list
  923. $oObject->DBDelete();
  924. }
  925. }
  926. }
  927. }
  928. }
  929. // Note: this is experimental - it was designed to speed up the setup of iTop
  930. // Known limitations:
  931. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  932. // - the id of the object is not updated
  933. static public final function BulkInsertStart()
  934. {
  935. self::$m_bBulkInsert = true;
  936. }
  937. static public final function BulkInsertFlush()
  938. {
  939. if (!self::$m_bBulkInsert) return;
  940. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  941. {
  942. foreach ($aTables as $sTable => $sColumns)
  943. {
  944. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  945. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  946. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  947. }
  948. }
  949. // Reset
  950. self::$m_aBulkInsertItems = array();
  951. self::$m_aBulkInsertCols = array();
  952. self::$m_bBulkInsert = false;
  953. }
  954. private function DBInsertSingleTable($sTableClass)
  955. {
  956. $sTable = MetaModel::DBGetTable($sTableClass);
  957. // Abstract classes or classes having no specific attribute do not have an associated table
  958. if ($sTable == '') return;
  959. $sClass = get_class($this);
  960. // fields in first array, values in the second
  961. $aFieldsToWrite = array();
  962. $aValuesToWrite = array();
  963. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  964. {
  965. // Add it to the list of fields to write
  966. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  967. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  968. }
  969. $aHierarchicalKeys = array();
  970. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  971. {
  972. // Skip this attribute if not defined in this table
  973. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  974. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  975. foreach($aAttColumns as $sColumn => $sValue)
  976. {
  977. $aFieldsToWrite[] = "`$sColumn`";
  978. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  979. }
  980. if ($oAttDef->IsHierarchicalKey())
  981. {
  982. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  983. }
  984. }
  985. if (count($aValuesToWrite) == 0) return false;
  986. if (MetaModel::DBIsReadOnly())
  987. {
  988. $iNewKey = -1;
  989. }
  990. else
  991. {
  992. if (self::$m_bBulkInsert)
  993. {
  994. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  995. {
  996. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  997. }
  998. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  999. $iNewKey = 999999; // TODO - compute next id....
  1000. }
  1001. else
  1002. {
  1003. if (count($aHierarchicalKeys) > 0)
  1004. {
  1005. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1006. {
  1007. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1008. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1009. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1010. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1011. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1012. }
  1013. }
  1014. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1015. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1016. }
  1017. }
  1018. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1019. if (empty($this->m_iKey))
  1020. {
  1021. // Take the autonumber
  1022. $this->m_iKey = $iNewKey;
  1023. }
  1024. return $this->m_iKey;
  1025. }
  1026. // Insert of record for the new object into the database
  1027. // Returns the key of the newly created object
  1028. public function DBInsertNoReload()
  1029. {
  1030. if ($this->m_bIsInDB)
  1031. {
  1032. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1033. }
  1034. $sClass = get_class($this);
  1035. $sRootClass = MetaModel::GetRootClass($sClass);
  1036. // Ensure the update of the values (we are accessing the data directly)
  1037. $this->DoComputeValues();
  1038. $this->OnInsert();
  1039. if ($this->m_iKey < 0)
  1040. {
  1041. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1042. $this->m_iKey = null;
  1043. }
  1044. // If not automatically computed, then check that the key is given by the caller
  1045. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1046. {
  1047. if (empty($this->m_iKey))
  1048. {
  1049. 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));
  1050. }
  1051. }
  1052. // Ultimate check - ensure DB integrity
  1053. list($bRes, $aIssues) = $this->CheckToWrite();
  1054. if (!$bRes)
  1055. {
  1056. $sIssues = implode(', ', $aIssues);
  1057. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1058. }
  1059. // First query built upon on the root class, because the ID must be created first
  1060. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1061. // Then do the leaf class, if different from the root class
  1062. if ($sClass != $sRootClass)
  1063. {
  1064. $this->DBInsertSingleTable($sClass);
  1065. }
  1066. // Then do the other classes
  1067. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1068. {
  1069. if ($sParentClass == $sRootClass) continue;
  1070. $this->DBInsertSingleTable($sParentClass);
  1071. }
  1072. $this->DBWriteLinks();
  1073. $this->m_bIsInDB = true;
  1074. $this->m_bDirty = false;
  1075. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  1076. $this->m_aAsArgs = null;
  1077. $this->AfterInsert();
  1078. // Activate any existing trigger
  1079. $sClass = get_class($this);
  1080. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1081. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1082. while ($oTrigger = $oSet->Fetch())
  1083. {
  1084. $oTrigger->DoActivate($this->ToArgs('this'));
  1085. }
  1086. return $this->m_iKey;
  1087. }
  1088. public function DBInsert()
  1089. {
  1090. $this->DBInsertNoReload();
  1091. $this->Reload();
  1092. return $this->m_iKey;
  1093. }
  1094. public function DBInsertTracked(CMDBChange $oVoid)
  1095. {
  1096. return $this->DBInsert();
  1097. }
  1098. // Creates a copy of the current object into the database
  1099. // Returns the id of the newly created object
  1100. public function DBClone($iNewKey = null)
  1101. {
  1102. $this->m_bIsInDB = false;
  1103. $this->m_iKey = $iNewKey;
  1104. return $this->DBInsert();
  1105. }
  1106. /**
  1107. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1108. * The purpose of this method is to reset the appropriate attributes of the object in
  1109. * order to make sure that the newly cloned object is really distinct from its clone
  1110. */
  1111. public function __clone()
  1112. {
  1113. $this->m_bIsInDB = false;
  1114. $this->m_bDirty = true;
  1115. $this->m_iKey = self::GetNextTempId(get_class($this));
  1116. }
  1117. // Update a record
  1118. public function DBUpdate()
  1119. {
  1120. if (!$this->m_bIsInDB)
  1121. {
  1122. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1123. }
  1124. $this->DoComputeValues();
  1125. $this->OnUpdate();
  1126. $aChanges = $this->ListChanges();
  1127. if (count($aChanges) == 0)
  1128. {
  1129. //throw new CoreWarning("Attempting to update an unchanged object");
  1130. return;
  1131. }
  1132. // Ultimate check - ensure DB integrity
  1133. list($bRes, $aIssues) = $this->CheckToWrite();
  1134. if (!$bRes)
  1135. {
  1136. $sIssues = implode(', ', $aIssues);
  1137. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1138. }
  1139. $bHasANewExternalKeyValue = false;
  1140. $aHierarchicalKeys = array();
  1141. foreach($aChanges as $sAttCode => $valuecurr)
  1142. {
  1143. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1144. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1145. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1146. if ($oAttDef->IsHierarchicalKey())
  1147. {
  1148. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1149. }
  1150. }
  1151. if (!MetaModel::DBIsReadOnly())
  1152. {
  1153. // Update the left & right indexes for each hierarchical key
  1154. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1155. {
  1156. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1157. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1158. $aRes = CMDBSource::QueryToArray($sSQL);
  1159. $iMyLeft = $aRes[0]['left'];
  1160. $iMyRight = $aRes[0]['right'];
  1161. $iDelta =$iMyRight - $iMyLeft + 1;
  1162. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1163. if ($aChanges[$sAttCode] == 0)
  1164. {
  1165. // No new parent, insert completely at the right of the tree
  1166. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1167. $aRes = CMDBSource::QueryToArray($sSQL);
  1168. if (count($aRes) == 0)
  1169. {
  1170. $iNewLeft = 1;
  1171. }
  1172. else
  1173. {
  1174. $iNewLeft = $aRes[0]['max']+1;
  1175. }
  1176. }
  1177. else
  1178. {
  1179. // Insert at the right of the specified parent
  1180. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aChanges[$sAttCode]);
  1181. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1182. }
  1183. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1184. $aHKChanges = array();
  1185. $aHKChanges[$sAttCode] = $aChanges[$sAttCode];
  1186. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1187. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1188. $aChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1189. }
  1190. // Update scalar attributes
  1191. if (count($aChanges) != 0)
  1192. {
  1193. $oFilter = new DBObjectSearch(get_class($this));
  1194. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1195. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1196. CMDBSource::Query($sSQL);
  1197. }
  1198. }
  1199. $this->DBWriteLinks();
  1200. $this->m_bDirty = false;
  1201. $this->AfterUpdate();
  1202. // Reload to get the external attributes
  1203. if ($bHasANewExternalKeyValue)
  1204. {
  1205. $this->Reload();
  1206. }
  1207. return $this->m_iKey;
  1208. }
  1209. public function DBUpdateTracked(CMDBChange $oVoid)
  1210. {
  1211. return $this->DBUpdate();
  1212. }
  1213. // Make the current changes persistent - clever wrapper for Insert or Update
  1214. public function DBWrite()
  1215. {
  1216. if ($this->m_bIsInDB)
  1217. {
  1218. return $this->DBUpdate();
  1219. }
  1220. else
  1221. {
  1222. return $this->DBInsert();
  1223. }
  1224. }
  1225. private function DBDeleteSingleTable($sTableClass)
  1226. {
  1227. $sTable = MetaModel::DBGetTable($sTableClass);
  1228. // Abstract classes or classes having no specific attribute do not have an associated table
  1229. if ($sTable == '') return;
  1230. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1231. $sKey = CMDBSource::Quote($this->m_iKey);
  1232. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1233. CMDBSource::DeleteFrom($sDeleteSQL);
  1234. }
  1235. protected function DBDeleteSingleObject()
  1236. {
  1237. $this->OnDelete();
  1238. if (!MetaModel::DBIsReadOnly())
  1239. {
  1240. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1241. {
  1242. if ($oAttDef->IsHierarchicalKey())
  1243. {
  1244. // Update the left & right indexes for each hierarchical key
  1245. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1246. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1247. $aRes = CMDBSource::QueryToArray($sSQL);
  1248. $iMyLeft = $aRes[0]['left'];
  1249. $iMyRight = $aRes[0]['right'];
  1250. $iDelta =$iMyRight - $iMyLeft + 1;
  1251. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1252. // No new parent for now, insert completely at the right of the tree
  1253. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1254. $aRes = CMDBSource::QueryToArray($sSQL);
  1255. if (count($aRes) == 0)
  1256. {
  1257. $iNewLeft = 1;
  1258. }
  1259. else
  1260. {
  1261. $iNewLeft = $aRes[0]['max']+1;
  1262. }
  1263. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1264. }
  1265. }
  1266. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1267. {
  1268. $this->DBDeleteSingleTable($sParentClass);
  1269. }
  1270. }
  1271. $this->AfterDelete();
  1272. $this->m_bIsInDB = false;
  1273. $this->m_iKey = null;
  1274. }
  1275. // Delete an object... and guarantee data integrity
  1276. //
  1277. public function DBDelete(&$oDeletionPlan = null)
  1278. {
  1279. if (is_null($oDeletionPlan))
  1280. {
  1281. $oDeletionPlan = new DeletionPlan();
  1282. }
  1283. $this->MakeDeletionPlan($oDeletionPlan);
  1284. $oDeletionPlan->ComputeResults();
  1285. if ($oDeletionPlan->FoundStopper())
  1286. {
  1287. $aIssues = $oDeletionPlan->GetIssues();
  1288. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1289. }
  1290. else
  1291. {
  1292. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1293. {
  1294. foreach ($aToDelete as $iId => $aData)
  1295. {
  1296. $oToDelete = $aData['to_delete'];
  1297. $oToDelete->DBDeleteSingleObject();
  1298. }
  1299. }
  1300. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1301. {
  1302. foreach ($aToUpdate as $iId => $aData)
  1303. {
  1304. $oToUpdate = $aData['to_reset'];
  1305. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1306. {
  1307. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1308. $oToUpdate->DBUpdate();
  1309. }
  1310. }
  1311. }
  1312. }
  1313. return $oDeletionPlan;
  1314. }
  1315. public function DBDeleteTracked(CMDBChange $oVoid, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1316. {
  1317. $this->DBDelete($oDeletionPlan);
  1318. }
  1319. public function EnumTransitions()
  1320. {
  1321. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1322. if (empty($sStateAttCode)) return array();
  1323. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1324. return MetaModel::EnumTransitions(get_class($this), $sState);
  1325. }
  1326. public function ApplyStimulus($sStimulusCode)
  1327. {
  1328. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1329. if (empty($sStateAttCode)) return false;
  1330. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1331. $aStateTransitions = $this->EnumTransitions();
  1332. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1333. // Change the state before proceeding to the actions, this is necessary because an action might
  1334. // trigger another stimuli (alternative: push the stimuli into a queue)
  1335. $sPreviousState = $this->Get($sStateAttCode);
  1336. $sNewState = $aTransitionDef['target_state'];
  1337. $this->Set($sStateAttCode, $sNewState);
  1338. // $aTransitionDef is an
  1339. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1340. $bSuccess = true;
  1341. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1342. {
  1343. // std PHP spec
  1344. $aActionCallSpec = array($this, $sActionHandler);
  1345. if (!is_callable($aActionCallSpec))
  1346. {
  1347. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1348. return;
  1349. }
  1350. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1351. // if one call fails, the whole is considered as failed
  1352. if (!$bRet) $bSuccess = false;
  1353. }
  1354. // Change state triggers...
  1355. $sClass = get_class($this);
  1356. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1357. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1358. while ($oTrigger = $oSet->Fetch())
  1359. {
  1360. $oTrigger->DoActivate($this->ToArgs('this'));
  1361. }
  1362. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1363. while ($oTrigger = $oSet->Fetch())
  1364. {
  1365. $oTrigger->DoActivate($this->ToArgs('this'));
  1366. }
  1367. return $bSuccess;
  1368. }
  1369. // Make standard context arguments
  1370. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1371. // Several options here:
  1372. // 1) cache the result
  1373. // 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)
  1374. public function ToArgs($sArgName = 'this')
  1375. {
  1376. if (is_null($this->m_aAsArgs))
  1377. {
  1378. $oKPI = new ExecutionKPI();
  1379. $aScalarArgs = array();
  1380. $aScalarArgs[$sArgName] = $this->GetKey();
  1381. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1382. $aScalarArgs[$sArgName.'->object()'] = $this;
  1383. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink('iTopStandardURLMaker', false);
  1384. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = $this->GetHyperlink('PortalURLMaker', false);
  1385. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1386. $sClass = get_class($this);
  1387. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1388. {
  1389. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1390. if ($oAttDef->IsScalar())
  1391. {
  1392. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1393. $sAsHtml = $this->GetAsHtml($sAttCode);
  1394. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1395. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1396. }
  1397. }
  1398. $this->m_aAsArgs = $aScalarArgs;
  1399. $oKPI->ComputeStats('ToArgs', get_class($this));
  1400. }
  1401. return $this->m_aAsArgs;
  1402. }
  1403. // To be optionaly overloaded
  1404. protected function OnInsert()
  1405. {
  1406. }
  1407. // To be optionaly overloaded
  1408. protected function AfterInsert()
  1409. {
  1410. }
  1411. // To be optionaly overloaded
  1412. protected function OnUpdate()
  1413. {
  1414. }
  1415. // To be optionaly overloaded
  1416. protected function AfterUpdate()
  1417. {
  1418. }
  1419. // To be optionaly overloaded
  1420. protected function OnDelete()
  1421. {
  1422. }
  1423. // To be optionaly overloaded
  1424. protected function AfterDelete()
  1425. {
  1426. }
  1427. // Return an empty set for the parent of all
  1428. public static function GetRelationQueries($sRelCode)
  1429. {
  1430. return array();
  1431. }
  1432. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1433. {
  1434. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1435. {
  1436. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1437. $sQuery = $aQueryInfo["sQuery"];
  1438. $bPropagate = $aQueryInfo["bPropagate"];
  1439. $iDistance = $aQueryInfo["iDistance"];
  1440. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1441. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1442. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1443. while ($oObj = $oObjSet->Fetch())
  1444. {
  1445. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1446. $sObjKey = $oObj->GetKey();
  1447. if (array_key_exists($sRootClass, $aResults))
  1448. {
  1449. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1450. {
  1451. continue; // already visited, skip
  1452. }
  1453. }
  1454. $aResults[$sRootClass][$sObjKey] = $oObj;
  1455. if ($iDepth > 0)
  1456. {
  1457. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1458. }
  1459. }
  1460. }
  1461. return $aResults;
  1462. }
  1463. public function GetReferencingObjects($bAllowAllData = false)
  1464. {
  1465. $aDependentObjects = array();
  1466. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1467. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1468. {
  1469. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1470. {
  1471. // skip if this external key is behind an external field
  1472. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1473. $oSearch = new DBObjectSearch($sRemoteClass);
  1474. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1475. if ($bAllowAllData)
  1476. {
  1477. $oSearch->AllowAllData();
  1478. }
  1479. $oSet = new CMDBObjectSet($oSearch);
  1480. if ($oSet->Count() > 0)
  1481. {
  1482. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1483. 'attribute' => $oExtKeyAttDef,
  1484. 'objects' => $oSet,
  1485. );
  1486. }
  1487. }
  1488. }
  1489. return $aDependentObjects;
  1490. }
  1491. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  1492. {
  1493. $sClass = get_class($this);
  1494. $iThisId = $this->GetKey();
  1495. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  1496. if (array_key_exists($sClass, $aVisited))
  1497. {
  1498. if (in_array($iThisId, $aVisited[$sClass]))
  1499. {
  1500. return;
  1501. }
  1502. }
  1503. $aVisited[$sClass] = $iThisId;
  1504. if ($iDeleteOption == DEL_MANUAL)
  1505. {
  1506. // Stop the recursion here
  1507. return;
  1508. }
  1509. // Check the node itself
  1510. $this->DoCheckToDelete($oDeletionPlan);
  1511. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  1512. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  1513. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1514. {
  1515. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1516. {
  1517. $oAttDef = $aData['attribute'];
  1518. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1519. $oDepSet = $aData['objects'];
  1520. $oDepSet->Rewind();
  1521. while ($oDependentObj = $oDepSet->fetch())
  1522. {
  1523. $iId = $oDependentObj->GetKey();
  1524. if ($oAttDef->IsNullAllowed())
  1525. {
  1526. // Optional external key, list to reset
  1527. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  1528. {
  1529. // Move the child up one level i.e. set the same parent as the current object
  1530. $iParentId = $this->Get($oAttDef->GetCode());
  1531. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  1532. }
  1533. else
  1534. {
  1535. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  1536. }
  1537. }
  1538. else
  1539. {
  1540. // Mandatory external key, list to delete
  1541. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  1542. }
  1543. }
  1544. }
  1545. }
  1546. }
  1547. /**
  1548. * Get all the synchro replica related to this object
  1549. * @param none
  1550. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  1551. */
  1552. public function GetMasterReplica()
  1553. {
  1554. if ($this->m_oMasterReplicaSet == null)
  1555. {
  1556. //$aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  1557. //$sClassesList = "'".implode("','", $aParentClasses)."'";
  1558. $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";
  1559. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  1560. $this->m_oMasterReplicaSet = $oReplicaSet;
  1561. }
  1562. else
  1563. {
  1564. $this->m_oMasterReplicaSet->Rewind();
  1565. }
  1566. return $this->m_oMasterReplicaSet;
  1567. }
  1568. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  1569. {
  1570. $iFlags = OPT_ATT_NORMAL;
  1571. $oSet = $this->GetMasterReplica();
  1572. while($aData = $oSet->FetchAssoc())
  1573. {
  1574. if ($aData['datasource']->GetKey() == SynchroDataSource::GetCurrentTaskId())
  1575. {
  1576. // Ignore the current task (check to write => ok)
  1577. continue;
  1578. }
  1579. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  1580. $oReplica = $aData['replica'];
  1581. $oSource = $aData['datasource'];
  1582. $oAttrSet = $oSource->Get('attribute_list');
  1583. while($oSyncAttr = $oAttrSet->Fetch())
  1584. {
  1585. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  1586. {
  1587. $iFlags |= OPT_ATT_SLAVE;
  1588. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  1589. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  1590. }
  1591. }
  1592. }
  1593. return $iFlags;
  1594. }
  1595. public function InSyncScope()
  1596. {
  1597. return true;
  1598. // TODO - FINALIZE THIS OPTIMIZATION
  1599. //
  1600. // Optimization: cache the list of Data Sources and classes candidates for synchro
  1601. //
  1602. static $aSynchroClasses = null;
  1603. if (is_null($aSynchroClasses))
  1604. {
  1605. $aSynchroClasses = array();
  1606. $sOQL = "SELECT SynchroDataSource AS datasource";
  1607. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  1608. while($oSource = $oSourceSet->Fetch())
  1609. {
  1610. $sTarget = $oSource->Get('scope_class');
  1611. $aSynchroClasses[] = $oSource;
  1612. }
  1613. }
  1614. // to be continued...
  1615. }
  1616. }
  1617. ?>