dbobject.class.php 69 KB

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