dbobject.class.php 114 KB

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