dbobject.class.php 82 KB

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