dbobject.class.php 87 KB

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