dbobject.class.php 63 KB

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