dbobject.class.php 85 KB

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