dbobject.class.php 87 KB

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