dbobject.class.php 108 KB

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