dbobject.class.php 114 KB

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