dbobject.class.php 92 KB

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