dbobject.class.php 107 KB

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