dbobject.class.php 92 KB

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