dbobject.class.php 92 KB

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