dbobject.class.php 93 KB

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