dbobject.class.php 107 KB

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