dbobject.class.php 92 KB

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