dbobject.class.php 107 KB

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