dbobject.class.php 62 KB

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