dbobject.class.php 115 KB

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