dbobject.class.php 92 KB

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