dbobject.class.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  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. if (method_exists(get_class($this), 'GetConstantColumns'))
  711. {
  712. if (in_array($sAttCode, $this->GetConstantColumns()))
  713. {
  714. return OPT_ATT_READONLY;
  715. }
  716. }
  717. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  718. if (!empty($sStateAttCode))
  719. {
  720. if ($sTargetState != '')
  721. {
  722. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  723. }
  724. else
  725. {
  726. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  727. }
  728. }
  729. $aReasons = array();
  730. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  731. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  732. }
  733. /**
  734. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  735. * for the given attribute for the current state of the object considered as an INITIAL state
  736. * @param string $sAttCode The code of the attribute
  737. * @return integer Flags: the binary combination of the flags applicable to this attribute
  738. */
  739. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  740. {
  741. $iFlags = 0;
  742. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  743. if (!empty($sStateAttCode))
  744. {
  745. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  746. }
  747. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  748. }
  749. // check if the given (or current) value is suitable for the attribute
  750. // return true if successfull
  751. // return the error desciption otherwise
  752. public function CheckValue($sAttCode, $value = null)
  753. {
  754. if (!is_null($value))
  755. {
  756. $toCheck = $value;
  757. }
  758. else
  759. {
  760. $toCheck = $this->Get($sAttCode);
  761. }
  762. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  763. if (!$oAtt->IsWritable())
  764. {
  765. return true;
  766. }
  767. elseif ($oAtt->IsNull($toCheck))
  768. {
  769. if ($oAtt->IsNullAllowed())
  770. {
  771. return true;
  772. }
  773. else
  774. {
  775. return "Null not allowed";
  776. }
  777. }
  778. elseif ($oAtt->IsExternalKey())
  779. {
  780. if (!MetaModel::SkipCheckExtKeys())
  781. {
  782. $sTargetClass = $oAtt->GetTargetClass();
  783. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  784. if (is_null($oTargetObj))
  785. {
  786. return "Target object not found ($sTargetClass::$toCheck)";
  787. }
  788. }
  789. if ($oAtt->IsHierarchicalKey())
  790. {
  791. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  792. if ($toCheck == $this->GetKey())
  793. {
  794. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  795. }
  796. }
  797. }
  798. elseif ($oAtt->IsScalar())
  799. {
  800. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  801. if (count($aValues) > 0)
  802. {
  803. if (!array_key_exists($toCheck, $aValues))
  804. {
  805. return "Value not allowed [$toCheck]";
  806. }
  807. }
  808. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  809. {
  810. $iLen = strlen($toCheck);
  811. if ($iLen > $iMaxSize)
  812. {
  813. return "String too long (found $iLen, limited to $iMaxSize)";
  814. }
  815. }
  816. if (!$oAtt->CheckFormat($toCheck))
  817. {
  818. return "Wrong format [$toCheck]";
  819. }
  820. }
  821. return true;
  822. }
  823. // check attributes together
  824. public function CheckConsistency()
  825. {
  826. return true;
  827. }
  828. // check integrity rules (before inserting or updating the object)
  829. // a displayable error is returned
  830. public function DoCheckToWrite()
  831. {
  832. $this->DoComputeValues();
  833. $this->m_aCheckIssues = array();
  834. $aChanges = $this->ListChanges();
  835. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  836. {
  837. $res = $this->CheckValue($sAttCode);
  838. if ($res !== true)
  839. {
  840. // $res contains the error description
  841. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  842. }
  843. }
  844. if (count($this->m_aCheckIssues) > 0)
  845. {
  846. // No need to check consistency between attributes if any of them has
  847. // an unexpected value
  848. return;
  849. }
  850. $res = $this->CheckConsistency();
  851. if ($res !== true)
  852. {
  853. // $res contains the error description
  854. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  855. }
  856. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  857. //
  858. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  859. {
  860. foreach($aChanges as $sAttCode => $value)
  861. {
  862. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  863. if ($iFlags & OPT_ATT_SLAVE)
  864. {
  865. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  866. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  867. $sAttLabel = $oAttDef->GetLabel();
  868. foreach($aReasons as $aReasonInfo)
  869. {
  870. // Todo: associate the attribute code with the error
  871. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  872. }
  873. }
  874. }
  875. }
  876. }
  877. final public function CheckToWrite()
  878. {
  879. if (MetaModel::SkipCheckToWrite())
  880. {
  881. return array(true, array());
  882. }
  883. if (is_null($this->m_bCheckStatus))
  884. {
  885. $oKPI = new ExecutionKPI();
  886. $this->DoCheckToWrite();
  887. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  888. if (count($this->m_aCheckIssues) == 0)
  889. {
  890. $this->m_bCheckStatus = true;
  891. }
  892. else
  893. {
  894. $this->m_bCheckStatus = false;
  895. }
  896. }
  897. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  898. }
  899. // check if it is allowed to delete the existing object from the database
  900. // a displayable error is returned
  901. protected function DoCheckToDelete(&$oDeletionPlan)
  902. {
  903. $this->m_aDeleteIssues = array(); // Ok
  904. if ($this->InSyncScope())
  905. {
  906. $oReplicaSet = $this->GetMasterReplica();
  907. if ($oReplicaSet->Count() > 0)
  908. {
  909. while($aData = $oReplicaSet->FetchAssoc())
  910. {
  911. $oDataSource = $aData['datasource'];
  912. $oReplica = $aData['replica'];
  913. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  914. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  915. {
  916. // The current task has the right to delete the object
  917. continue;
  918. }
  919. if ($oReplica->Get('status_dest_creator') != 1)
  920. {
  921. // The object is not owned by the task
  922. continue;
  923. }
  924. $sLink = $oDataSource->GetName();
  925. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  926. switch($sUserDeletePolicy)
  927. {
  928. case 'nobody':
  929. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  930. break;
  931. case 'administrators':
  932. if (!UserRights::IsAdministrator())
  933. {
  934. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  935. }
  936. break;
  937. case 'everybody':
  938. default:
  939. // Ok
  940. break;
  941. }
  942. }
  943. }
  944. }
  945. }
  946. final public function CheckToDelete(&$oDeletionPlan)
  947. {
  948. $this->MakeDeletionPlan($oDeletionPlan);
  949. $oDeletionPlan->ComputeResults();
  950. return (!$oDeletionPlan->FoundStopper());
  951. }
  952. protected function ListChangedValues(array $aProposal)
  953. {
  954. $aDelta = array();
  955. foreach ($aProposal as $sAtt => $proposedValue)
  956. {
  957. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  958. {
  959. // The value was not set
  960. $aDelta[$sAtt] = $proposedValue;
  961. }
  962. elseif(is_object($proposedValue))
  963. {
  964. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  965. // The value is an object, the comparison is not strict
  966. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  967. {
  968. $aDelta[$sAtt] = $proposedValue;
  969. }
  970. }
  971. else
  972. {
  973. // The value is a scalar, the comparison must be 100% strict
  974. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  975. {
  976. //echo "$sAtt:<pre>\n";
  977. //var_dump($this->m_aOrigValues[$sAtt]);
  978. //var_dump($proposedValue);
  979. //echo "</pre>\n";
  980. $aDelta[$sAtt] = $proposedValue;
  981. }
  982. }
  983. }
  984. return $aDelta;
  985. }
  986. // List the attributes that have been changed
  987. // Returns an array of attname => currentvalue
  988. public function ListChanges()
  989. {
  990. if ($this->m_bIsInDB)
  991. {
  992. return $this->ListChangedValues($this->m_aCurrValues);
  993. }
  994. else
  995. {
  996. return $this->m_aCurrValues;
  997. }
  998. }
  999. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1000. public function IsModified()
  1001. {
  1002. $aChanges = $this->ListChanges();
  1003. return (count($aChanges) != 0);
  1004. }
  1005. public function Equals($oSibling)
  1006. {
  1007. if (get_class($oSibling) != get_class($this))
  1008. {
  1009. return false;
  1010. }
  1011. if ($this->GetKey() != $oSibling->GetKey())
  1012. {
  1013. return false;
  1014. }
  1015. if ($this->m_bIsInDB)
  1016. {
  1017. // If one has changed, then consider them as being different
  1018. if ($this->IsModified() || $oSibling->IsModified())
  1019. {
  1020. return false;
  1021. }
  1022. }
  1023. else
  1024. {
  1025. // Todo - implement this case (loop on every attribute)
  1026. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1027. //{
  1028. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1029. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1030. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1031. //{
  1032. //return false;
  1033. //}
  1034. //}
  1035. return false;
  1036. }
  1037. return true;
  1038. }
  1039. // used both by insert/update
  1040. private function DBWriteLinks()
  1041. {
  1042. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1043. {
  1044. if (!$oAttDef->IsLinkSet()) continue;
  1045. $oLinks = $this->Get($sAttCode);
  1046. $oLinks->Rewind();
  1047. while ($oLinkedObject = $oLinks->Fetch())
  1048. {
  1049. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1050. if ($oLinkedObject->IsModified())
  1051. {
  1052. $oLinkedObject->DBWrite();
  1053. }
  1054. }
  1055. // Delete the objects that were initialy present and disappeared from the list
  1056. // (if any)
  1057. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  1058. if ($oOriginalSet != null)
  1059. {
  1060. $aOriginalList = $oOriginalSet->ToArray();
  1061. $aNewSet = $oLinks->ToArray();
  1062. foreach($aOriginalList as $iId => $oObject)
  1063. {
  1064. if (!array_key_exists($iId, $aNewSet))
  1065. {
  1066. // It disappeared from the list
  1067. $oObject->DBDelete();
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }
  1073. // Note: this is experimental - it was designed to speed up the setup of iTop
  1074. // Known limitations:
  1075. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1076. // - the id of the object is not updated
  1077. static public final function BulkInsertStart()
  1078. {
  1079. self::$m_bBulkInsert = true;
  1080. }
  1081. static public final function BulkInsertFlush()
  1082. {
  1083. if (!self::$m_bBulkInsert) return;
  1084. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1085. {
  1086. foreach ($aTables as $sTable => $sColumns)
  1087. {
  1088. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1089. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1090. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1091. }
  1092. }
  1093. // Reset
  1094. self::$m_aBulkInsertItems = array();
  1095. self::$m_aBulkInsertCols = array();
  1096. self::$m_bBulkInsert = false;
  1097. }
  1098. private function DBInsertSingleTable($sTableClass)
  1099. {
  1100. $sTable = MetaModel::DBGetTable($sTableClass);
  1101. // Abstract classes or classes having no specific attribute do not have an associated table
  1102. if ($sTable == '') return;
  1103. $sClass = get_class($this);
  1104. // fields in first array, values in the second
  1105. $aFieldsToWrite = array();
  1106. $aValuesToWrite = array();
  1107. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1108. {
  1109. // Add it to the list of fields to write
  1110. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1111. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1112. }
  1113. $aHierarchicalKeys = array();
  1114. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1115. {
  1116. // Skip this attribute if not defined in this table
  1117. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1118. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1119. foreach($aAttColumns as $sColumn => $sValue)
  1120. {
  1121. $aFieldsToWrite[] = "`$sColumn`";
  1122. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1123. }
  1124. if ($oAttDef->IsHierarchicalKey())
  1125. {
  1126. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1127. }
  1128. }
  1129. if (count($aValuesToWrite) == 0) return false;
  1130. if (MetaModel::DBIsReadOnly())
  1131. {
  1132. $iNewKey = -1;
  1133. }
  1134. else
  1135. {
  1136. if (self::$m_bBulkInsert)
  1137. {
  1138. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1139. {
  1140. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1141. }
  1142. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1143. $iNewKey = 999999; // TODO - compute next id....
  1144. }
  1145. else
  1146. {
  1147. if (count($aHierarchicalKeys) > 0)
  1148. {
  1149. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1150. {
  1151. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1152. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1153. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1154. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1155. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1156. }
  1157. }
  1158. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1159. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1160. }
  1161. }
  1162. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1163. if (empty($this->m_iKey))
  1164. {
  1165. // Take the autonumber
  1166. $this->m_iKey = $iNewKey;
  1167. }
  1168. return $this->m_iKey;
  1169. }
  1170. // Insert of record for the new object into the database
  1171. // Returns the key of the newly created object
  1172. public function DBInsertNoReload()
  1173. {
  1174. if ($this->m_bIsInDB)
  1175. {
  1176. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1177. }
  1178. $sClass = get_class($this);
  1179. $sRootClass = MetaModel::GetRootClass($sClass);
  1180. // Ensure the update of the values (we are accessing the data directly)
  1181. $this->DoComputeValues();
  1182. $this->OnInsert();
  1183. if ($this->m_iKey < 0)
  1184. {
  1185. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1186. $this->m_iKey = null;
  1187. }
  1188. // If not automatically computed, then check that the key is given by the caller
  1189. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1190. {
  1191. if (empty($this->m_iKey))
  1192. {
  1193. 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));
  1194. }
  1195. }
  1196. // Ultimate check - ensure DB integrity
  1197. list($bRes, $aIssues) = $this->CheckToWrite();
  1198. if (!$bRes)
  1199. {
  1200. $sIssues = implode(', ', $aIssues);
  1201. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1202. }
  1203. // Stop watches
  1204. $sState = $this->GetState();
  1205. if ($sState != '')
  1206. {
  1207. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1208. {
  1209. if ($oAttDef instanceof AttributeStopWatch)
  1210. {
  1211. if (in_array($sState, $oAttDef->GetStates()))
  1212. {
  1213. // Start the stop watch and compute the deadlines
  1214. $oSW = $this->Get($sAttCode);
  1215. $oSW->Start($this, $oAttDef);
  1216. $oSW->ComputeDeadlines($this, $oAttDef);
  1217. $this->Set($sAttCode, $oSW);
  1218. }
  1219. }
  1220. }
  1221. }
  1222. // First query built upon on the root class, because the ID must be created first
  1223. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1224. // Then do the leaf class, if different from the root class
  1225. if ($sClass != $sRootClass)
  1226. {
  1227. $this->DBInsertSingleTable($sClass);
  1228. }
  1229. // Then do the other classes
  1230. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1231. {
  1232. if ($sParentClass == $sRootClass) continue;
  1233. $this->DBInsertSingleTable($sParentClass);
  1234. }
  1235. $this->DBWriteLinks();
  1236. $this->m_bIsInDB = true;
  1237. $this->m_bDirty = false;
  1238. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  1239. $this->m_aAsArgs = null;
  1240. $this->AfterInsert();
  1241. // Activate any existing trigger
  1242. $sClass = get_class($this);
  1243. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1244. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1245. while ($oTrigger = $oSet->Fetch())
  1246. {
  1247. $oTrigger->DoActivate($this->ToArgs('this'));
  1248. }
  1249. return $this->m_iKey;
  1250. }
  1251. public function DBInsert()
  1252. {
  1253. $this->DBInsertNoReload();
  1254. $this->Reload();
  1255. return $this->m_iKey;
  1256. }
  1257. public function DBInsertTracked(CMDBChange $oVoid)
  1258. {
  1259. return $this->DBInsert();
  1260. }
  1261. public function DBInsertTrackedNoReload(CMDBChange $oVoid)
  1262. {
  1263. return $this->DBInsertNoReload();
  1264. }
  1265. // Creates a copy of the current object into the database
  1266. // Returns the id of the newly created object
  1267. public function DBClone($iNewKey = null)
  1268. {
  1269. $this->m_bIsInDB = false;
  1270. $this->m_iKey = $iNewKey;
  1271. return $this->DBInsert();
  1272. }
  1273. /**
  1274. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1275. * The purpose of this method is to reset the appropriate attributes of the object in
  1276. * order to make sure that the newly cloned object is really distinct from its clone
  1277. */
  1278. public function __clone()
  1279. {
  1280. $this->m_bIsInDB = false;
  1281. $this->m_bDirty = true;
  1282. $this->m_iKey = self::GetNextTempId(get_class($this));
  1283. }
  1284. // Update a record
  1285. public function DBUpdate()
  1286. {
  1287. if (!$this->m_bIsInDB)
  1288. {
  1289. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1290. }
  1291. // Stop watches
  1292. $sState = $this->GetState();
  1293. if ($sState != '')
  1294. {
  1295. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1296. {
  1297. if ($oAttDef instanceof AttributeStopWatch)
  1298. {
  1299. if (in_array($sState, $oAttDef->GetStates()))
  1300. {
  1301. // Compute or recompute the deadlines
  1302. $oSW = $this->Get($sAttCode);
  1303. $oSW->ComputeDeadlines($this, $oAttDef);
  1304. $this->Set($sAttCode, $oSW);
  1305. }
  1306. }
  1307. }
  1308. }
  1309. $this->DoComputeValues();
  1310. $this->OnUpdate();
  1311. $aChanges = $this->ListChanges();
  1312. if (count($aChanges) == 0)
  1313. {
  1314. //throw new CoreWarning("Attempting to update an unchanged object");
  1315. return;
  1316. }
  1317. // Ultimate check - ensure DB integrity
  1318. list($bRes, $aIssues) = $this->CheckToWrite();
  1319. if (!$bRes)
  1320. {
  1321. $sIssues = implode(', ', $aIssues);
  1322. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1323. }
  1324. $bHasANewExternalKeyValue = false;
  1325. $aHierarchicalKeys = array();
  1326. foreach($aChanges as $sAttCode => $valuecurr)
  1327. {
  1328. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1329. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1330. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1331. if ($oAttDef->IsHierarchicalKey())
  1332. {
  1333. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1334. }
  1335. }
  1336. if (!MetaModel::DBIsReadOnly())
  1337. {
  1338. // Update the left & right indexes for each hierarchical key
  1339. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1340. {
  1341. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1342. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1343. $aRes = CMDBSource::QueryToArray($sSQL);
  1344. $iMyLeft = $aRes[0]['left'];
  1345. $iMyRight = $aRes[0]['right'];
  1346. $iDelta =$iMyRight - $iMyLeft + 1;
  1347. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1348. if ($aChanges[$sAttCode] == 0)
  1349. {
  1350. // No new parent, insert completely at the right of the tree
  1351. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1352. $aRes = CMDBSource::QueryToArray($sSQL);
  1353. if (count($aRes) == 0)
  1354. {
  1355. $iNewLeft = 1;
  1356. }
  1357. else
  1358. {
  1359. $iNewLeft = $aRes[0]['max']+1;
  1360. }
  1361. }
  1362. else
  1363. {
  1364. // Insert at the right of the specified parent
  1365. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aChanges[$sAttCode]);
  1366. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1367. }
  1368. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1369. $aHKChanges = array();
  1370. $aHKChanges[$sAttCode] = $aChanges[$sAttCode];
  1371. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1372. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1373. $aChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1374. }
  1375. // Update scalar attributes
  1376. if (count($aChanges) != 0)
  1377. {
  1378. $oFilter = new DBObjectSearch(get_class($this));
  1379. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1380. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1381. CMDBSource::Query($sSQL);
  1382. }
  1383. }
  1384. $this->DBWriteLinks();
  1385. $this->m_bDirty = false;
  1386. $this->AfterUpdate();
  1387. // Reload to get the external attributes
  1388. if ($bHasANewExternalKeyValue)
  1389. {
  1390. $this->Reload();
  1391. }
  1392. return $this->m_iKey;
  1393. }
  1394. public function DBUpdateTracked(CMDBChange $oVoid)
  1395. {
  1396. return $this->DBUpdate();
  1397. }
  1398. // Make the current changes persistent - clever wrapper for Insert or Update
  1399. public function DBWrite()
  1400. {
  1401. if ($this->m_bIsInDB)
  1402. {
  1403. return $this->DBUpdate();
  1404. }
  1405. else
  1406. {
  1407. return $this->DBInsert();
  1408. }
  1409. }
  1410. private function DBDeleteSingleTable($sTableClass)
  1411. {
  1412. $sTable = MetaModel::DBGetTable($sTableClass);
  1413. // Abstract classes or classes having no specific attribute do not have an associated table
  1414. if ($sTable == '') return;
  1415. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1416. $sKey = CMDBSource::Quote($this->m_iKey);
  1417. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1418. CMDBSource::DeleteFrom($sDeleteSQL);
  1419. }
  1420. protected function DBDeleteSingleObject()
  1421. {
  1422. $this->OnDelete();
  1423. if (!MetaModel::DBIsReadOnly())
  1424. {
  1425. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1426. {
  1427. if ($oAttDef->IsHierarchicalKey())
  1428. {
  1429. // Update the left & right indexes for each hierarchical key
  1430. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1431. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1432. $aRes = CMDBSource::QueryToArray($sSQL);
  1433. $iMyLeft = $aRes[0]['left'];
  1434. $iMyRight = $aRes[0]['right'];
  1435. $iDelta =$iMyRight - $iMyLeft + 1;
  1436. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1437. // No new parent for now, insert completely at the right of the tree
  1438. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1439. $aRes = CMDBSource::QueryToArray($sSQL);
  1440. if (count($aRes) == 0)
  1441. {
  1442. $iNewLeft = 1;
  1443. }
  1444. else
  1445. {
  1446. $iNewLeft = $aRes[0]['max']+1;
  1447. }
  1448. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1449. }
  1450. }
  1451. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1452. {
  1453. $this->DBDeleteSingleTable($sParentClass);
  1454. }
  1455. }
  1456. $this->AfterDelete();
  1457. $this->m_bIsInDB = false;
  1458. $this->m_iKey = null;
  1459. }
  1460. // Delete an object... and guarantee data integrity
  1461. //
  1462. public function DBDelete(&$oDeletionPlan = null)
  1463. {
  1464. if (is_null($oDeletionPlan))
  1465. {
  1466. $oDeletionPlan = new DeletionPlan();
  1467. }
  1468. $this->MakeDeletionPlan($oDeletionPlan);
  1469. $oDeletionPlan->ComputeResults();
  1470. if ($oDeletionPlan->FoundStopper())
  1471. {
  1472. $aIssues = $oDeletionPlan->GetIssues();
  1473. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1474. }
  1475. else
  1476. {
  1477. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1478. {
  1479. foreach ($aToDelete as $iId => $aData)
  1480. {
  1481. $oToDelete = $aData['to_delete'];
  1482. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1483. // because for each object we would try to update all the preceding ones... that are already deleted
  1484. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1485. // As a temporary fix: delete only the objects that are still to be deleted...
  1486. if ($oToDelete->m_bIsInDB)
  1487. {
  1488. $oToDelete->DBDeleteSingleObject();
  1489. }
  1490. }
  1491. }
  1492. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1493. {
  1494. foreach ($aToUpdate as $iId => $aData)
  1495. {
  1496. $oToUpdate = $aData['to_reset'];
  1497. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1498. {
  1499. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1500. $oToUpdate->DBUpdate();
  1501. }
  1502. }
  1503. }
  1504. }
  1505. return $oDeletionPlan;
  1506. }
  1507. public function DBDeleteTracked(CMDBChange $oVoid, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1508. {
  1509. $this->DBDelete($oDeletionPlan);
  1510. }
  1511. public function EnumTransitions()
  1512. {
  1513. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1514. if (empty($sStateAttCode)) return array();
  1515. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1516. return MetaModel::EnumTransitions(get_class($this), $sState);
  1517. }
  1518. /**
  1519. * Designed as an action to be called when a stop watch threshold times out
  1520. * or from within the framework
  1521. */
  1522. public function ApplyStimulus($sStimulusCode)
  1523. {
  1524. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1525. if (empty($sStateAttCode)) return false;
  1526. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1527. $aStateTransitions = $this->EnumTransitions();
  1528. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1529. // Change the state before proceeding to the actions, this is necessary because an action might
  1530. // trigger another stimuli (alternative: push the stimuli into a queue)
  1531. $sPreviousState = $this->Get($sStateAttCode);
  1532. $sNewState = $aTransitionDef['target_state'];
  1533. $this->Set($sStateAttCode, $sNewState);
  1534. // $aTransitionDef is an
  1535. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1536. $bSuccess = true;
  1537. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1538. {
  1539. // std PHP spec
  1540. $aActionCallSpec = array($this, $sActionHandler);
  1541. if (!is_callable($aActionCallSpec))
  1542. {
  1543. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1544. return;
  1545. }
  1546. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1547. // if one call fails, the whole is considered as failed
  1548. if (!$bRet) $bSuccess = false;
  1549. }
  1550. if ($bSuccess)
  1551. {
  1552. // Change state triggers...
  1553. $sClass = get_class($this);
  1554. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1555. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1556. while ($oTrigger = $oSet->Fetch())
  1557. {
  1558. $oTrigger->DoActivate($this->ToArgs('this'));
  1559. }
  1560. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1561. while ($oTrigger = $oSet->Fetch())
  1562. {
  1563. $oTrigger->DoActivate($this->ToArgs('this'));
  1564. }
  1565. // Stop watches
  1566. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1567. {
  1568. if ($oAttDef instanceof AttributeStopWatch)
  1569. {
  1570. $oSW = $this->Get($sAttCode);
  1571. if (in_array($sNewState, $oAttDef->GetStates()))
  1572. {
  1573. $oSW->Start($this, $oAttDef);
  1574. }
  1575. else
  1576. {
  1577. $oSW->Stop($this, $oAttDef);
  1578. }
  1579. $this->Set($sAttCode, $oSW);
  1580. }
  1581. }
  1582. }
  1583. return $bSuccess;
  1584. }
  1585. /**
  1586. * Designed as an action to be called when a stop watch threshold times out
  1587. */
  1588. public function ResetStopWatch($sAttCode)
  1589. {
  1590. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1591. if (!$oAttDef instanceof AttributeStopWatch)
  1592. {
  1593. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  1594. }
  1595. $oSW = $this->Get($sAttCode);
  1596. $oSW->Reset($this, $oAttDef);
  1597. $this->Set($sAttCode, $oSW);
  1598. }
  1599. // Make standard context arguments
  1600. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1601. // Several options here:
  1602. // 1) cache the result
  1603. // 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)
  1604. public function ToArgs($sArgName = 'this')
  1605. {
  1606. if (is_null($this->m_aAsArgs))
  1607. {
  1608. $oKPI = new ExecutionKPI();
  1609. $aScalarArgs = array();
  1610. $aScalarArgs[$sArgName] = $this->GetKey();
  1611. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1612. $aScalarArgs[$sArgName.'->object()'] = $this;
  1613. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink('iTopStandardURLMaker', false);
  1614. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = $this->GetHyperlink('PortalURLMaker', false);
  1615. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1616. $sClass = get_class($this);
  1617. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1618. {
  1619. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1620. if ($oAttDef->IsScalar())
  1621. {
  1622. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1623. $sAsHtml = $this->GetAsHtml($sAttCode);
  1624. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1625. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = $this->GetEditValue($sAttCode); // "Nice" display value, but without HTML tags and entities
  1626. }
  1627. // Do something for case logs... quick N' dirty...
  1628. if ($aScalarArgs[$sArgName.'->'.$sAttCode] instanceof ormCaseLog)
  1629. {
  1630. $oCaseLog = $aScalarArgs[$sArgName.'->'.$sAttCode];
  1631. $aScalarArgs[$sArgName.'->'.$sAttCode] = $oCaseLog->GetText();
  1632. $aScalarArgs[$sArgName.'->head('.$sAttCode.')'] = $oCaseLog->GetLatestEntry();
  1633. }
  1634. }
  1635. $this->m_aAsArgs = $aScalarArgs;
  1636. $oKPI->ComputeStats('ToArgs', get_class($this));
  1637. }
  1638. return $this->m_aAsArgs;
  1639. }
  1640. // To be optionaly overloaded
  1641. protected function OnInsert()
  1642. {
  1643. }
  1644. // To be optionaly overloaded
  1645. protected function AfterInsert()
  1646. {
  1647. }
  1648. // To be optionaly overloaded
  1649. protected function OnUpdate()
  1650. {
  1651. }
  1652. // To be optionaly overloaded
  1653. protected function AfterUpdate()
  1654. {
  1655. }
  1656. // To be optionaly overloaded
  1657. protected function OnDelete()
  1658. {
  1659. }
  1660. // To be optionaly overloaded
  1661. protected function AfterDelete()
  1662. {
  1663. }
  1664. // Return an empty set for the parent of all
  1665. public static function GetRelationQueries($sRelCode)
  1666. {
  1667. return array();
  1668. }
  1669. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1670. {
  1671. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1672. {
  1673. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1674. $sQuery = $aQueryInfo["sQuery"];
  1675. $bPropagate = $aQueryInfo["bPropagate"];
  1676. $iDistance = $aQueryInfo["iDistance"];
  1677. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1678. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1679. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1680. while ($oObj = $oObjSet->Fetch())
  1681. {
  1682. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1683. $sObjKey = $oObj->GetKey();
  1684. if (array_key_exists($sRootClass, $aResults))
  1685. {
  1686. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1687. {
  1688. continue; // already visited, skip
  1689. }
  1690. }
  1691. $aResults[$sRootClass][$sObjKey] = $oObj;
  1692. if ($iDepth > 0)
  1693. {
  1694. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1695. }
  1696. }
  1697. }
  1698. return $aResults;
  1699. }
  1700. public function GetReferencingObjects($bAllowAllData = false)
  1701. {
  1702. $aDependentObjects = array();
  1703. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1704. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1705. {
  1706. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1707. {
  1708. // skip if this external key is behind an external field
  1709. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1710. $oSearch = new DBObjectSearch($sRemoteClass);
  1711. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1712. if ($bAllowAllData)
  1713. {
  1714. $oSearch->AllowAllData();
  1715. }
  1716. $oSet = new CMDBObjectSet($oSearch);
  1717. if ($oSet->Count() > 0)
  1718. {
  1719. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1720. 'attribute' => $oExtKeyAttDef,
  1721. 'objects' => $oSet,
  1722. );
  1723. }
  1724. }
  1725. }
  1726. return $aDependentObjects;
  1727. }
  1728. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  1729. {
  1730. $sClass = get_class($this);
  1731. $iThisId = $this->GetKey();
  1732. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  1733. if (array_key_exists($sClass, $aVisited))
  1734. {
  1735. if (in_array($iThisId, $aVisited[$sClass]))
  1736. {
  1737. return;
  1738. }
  1739. }
  1740. $aVisited[$sClass] = $iThisId;
  1741. if ($iDeleteOption == DEL_MANUAL)
  1742. {
  1743. // Stop the recursion here
  1744. return;
  1745. }
  1746. // Check the node itself
  1747. $this->DoCheckToDelete($oDeletionPlan);
  1748. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  1749. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  1750. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1751. {
  1752. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1753. {
  1754. $oAttDef = $aData['attribute'];
  1755. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1756. $oDepSet = $aData['objects'];
  1757. $oDepSet->Rewind();
  1758. while ($oDependentObj = $oDepSet->fetch())
  1759. {
  1760. $iId = $oDependentObj->GetKey();
  1761. if ($oAttDef->IsNullAllowed())
  1762. {
  1763. // Optional external key, list to reset
  1764. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  1765. {
  1766. // Move the child up one level i.e. set the same parent as the current object
  1767. $iParentId = $this->Get($oAttDef->GetCode());
  1768. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  1769. }
  1770. else
  1771. {
  1772. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  1773. }
  1774. }
  1775. else
  1776. {
  1777. // Mandatory external key, list to delete
  1778. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  1779. }
  1780. }
  1781. }
  1782. }
  1783. }
  1784. /**
  1785. * Get all the synchro replica related to this object
  1786. * @param none
  1787. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  1788. */
  1789. public function GetMasterReplica()
  1790. {
  1791. if ($this->m_oMasterReplicaSet == null)
  1792. {
  1793. //$aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  1794. //$sClassesList = "'".implode("','", $aParentClasses)."'";
  1795. $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";
  1796. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  1797. $this->m_oMasterReplicaSet = $oReplicaSet;
  1798. }
  1799. else
  1800. {
  1801. $this->m_oMasterReplicaSet->Rewind();
  1802. }
  1803. return $this->m_oMasterReplicaSet;
  1804. }
  1805. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  1806. {
  1807. $iFlags = OPT_ATT_NORMAL;
  1808. $oSet = $this->GetMasterReplica();
  1809. while($aData = $oSet->FetchAssoc())
  1810. {
  1811. if ($aData['datasource']->GetKey() == SynchroExecution::GetCurrentTaskId())
  1812. {
  1813. // Ignore the current task (check to write => ok)
  1814. continue;
  1815. }
  1816. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  1817. $oReplica = $aData['replica'];
  1818. $oSource = $aData['datasource'];
  1819. $oAttrSet = $oSource->Get('attribute_list');
  1820. while($oSyncAttr = $oAttrSet->Fetch())
  1821. {
  1822. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  1823. {
  1824. $iFlags |= OPT_ATT_SLAVE;
  1825. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  1826. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  1827. }
  1828. }
  1829. }
  1830. return $iFlags;
  1831. }
  1832. public function InSyncScope()
  1833. {
  1834. return true;
  1835. // TODO - FINALIZE THIS OPTIMIZATION
  1836. //
  1837. // Optimization: cache the list of Data Sources and classes candidates for synchro
  1838. //
  1839. static $aSynchroClasses = null;
  1840. if (is_null($aSynchroClasses))
  1841. {
  1842. $aSynchroClasses = array();
  1843. $sOQL = "SELECT SynchroDataSource AS datasource";
  1844. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  1845. while($oSource = $oSourceSet->Fetch())
  1846. {
  1847. $sTarget = $oSource->Get('scope_class');
  1848. $aSynchroClasses[] = $oSource;
  1849. }
  1850. }
  1851. // to be continued...
  1852. }
  1853. }
  1854. ?>