dbobject.class.php 112 KB

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