dbobject.class.php 105 KB

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