dbobject.class.php 78 KB

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