dbobject.class.php 79 KB

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