dbobject.class.php 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548
  1. <?php
  2. // Copyright (C) 2010-2017 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 in a transition
  963. * @param $sAttCode string $sAttCode The code of the attribute
  964. * @param $sStimulus string The stimulus code to apply
  965. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  966. * @param $sOriginState string The state from which to apply $sStimulus, if empty current state will be used
  967. * @return integer Flags: the binary combination of the flags applicable to this attribute
  968. */
  969. public function GetTransitionFlags($sAttCode, $sStimulus, &$aReasons = array(), $sOriginState = '')
  970. {
  971. $iFlags = 0; // By default (if no lifecycle) no flag at all
  972. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  973. // If no state attribute, there is no lifecycle
  974. if (empty($sStateAttCode))
  975. {
  976. return $iFlags;
  977. }
  978. // Retrieving current state if necessary
  979. if ($sOriginState === '')
  980. {
  981. $sOriginState = $this->Get($sStateAttCode);
  982. }
  983. // Retrieving attribute flags
  984. $iAttributeFlags = $this->GetAttributeFlags($sAttCode, $aReasons, $sOriginState);
  985. // Retrieving transition flags
  986. $iTransitionFlags = MetaModel::GetTransitionFlags(get_class($this), $sOriginState, $sStimulus, $sAttCode);
  987. // Merging transition flags with attribute flags
  988. $iFlags = $iTransitionFlags | $iAttributeFlags;
  989. return $iFlags;
  990. }
  991. /**
  992. * Returns an array of attribute codes (with their flags) when $sStimulus is applied on the object in the $sOriginState state.
  993. * Note: Attributes (and flags) from the target state and the transition are combined.
  994. *
  995. * @param $sStimulus string
  996. * @param $sOriginState string Default is current state
  997. * @return array
  998. */
  999. public function GetTransitionAttributes($sStimulus, $sOriginState = null)
  1000. {
  1001. $sObjClass = get_class($this);
  1002. // Defining current state as origin state if not specified
  1003. if($sOriginState === null)
  1004. {
  1005. $sOriginState = $this->GetState();
  1006. }
  1007. $aAttributes = MetaModel::GetTransitionAttributes($sObjClass, $sStimulus, $sOriginState);
  1008. return $aAttributes;
  1009. }
  1010. /**
  1011. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  1012. * for the given attribute for the current state of the object considered as an INITIAL state
  1013. * @param string $sAttCode The code of the attribute
  1014. * @return integer Flags: the binary combination of the flags applicable to this attribute
  1015. */
  1016. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  1017. {
  1018. $iFlags = 0;
  1019. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1020. if (!empty($sStateAttCode))
  1021. {
  1022. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  1023. }
  1024. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  1025. }
  1026. // check if the given (or current) value is suitable for the attribute
  1027. // return true if successfull
  1028. // return the error desciption otherwise
  1029. public function CheckValue($sAttCode, $value = null)
  1030. {
  1031. if (!is_null($value))
  1032. {
  1033. $toCheck = $value;
  1034. }
  1035. else
  1036. {
  1037. $toCheck = $this->Get($sAttCode);
  1038. }
  1039. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1040. if (!$oAtt->IsWritable())
  1041. {
  1042. return true;
  1043. }
  1044. elseif ($oAtt->IsNull($toCheck))
  1045. {
  1046. if ($oAtt->IsNullAllowed())
  1047. {
  1048. return true;
  1049. }
  1050. else
  1051. {
  1052. return "Null not allowed";
  1053. }
  1054. }
  1055. elseif ($oAtt->IsExternalKey())
  1056. {
  1057. if (!MetaModel::SkipCheckExtKeys())
  1058. {
  1059. $sTargetClass = $oAtt->GetTargetClass();
  1060. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  1061. if (is_null($oTargetObj))
  1062. {
  1063. return "Target object not found ($sTargetClass::$toCheck)";
  1064. }
  1065. }
  1066. if ($oAtt->IsHierarchicalKey())
  1067. {
  1068. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  1069. if ($toCheck == $this->GetKey())
  1070. {
  1071. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  1072. }
  1073. }
  1074. }
  1075. elseif ($oAtt->IsScalar())
  1076. {
  1077. $aValues = $oAtt->GetAllowedValues($this->ToArgsForQuery());
  1078. if (count($aValues) > 0)
  1079. {
  1080. if (!array_key_exists($toCheck, $aValues))
  1081. {
  1082. return "Value not allowed [$toCheck]";
  1083. }
  1084. }
  1085. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  1086. {
  1087. $iLen = strlen($toCheck);
  1088. if ($iLen > $iMaxSize)
  1089. {
  1090. return "String too long (found $iLen, limited to $iMaxSize)";
  1091. }
  1092. }
  1093. if (!$oAtt->CheckFormat($toCheck))
  1094. {
  1095. return "Wrong format [$toCheck]";
  1096. }
  1097. }
  1098. else
  1099. {
  1100. return $oAtt->CheckValue($this, $toCheck);
  1101. }
  1102. return true;
  1103. }
  1104. // check attributes together
  1105. public function CheckConsistency()
  1106. {
  1107. return true;
  1108. }
  1109. // check integrity rules (before inserting or updating the object)
  1110. // a displayable error is returned
  1111. public function DoCheckToWrite()
  1112. {
  1113. $this->DoComputeValues();
  1114. $aChanges = $this->ListChanges();
  1115. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1116. {
  1117. $res = $this->CheckValue($sAttCode);
  1118. if ($res !== true)
  1119. {
  1120. // $res contains the error description
  1121. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  1122. }
  1123. }
  1124. if (count($this->m_aCheckIssues) > 0)
  1125. {
  1126. // No need to check consistency between attributes if any of them has
  1127. // an unexpected value
  1128. return;
  1129. }
  1130. $res = $this->CheckConsistency();
  1131. if ($res !== true)
  1132. {
  1133. // $res contains the error description
  1134. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  1135. }
  1136. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  1137. //
  1138. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  1139. {
  1140. foreach($aChanges as $sAttCode => $value)
  1141. {
  1142. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  1143. if ($iFlags & OPT_ATT_SLAVE)
  1144. {
  1145. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  1146. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1147. $sAttLabel = $oAttDef->GetLabel();
  1148. foreach($aReasons as $aReasonInfo)
  1149. {
  1150. // Todo: associate the attribute code with the error
  1151. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  1152. }
  1153. }
  1154. }
  1155. }
  1156. }
  1157. final public function CheckToWrite()
  1158. {
  1159. if (MetaModel::SkipCheckToWrite())
  1160. {
  1161. return array(true, array());
  1162. }
  1163. if (is_null($this->m_bCheckStatus))
  1164. {
  1165. $this->m_aCheckIssues = array();
  1166. $oKPI = new ExecutionKPI();
  1167. $this->DoCheckToWrite();
  1168. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  1169. if (count($this->m_aCheckIssues) == 0)
  1170. {
  1171. $this->m_bCheckStatus = true;
  1172. }
  1173. else
  1174. {
  1175. $this->m_bCheckStatus = false;
  1176. }
  1177. }
  1178. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  1179. }
  1180. // check if it is allowed to delete the existing object from the database
  1181. // a displayable error is returned
  1182. protected function DoCheckToDelete(&$oDeletionPlan)
  1183. {
  1184. $this->m_aDeleteIssues = array(); // Ok
  1185. if ($this->InSyncScope())
  1186. {
  1187. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  1188. {
  1189. foreach ($aSourceData['replica'] as $oReplica)
  1190. {
  1191. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  1192. }
  1193. $oDataSource = $aSourceData['source'];
  1194. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  1195. {
  1196. // The current task has the right to delete the object
  1197. continue;
  1198. }
  1199. $oReplica = reset($aSourceData['replica']); // Take the first one
  1200. if ($oReplica->Get('status_dest_creator') != 1)
  1201. {
  1202. // The object is not owned by the task
  1203. continue;
  1204. }
  1205. $sLink = $oDataSource->GetName();
  1206. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  1207. switch($sUserDeletePolicy)
  1208. {
  1209. case 'nobody':
  1210. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1211. break;
  1212. case 'administrators':
  1213. if (!UserRights::IsAdministrator())
  1214. {
  1215. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1216. }
  1217. break;
  1218. case 'everybody':
  1219. default:
  1220. // Ok
  1221. break;
  1222. }
  1223. }
  1224. }
  1225. }
  1226. public function CheckToDelete(&$oDeletionPlan)
  1227. {
  1228. $this->MakeDeletionPlan($oDeletionPlan);
  1229. $oDeletionPlan->ComputeResults();
  1230. return (!$oDeletionPlan->FoundStopper());
  1231. }
  1232. protected function ListChangedValues(array $aProposal)
  1233. {
  1234. $aDelta = array();
  1235. foreach ($aProposal as $sAtt => $proposedValue)
  1236. {
  1237. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1238. {
  1239. // The value was not set
  1240. $aDelta[$sAtt] = $proposedValue;
  1241. }
  1242. elseif(!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false))
  1243. {
  1244. // This attCode was never set, cannot be modified
  1245. // or the same value - as the original value - was set, and has been verified as equivalent to the original value
  1246. continue;
  1247. }
  1248. else if (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true)
  1249. {
  1250. // We already know that the value is really modified
  1251. $aDelta[$sAtt] = $proposedValue;
  1252. }
  1253. elseif(is_object($proposedValue))
  1254. {
  1255. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1256. // The value is an object, the comparison is not strict
  1257. if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue))
  1258. {
  1259. $aDelta[$sAtt] = $proposedValue;
  1260. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1261. }
  1262. else
  1263. {
  1264. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1265. }
  1266. }
  1267. else
  1268. {
  1269. // The value is a scalar, the comparison must be 100% strict
  1270. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1271. {
  1272. //echo "$sAtt:<pre>\n";
  1273. //var_dump($this->m_aOrigValues[$sAtt]);
  1274. //var_dump($proposedValue);
  1275. //echo "</pre>\n";
  1276. $aDelta[$sAtt] = $proposedValue;
  1277. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1278. }
  1279. else
  1280. {
  1281. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1282. }
  1283. }
  1284. }
  1285. return $aDelta;
  1286. }
  1287. // List the attributes that have been changed
  1288. // Returns an array of attname => currentvalue
  1289. public function ListChanges()
  1290. {
  1291. if ($this->m_bIsInDB)
  1292. {
  1293. return $this->ListChangedValues($this->m_aCurrValues);
  1294. }
  1295. else
  1296. {
  1297. return $this->m_aCurrValues;
  1298. }
  1299. }
  1300. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1301. public function IsModified()
  1302. {
  1303. $aChanges = $this->ListChanges();
  1304. return (count($aChanges) != 0);
  1305. }
  1306. public function Equals($oSibling)
  1307. {
  1308. if (get_class($oSibling) != get_class($this))
  1309. {
  1310. return false;
  1311. }
  1312. if ($this->GetKey() != $oSibling->GetKey())
  1313. {
  1314. return false;
  1315. }
  1316. if ($this->m_bIsInDB)
  1317. {
  1318. // If one has changed, then consider them as being different
  1319. if ($this->IsModified() || $oSibling->IsModified())
  1320. {
  1321. return false;
  1322. }
  1323. }
  1324. else
  1325. {
  1326. // Todo - implement this case (loop on every attribute)
  1327. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1328. //{
  1329. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1330. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1331. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1332. //{
  1333. //return false;
  1334. //}
  1335. //}
  1336. return false;
  1337. }
  1338. return true;
  1339. }
  1340. // used only by insert
  1341. protected function OnObjectKeyReady()
  1342. {
  1343. // Meant to be overloaded
  1344. }
  1345. // used both by insert/update
  1346. private function DBWriteLinks()
  1347. {
  1348. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1349. {
  1350. if (!$oAttDef->IsLinkSet()) continue;
  1351. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1352. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1353. // Note: any change to this algorithm must be reproduced into the implementation of AttributeLinkSet::Equals()
  1354. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1355. $sAdditionalKey = null;
  1356. if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
  1357. {
  1358. $sAdditionalKey = $oAttDef->GetExtKeyToRemote();
  1359. }
  1360. $oComparator = new DBObjectSetComparator($this->m_aOrigValues[$sAttCode], $this->Get($sAttCode), array($sExtKeyToMe), $sAdditionalKey);
  1361. $aChanges = $oComparator->GetDifferences();
  1362. foreach($aChanges['added'] as $oLink)
  1363. {
  1364. // Make sure that the objects in the set point to "this"
  1365. $oLink->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1366. $id = $oLink->DBWrite();
  1367. }
  1368. foreach($aChanges['modified'] as $oLink)
  1369. {
  1370. // Objects in the set either remain attached or have been detached -> leave the link as is
  1371. $oLink->DBWrite();
  1372. }
  1373. foreach($aChanges['removed'] as $oLink)
  1374. {
  1375. $oLink->DBDelete();
  1376. }
  1377. }
  1378. }
  1379. // used both by insert/update
  1380. private function WriteExternalAttributes()
  1381. {
  1382. foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1383. {
  1384. if (!$oAttDef->LoadInObject()) continue;
  1385. if ($oAttDef->LoadFromDB()) continue;
  1386. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1387. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1388. $oAttDef->WriteValue($this, $this->m_aCurrValues[$sAttCode]);
  1389. }
  1390. }
  1391. // Note: this is experimental - it was designed to speed up the setup of iTop
  1392. // Known limitations:
  1393. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1394. // - the id of the object is not updated
  1395. static public final function BulkInsertStart()
  1396. {
  1397. self::$m_bBulkInsert = true;
  1398. }
  1399. static public final function BulkInsertFlush()
  1400. {
  1401. if (!self::$m_bBulkInsert) return;
  1402. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1403. {
  1404. foreach ($aTables as $sTable => $sColumns)
  1405. {
  1406. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1407. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1408. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1409. }
  1410. }
  1411. // Reset
  1412. self::$m_aBulkInsertItems = array();
  1413. self::$m_aBulkInsertCols = array();
  1414. self::$m_bBulkInsert = false;
  1415. }
  1416. private function DBInsertSingleTable($sTableClass)
  1417. {
  1418. $sTable = MetaModel::DBGetTable($sTableClass);
  1419. // Abstract classes or classes having no specific attribute do not have an associated table
  1420. if ($sTable == '') return;
  1421. $sClass = get_class($this);
  1422. // fields in first array, values in the second
  1423. $aFieldsToWrite = array();
  1424. $aValuesToWrite = array();
  1425. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1426. {
  1427. // Add it to the list of fields to write
  1428. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1429. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1430. }
  1431. $aHierarchicalKeys = array();
  1432. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1433. {
  1434. // Skip this attribute if not defined in this table
  1435. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1436. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1437. foreach($aAttColumns as $sColumn => $sValue)
  1438. {
  1439. $aFieldsToWrite[] = "`$sColumn`";
  1440. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1441. }
  1442. if ($oAttDef->IsHierarchicalKey())
  1443. {
  1444. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1445. }
  1446. }
  1447. if (count($aValuesToWrite) == 0) return false;
  1448. if (MetaModel::DBIsReadOnly())
  1449. {
  1450. $iNewKey = -1;
  1451. }
  1452. else
  1453. {
  1454. if (self::$m_bBulkInsert)
  1455. {
  1456. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1457. {
  1458. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1459. }
  1460. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1461. $iNewKey = 999999; // TODO - compute next id....
  1462. }
  1463. else
  1464. {
  1465. if (count($aHierarchicalKeys) > 0)
  1466. {
  1467. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1468. {
  1469. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1470. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1471. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1472. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1473. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1474. }
  1475. }
  1476. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1477. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1478. }
  1479. }
  1480. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1481. if (empty($this->m_iKey))
  1482. {
  1483. // Take the autonumber
  1484. $this->m_iKey = $iNewKey;
  1485. }
  1486. return $this->m_iKey;
  1487. }
  1488. // Insert of record for the new object into the database
  1489. // Returns the key of the newly created object
  1490. public function DBInsertNoReload()
  1491. {
  1492. if ($this->m_bIsInDB)
  1493. {
  1494. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1495. }
  1496. $sClass = get_class($this);
  1497. $sRootClass = MetaModel::GetRootClass($sClass);
  1498. // Ensure the update of the values (we are accessing the data directly)
  1499. $this->DoComputeValues();
  1500. $this->OnInsert();
  1501. if ($this->m_iKey < 0)
  1502. {
  1503. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1504. $this->m_iKey = null;
  1505. }
  1506. // If not automatically computed, then check that the key is given by the caller
  1507. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1508. {
  1509. if (empty($this->m_iKey))
  1510. {
  1511. 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));
  1512. }
  1513. }
  1514. // Ultimate check - ensure DB integrity
  1515. list($bRes, $aIssues) = $this->CheckToWrite();
  1516. if (!$bRes)
  1517. {
  1518. $sIssues = implode(', ', $aIssues);
  1519. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1520. }
  1521. // Stop watches
  1522. $sState = $this->GetState();
  1523. if ($sState != '')
  1524. {
  1525. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1526. {
  1527. if ($oAttDef instanceof AttributeStopWatch)
  1528. {
  1529. if (in_array($sState, $oAttDef->GetStates()))
  1530. {
  1531. // Start the stop watch and compute the deadlines
  1532. $oSW = $this->Get($sAttCode);
  1533. $oSW->Start($this, $oAttDef);
  1534. $oSW->ComputeDeadlines($this, $oAttDef);
  1535. $this->Set($sAttCode, $oSW);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. // First query built upon on the root class, because the ID must be created first
  1541. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1542. // Then do the leaf class, if different from the root class
  1543. if ($sClass != $sRootClass)
  1544. {
  1545. $this->DBInsertSingleTable($sClass);
  1546. }
  1547. // Then do the other classes
  1548. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1549. {
  1550. if ($sParentClass == $sRootClass) continue;
  1551. $this->DBInsertSingleTable($sParentClass);
  1552. }
  1553. $this->OnObjectKeyReady();
  1554. $this->DBWriteLinks();
  1555. $this->WriteExternalAttributes();
  1556. $this->m_bIsInDB = true;
  1557. $this->m_bDirty = false;
  1558. $this->AfterInsert();
  1559. // Activate any existing trigger
  1560. $sClass = get_class($this);
  1561. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1562. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1563. while ($oTrigger = $oSet->Fetch())
  1564. {
  1565. $oTrigger->DoActivate($this->ToArgs('this'));
  1566. }
  1567. // Callbacks registered with RegisterCallback
  1568. if (isset($this->m_aCallbacks[self::CALLBACK_AFTERINSERT]))
  1569. {
  1570. foreach ($this->m_aCallbacks[self::CALLBACK_AFTERINSERT] as $aCallBackData)
  1571. {
  1572. call_user_func_array($aCallBackData['callback'], $aCallBackData['params']);
  1573. }
  1574. }
  1575. $this->RecordObjCreation();
  1576. return $this->m_iKey;
  1577. }
  1578. protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
  1579. {
  1580. $sTable = MetaModel::DBGetTable($sTableClass);
  1581. // Abstract classes or classes having no specific attribute do not have an associated table
  1582. if ($sTable == '') return;
  1583. $sClass = get_class($this);
  1584. // fields in first array, values in the second
  1585. $aFieldsToWrite = array();
  1586. $aValuesToWrite = array();
  1587. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1588. {
  1589. // Add it to the list of fields to write
  1590. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1591. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1592. }
  1593. $aHierarchicalKeys = array();
  1594. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1595. {
  1596. // Skip this attribute if not defined in this table
  1597. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1598. // Skip link set that can still be undefined though the object is 100% loaded
  1599. if ($oAttDef->IsLinkSet()) continue;
  1600. $value = $this->m_aCurrValues[$sAttCode];
  1601. if ($oAttDef->IsExternalKey())
  1602. {
  1603. $sTargetClass = $oAttDef->GetTargetClass();
  1604. if (is_array($aAuthorizedExtKeys))
  1605. {
  1606. if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
  1607. {
  1608. $value = 0;
  1609. }
  1610. }
  1611. }
  1612. $aAttColumns = $oAttDef->GetSQLValues($value);
  1613. foreach($aAttColumns as $sColumn => $sValue)
  1614. {
  1615. $aFieldsToWrite[] = "`$sColumn`";
  1616. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1617. }
  1618. if ($oAttDef->IsHierarchicalKey())
  1619. {
  1620. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1621. }
  1622. }
  1623. if (count($aValuesToWrite) == 0) return false;
  1624. if (count($aHierarchicalKeys) > 0)
  1625. {
  1626. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1627. {
  1628. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1629. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1630. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1631. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1632. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1633. }
  1634. }
  1635. $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
  1636. }
  1637. public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
  1638. {
  1639. $sClass = get_class($this);
  1640. $sRootClass = MetaModel::GetRootClass($sClass);
  1641. // First query built upon on the root class, because the ID must be created first
  1642. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
  1643. // Then do the leaf class, if different from the root class
  1644. if ($sClass != $sRootClass)
  1645. {
  1646. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
  1647. }
  1648. // Then do the other classes
  1649. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1650. {
  1651. if ($sParentClass == $sRootClass) continue;
  1652. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
  1653. }
  1654. }
  1655. public function DBInsert()
  1656. {
  1657. $this->DBInsertNoReload();
  1658. $this->Reload();
  1659. return $this->m_iKey;
  1660. }
  1661. public function DBInsertTracked(CMDBChange $oChange)
  1662. {
  1663. CMDBObject::SetCurrentChange($oChange);
  1664. return $this->DBInsert();
  1665. }
  1666. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1667. {
  1668. CMDBObject::SetCurrentChange($oChange);
  1669. return $this->DBInsertNoReload();
  1670. }
  1671. // Creates a copy of the current object into the database
  1672. // Returns the id of the newly created object
  1673. public function DBClone($iNewKey = null)
  1674. {
  1675. $this->m_bIsInDB = false;
  1676. $this->m_iKey = $iNewKey;
  1677. $ret = $this->DBInsert();
  1678. $this->RecordObjCreation();
  1679. return $ret;
  1680. }
  1681. /**
  1682. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1683. * The purpose of this method is to reset the appropriate attributes of the object in
  1684. * order to make sure that the newly cloned object is really distinct from its clone
  1685. */
  1686. public function __clone()
  1687. {
  1688. $this->m_bIsInDB = false;
  1689. $this->m_bDirty = true;
  1690. $this->m_iKey = self::GetNextTempId(get_class($this));
  1691. }
  1692. // Update a record
  1693. public function DBUpdate()
  1694. {
  1695. if (!$this->m_bIsInDB)
  1696. {
  1697. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1698. }
  1699. // Protect against reentrance (e.g. cascading the update of ticket logs)
  1700. static $aUpdateReentrance = array();
  1701. $sKey = get_class($this).'::'.$this->GetKey();
  1702. if (array_key_exists($sKey, $aUpdateReentrance))
  1703. {
  1704. return;
  1705. }
  1706. $aUpdateReentrance[$sKey] = true;
  1707. try
  1708. {
  1709. // Stop watches
  1710. $sState = $this->GetState();
  1711. if ($sState != '')
  1712. {
  1713. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1714. {
  1715. if ($oAttDef instanceof AttributeStopWatch)
  1716. {
  1717. if (in_array($sState, $oAttDef->GetStates()))
  1718. {
  1719. // Compute or recompute the deadlines
  1720. $oSW = $this->Get($sAttCode);
  1721. $oSW->ComputeDeadlines($this, $oAttDef);
  1722. $this->Set($sAttCode, $oSW);
  1723. }
  1724. }
  1725. }
  1726. }
  1727. $this->DoComputeValues();
  1728. $this->OnUpdate();
  1729. $aChanges = $this->ListChanges();
  1730. if (count($aChanges) == 0)
  1731. {
  1732. // Attempting to update an unchanged object
  1733. unset($aUpdateReentrance[$sKey]);
  1734. return $this->m_iKey;
  1735. }
  1736. // Ultimate check - ensure DB integrity
  1737. list($bRes, $aIssues) = $this->CheckToWrite();
  1738. if (!$bRes)
  1739. {
  1740. $sIssues = implode(', ', $aIssues);
  1741. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1742. }
  1743. // Save the original values (will be reset to the new values when the object get written to the DB)
  1744. $aOriginalValues = $this->m_aOrigValues;
  1745. $bHasANewExternalKeyValue = false;
  1746. $aHierarchicalKeys = array();
  1747. $aDBChanges = array();
  1748. foreach($aChanges as $sAttCode => $valuecurr)
  1749. {
  1750. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1751. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1752. if ($oAttDef->IsDirectField())
  1753. {
  1754. $aDBChanges[$sAttCode] = $aChanges[$sAttCode];
  1755. }
  1756. if ($oAttDef->IsHierarchicalKey())
  1757. {
  1758. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1759. }
  1760. }
  1761. if (!MetaModel::DBIsReadOnly())
  1762. {
  1763. // Update the left & right indexes for each hierarchical key
  1764. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1765. {
  1766. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1767. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1768. $aRes = CMDBSource::QueryToArray($sSQL);
  1769. $iMyLeft = $aRes[0]['left'];
  1770. $iMyRight = $aRes[0]['right'];
  1771. $iDelta =$iMyRight - $iMyLeft + 1;
  1772. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1773. if ($aDBChanges[$sAttCode] == 0)
  1774. {
  1775. // No new parent, insert completely at the right of the tree
  1776. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1777. $aRes = CMDBSource::QueryToArray($sSQL);
  1778. if (count($aRes) == 0)
  1779. {
  1780. $iNewLeft = 1;
  1781. }
  1782. else
  1783. {
  1784. $iNewLeft = $aRes[0]['max']+1;
  1785. }
  1786. }
  1787. else
  1788. {
  1789. // Insert at the right of the specified parent
  1790. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aDBChanges[$sAttCode]);
  1791. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1792. }
  1793. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1794. $aHKChanges = array();
  1795. $aHKChanges[$sAttCode] = $aDBChanges[$sAttCode];
  1796. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1797. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1798. $aDBChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1799. }
  1800. // Update scalar attributes
  1801. if (count($aDBChanges) != 0)
  1802. {
  1803. $oFilter = new DBObjectSearch(get_class($this));
  1804. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1805. $oFilter->AllowAllData();
  1806. $sSQL = $oFilter->MakeUpdateQuery($aDBChanges);
  1807. CMDBSource::Query($sSQL);
  1808. }
  1809. }
  1810. $this->DBWriteLinks();
  1811. $this->WriteExternalAttributes();
  1812. $this->m_bDirty = false;
  1813. $this->m_aTouchedAtt = array();
  1814. $this->m_aModifiedAtt = array();
  1815. $this->AfterUpdate();
  1816. // Reload to get the external attributes
  1817. if ($bHasANewExternalKeyValue)
  1818. {
  1819. $this->Reload(true /* AllowAllData */);
  1820. }
  1821. else
  1822. {
  1823. // Reset original values although the object has not been reloaded
  1824. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1825. {
  1826. if ($bLoaded)
  1827. {
  1828. $value = $this->m_aCurrValues[$sAttCode];
  1829. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1830. }
  1831. }
  1832. }
  1833. if (count($aChanges) != 0)
  1834. {
  1835. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1836. }
  1837. }
  1838. catch (Exception $e)
  1839. {
  1840. unset($aUpdateReentrance[$sKey]);
  1841. throw $e;
  1842. }
  1843. unset($aUpdateReentrance[$sKey]);
  1844. return $this->m_iKey;
  1845. }
  1846. public function DBUpdateTracked(CMDBChange $oChange)
  1847. {
  1848. CMDBObject::SetCurrentChange($oChange);
  1849. return $this->DBUpdate();
  1850. }
  1851. // Make the current changes persistent - clever wrapper for Insert or Update
  1852. public function DBWrite()
  1853. {
  1854. if ($this->m_bIsInDB)
  1855. {
  1856. return $this->DBUpdate();
  1857. }
  1858. else
  1859. {
  1860. return $this->DBInsert();
  1861. }
  1862. }
  1863. private function DBDeleteSingleTable($sTableClass)
  1864. {
  1865. $sTable = MetaModel::DBGetTable($sTableClass);
  1866. // Abstract classes or classes having no specific attribute do not have an associated table
  1867. if ($sTable == '') return;
  1868. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1869. $sKey = CMDBSource::Quote($this->m_iKey);
  1870. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1871. CMDBSource::DeleteFrom($sDeleteSQL);
  1872. }
  1873. protected function DBDeleteSingleObject()
  1874. {
  1875. if (!MetaModel::DBIsReadOnly())
  1876. {
  1877. $this->OnDelete();
  1878. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1879. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1880. {
  1881. if ($oAttDef->IsHierarchicalKey())
  1882. {
  1883. // Update the left & right indexes for each hierarchical key
  1884. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1885. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1886. $aRes = CMDBSource::QueryToArray($sSQL);
  1887. $iMyLeft = $aRes[0]['left'];
  1888. $iMyRight = $aRes[0]['right'];
  1889. $iDelta =$iMyRight - $iMyLeft + 1;
  1890. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1891. // No new parent for now, insert completely at the right of the tree
  1892. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1893. $aRes = CMDBSource::QueryToArray($sSQL);
  1894. if (count($aRes) == 0)
  1895. {
  1896. $iNewLeft = 1;
  1897. }
  1898. else
  1899. {
  1900. $iNewLeft = $aRes[0]['max']+1;
  1901. }
  1902. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1903. }
  1904. elseif (!$oAttDef->LoadFromDB())
  1905. {
  1906. $oAttDef->DeleteValue($this);
  1907. }
  1908. }
  1909. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1910. {
  1911. $this->DBDeleteSingleTable($sParentClass);
  1912. }
  1913. $this->AfterDelete();
  1914. $this->m_bIsInDB = false;
  1915. // 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)
  1916. // 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
  1917. }
  1918. }
  1919. // Delete an object... and guarantee data integrity
  1920. //
  1921. public function DBDelete(&$oDeletionPlan = null)
  1922. {
  1923. static $iLoopTimeLimit = null;
  1924. if ($iLoopTimeLimit == null)
  1925. {
  1926. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  1927. }
  1928. if (is_null($oDeletionPlan))
  1929. {
  1930. $oDeletionPlan = new DeletionPlan();
  1931. }
  1932. $this->MakeDeletionPlan($oDeletionPlan);
  1933. $oDeletionPlan->ComputeResults();
  1934. if ($oDeletionPlan->FoundStopper())
  1935. {
  1936. $aIssues = $oDeletionPlan->GetIssues();
  1937. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1938. }
  1939. else
  1940. {
  1941. // Getting and setting time limit are not symetric:
  1942. // www.php.net/manual/fr/function.set-time-limit.php#72305
  1943. $iPreviousTimeLimit = ini_get('max_execution_time');
  1944. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1945. {
  1946. foreach ($aToDelete as $iId => $aData)
  1947. {
  1948. $oToDelete = $aData['to_delete'];
  1949. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1950. // because for each object we would try to update all the preceding ones... that are already deleted
  1951. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1952. // As a temporary fix: delete only the objects that are still to be deleted...
  1953. if ($oToDelete->m_bIsInDB)
  1954. {
  1955. set_time_limit($iLoopTimeLimit);
  1956. $oToDelete->DBDeleteSingleObject();
  1957. }
  1958. }
  1959. }
  1960. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1961. {
  1962. foreach ($aToUpdate as $iId => $aData)
  1963. {
  1964. $oToUpdate = $aData['to_reset'];
  1965. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1966. {
  1967. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1968. set_time_limit($iLoopTimeLimit);
  1969. $oToUpdate->DBUpdate();
  1970. }
  1971. }
  1972. }
  1973. set_time_limit($iPreviousTimeLimit);
  1974. }
  1975. return $oDeletionPlan;
  1976. }
  1977. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1978. {
  1979. CMDBObject::SetCurrentChange($oChange);
  1980. $this->DBDelete($oDeletionPlan);
  1981. }
  1982. public function EnumTransitions()
  1983. {
  1984. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1985. if (empty($sStateAttCode)) return array();
  1986. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1987. return MetaModel::EnumTransitions(get_class($this), $sState);
  1988. }
  1989. /**
  1990. * Designed as an action to be called when a stop watch threshold times out
  1991. * or from within the framework
  1992. * @param $sStimulusCode
  1993. * @param bool|false $bDoNotWrite
  1994. * @return bool
  1995. * @throws CoreException
  1996. * @throws CoreUnexpectedValue
  1997. */
  1998. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  1999. {
  2000. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  2001. if (empty($sStateAttCode))
  2002. {
  2003. throw new CoreException('No lifecycle for the class '.get_class($this));
  2004. }
  2005. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  2006. $aStateTransitions = $this->EnumTransitions();
  2007. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  2008. {
  2009. // This simulus has no effect in the current state... do nothing
  2010. return true;
  2011. }
  2012. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  2013. // Change the state before proceeding to the actions, this is necessary because an action might
  2014. // trigger another stimuli (alternative: push the stimuli into a queue)
  2015. $sPreviousState = $this->Get($sStateAttCode);
  2016. $sNewState = $aTransitionDef['target_state'];
  2017. $this->Set($sStateAttCode, $sNewState);
  2018. // $aTransitionDef is an
  2019. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  2020. $bSuccess = true;
  2021. foreach ($aTransitionDef['actions'] as $actionHandler)
  2022. {
  2023. if (is_string($actionHandler))
  2024. {
  2025. // Old (pre-2.1.0 modules) action definition without any parameter
  2026. $aActionCallSpec = array($this, $actionHandler);
  2027. $sActionDesc = get_class($this).'::'.$actionHandler;
  2028. if (!is_callable($aActionCallSpec))
  2029. {
  2030. throw new CoreException("Unable to call action: ".get_class($this)."::$actionHandler");
  2031. }
  2032. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  2033. }
  2034. else // if (is_array($actionHandler))
  2035. {
  2036. // New syntax: 'verb' and typed parameters
  2037. $sAction = $actionHandler['verb'];
  2038. $sActionDesc = get_class($this).'::'.$sAction;
  2039. $aParams = array();
  2040. foreach($actionHandler['params'] as $aDefinition)
  2041. {
  2042. $sParamType = array_key_exists('type', $aDefinition) ? $aDefinition['type'] : 'string';
  2043. switch($sParamType)
  2044. {
  2045. case 'int':
  2046. $value = (int)$aDefinition['value'];
  2047. break;
  2048. case 'float':
  2049. $value = (float)$aDefinition['value'];
  2050. break;
  2051. case 'bool':
  2052. $value = (bool)$aDefinition['value'];
  2053. break;
  2054. case 'reference':
  2055. $value = ${$aDefinition['value']};
  2056. break;
  2057. case 'string':
  2058. default:
  2059. $value = (string)$aDefinition['value'];
  2060. }
  2061. $aParams[] = $value;
  2062. }
  2063. $aCallSpec = array($this, $sAction);
  2064. $bRet = call_user_func_array($aCallSpec, $aParams);
  2065. }
  2066. // if one call fails, the whole is considered as failed
  2067. // (in case there is no returned value, null is obtained and means "ok")
  2068. if ($bRet === false)
  2069. {
  2070. IssueLog::Info("Lifecycle action $sActionDesc returned false on object #".$this->GetKey());
  2071. $bSuccess = false;
  2072. }
  2073. }
  2074. if ($bSuccess)
  2075. {
  2076. $sClass = get_class($this);
  2077. // Stop watches
  2078. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2079. {
  2080. if ($oAttDef instanceof AttributeStopWatch)
  2081. {
  2082. $oSW = $this->Get($sAttCode);
  2083. if (in_array($sNewState, $oAttDef->GetStates()))
  2084. {
  2085. $oSW->Start($this, $oAttDef);
  2086. }
  2087. else
  2088. {
  2089. $oSW->Stop($this, $oAttDef);
  2090. }
  2091. $this->Set($sAttCode, $oSW);
  2092. }
  2093. }
  2094. if (!$bDoNotWrite)
  2095. {
  2096. $this->DBWrite();
  2097. }
  2098. // Change state triggers...
  2099. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  2100. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  2101. while ($oTrigger = $oSet->Fetch())
  2102. {
  2103. $oTrigger->DoActivate($this->ToArgs('this'));
  2104. }
  2105. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  2106. while ($oTrigger = $oSet->Fetch())
  2107. {
  2108. $oTrigger->DoActivate($this->ToArgs('this'));
  2109. }
  2110. }
  2111. return $bSuccess;
  2112. }
  2113. /**
  2114. * Designed as an action to be called when a stop watch threshold times out
  2115. */
  2116. public function ResetStopWatch($sAttCode)
  2117. {
  2118. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2119. if (!$oAttDef instanceof AttributeStopWatch)
  2120. {
  2121. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  2122. }
  2123. $oSW = $this->Get($sAttCode);
  2124. $oSW->Reset($this, $oAttDef);
  2125. $this->Set($sAttCode, $oSW);
  2126. return true;
  2127. }
  2128. /**
  2129. * Lifecycle action: Recover the default value (aka when an object is being created)
  2130. */
  2131. public function Reset($sAttCode)
  2132. {
  2133. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2134. $this->Set($sAttCode, $oAttDef->GetDefaultValue($this));
  2135. return true;
  2136. }
  2137. /**
  2138. * Lifecycle action: Copy an attribute to another
  2139. */
  2140. public function Copy($sDestAttCode, $sSourceAttCode)
  2141. {
  2142. $this->Set($sDestAttCode, $this->Get($sSourceAttCode));
  2143. return true;
  2144. }
  2145. /**
  2146. * Lifecycle action: Set the current date/time for the given attribute
  2147. */
  2148. public function SetCurrentDate($sAttCode)
  2149. {
  2150. $this->Set($sAttCode, time());
  2151. return true;
  2152. }
  2153. /**
  2154. * Lifecycle action: Set the current logged in user for the given attribute
  2155. */
  2156. public function SetCurrentUser($sAttCode)
  2157. {
  2158. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2159. if ($oAttDef instanceof AttributeString)
  2160. {
  2161. // Note: the user friendly name is the contact friendly name if a contact is attached to the logged in user
  2162. $this->Set($sAttCode, UserRights::GetUserFriendlyName());
  2163. }
  2164. else
  2165. {
  2166. if ($oAttDef->IsExternalKey())
  2167. {
  2168. if ($oAttDef->GetTargetClass() != 'User')
  2169. {
  2170. throw new Exception("SetCurrentUser: the attribute $sAttCode must be an external key to 'User', found '".$oAttDef->GetTargetClass()."'");
  2171. }
  2172. }
  2173. $this->Set($sAttCode, UserRights::GetUserId());
  2174. }
  2175. return true;
  2176. }
  2177. /**
  2178. * Lifecycle action: Set the current logged in CONTACT for the given attribute
  2179. */
  2180. public function SetCurrentPerson($sAttCode)
  2181. {
  2182. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2183. if ($oAttDef instanceof AttributeString)
  2184. {
  2185. $iPerson = UserRights::GetContactId();
  2186. if ($iPerson == 0)
  2187. {
  2188. $this->Set($sAttCode, '');
  2189. }
  2190. else
  2191. {
  2192. $oPerson = MetaModel::GetObject('Person', $iPerson);
  2193. $this->Set($sAttCode, $oPerson->Get('friendlyname'));
  2194. }
  2195. }
  2196. else
  2197. {
  2198. if ($oAttDef->IsExternalKey())
  2199. {
  2200. if (!MetaModel::IsParentClass($oAttDef->GetTargetClass(), 'Person'))
  2201. {
  2202. throw new Exception("SetCurrentContact: the attribute $sAttCode must be an external key to 'Person' or any other class above 'Person', found '".$oAttDef->GetTargetClass()."'");
  2203. }
  2204. }
  2205. $this->Set($sAttCode, UserRights::GetContactId());
  2206. }
  2207. return true;
  2208. }
  2209. /**
  2210. * Lifecycle action: Set the time elapsed since a reference point
  2211. */
  2212. public function SetElapsedTime($sAttCode, $sRefAttCode, $sWorkingTimeComputer = null)
  2213. {
  2214. if (is_null($sWorkingTimeComputer))
  2215. {
  2216. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  2217. }
  2218. $oComputer = new $sWorkingTimeComputer();
  2219. $aCallSpec = array($oComputer, 'GetOpenDuration');
  2220. if (!is_callable($aCallSpec))
  2221. {
  2222. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  2223. }
  2224. $iStartTime = AttributeDateTime::GetAsUnixSeconds($this->Get($sRefAttCode));
  2225. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  2226. $oEndDate = new DateTime(); // now
  2227. if (class_exists('WorkingTimeRecorder'))
  2228. {
  2229. $sClass = get_class($this);
  2230. WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', array("Class:$sClass/Attribute:$sAttCode"));
  2231. }
  2232. $iElapsed = call_user_func($aCallSpec, $this, $oStartDate, $oEndDate);
  2233. if (class_exists('WorkingTimeRecorder'))
  2234. {
  2235. WorkingTimeRecorder::End();
  2236. }
  2237. $this->Set($sAttCode, $iElapsed);
  2238. return true;
  2239. }
  2240. /**
  2241. * Create query parameters (SELECT ... WHERE service = :this->service_id)
  2242. * to be used with the APIs DBObjectSearch/DBObjectSet
  2243. *
  2244. * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
  2245. * in VariableExpression::Render()
  2246. */
  2247. public function ToArgsForQuery($sArgName = 'this')
  2248. {
  2249. return array($sArgName.'->object()' => $this);
  2250. }
  2251. /**
  2252. * Create template placeholders: now equivalent to ToArgsForQuery since the actual
  2253. * template placeholders are computed on demand.
  2254. */
  2255. public function ToArgs($sArgName = 'this')
  2256. {
  2257. return $this->ToArgsForQuery($sArgName);
  2258. }
  2259. public function GetForTemplate($sPlaceholderAttCode)
  2260. {
  2261. $ret = null;
  2262. if (preg_match('/^([^-]+)-(>|&gt;)(.+)$/', $sPlaceholderAttCode, $aMatches)) // Support both syntaxes: this->xxx or this-&gt;xxx for HTML compatibility
  2263. {
  2264. $sExtKeyAttCode = $aMatches[1];
  2265. $sRemoteAttCode = $aMatches[3];
  2266. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  2267. {
  2268. throw new CoreException("Unknown attribute '$sExtKeyAttCode' for the class ".get_class($this));
  2269. }
  2270. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  2271. if (!$oKeyAttDef instanceof AttributeExternalKey)
  2272. {
  2273. throw new CoreException("'$sExtKeyAttCode' is not an external key of the class ".get_class($this));
  2274. }
  2275. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  2276. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  2277. if (is_null($oRemoteObj))
  2278. {
  2279. $ret = Dict::S('UI:UndefinedObject');
  2280. }
  2281. else
  2282. {
  2283. // Recurse
  2284. $ret = $oRemoteObj->GetForTemplate($sRemoteAttCode);
  2285. }
  2286. }
  2287. else
  2288. {
  2289. switch($sPlaceholderAttCode)
  2290. {
  2291. case 'id':
  2292. $ret = $this->GetKey();
  2293. break;
  2294. case 'name()':
  2295. $ret = $this->GetName();
  2296. break;
  2297. default:
  2298. if (preg_match('/^([^(]+)\\((.*)\\)$/', $sPlaceholderAttCode, $aMatches))
  2299. {
  2300. $sVerb = $aMatches[1];
  2301. $sAttCode = $aMatches[2];
  2302. }
  2303. else
  2304. {
  2305. $sVerb = '';
  2306. $sAttCode = $sPlaceholderAttCode;
  2307. }
  2308. if ($sVerb == 'hyperlink')
  2309. {
  2310. $sPortalId = ($sAttCode === '') ? 'console' : $sAttCode;
  2311. if (!array_key_exists($sPortalId, self::$aPortalToURLMaker))
  2312. {
  2313. throw new Exception("Unknown portal id '$sPortalId' in placeholder '$sPlaceholderAttCode''");
  2314. }
  2315. $ret = $this->GetHyperlink(self::$aPortalToURLMaker[$sPortalId], false);
  2316. }
  2317. else
  2318. {
  2319. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2320. $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this);
  2321. }
  2322. }
  2323. if ($ret === null)
  2324. {
  2325. $ret = '';
  2326. }
  2327. }
  2328. return $ret;
  2329. }
  2330. static protected $aPortalToURLMaker = array('console' => 'iTopStandardURLMaker', 'portal' => 'PortalURLMaker');
  2331. /**
  2332. * Associate a portal to a class that implements iDBObjectURLMaker,
  2333. * and which will be invoked with placeholders like $this->org_id->hyperlink(portal)$
  2334. *
  2335. * @param $sPortalId Identifies the portal. Conventions: the main portal is 'console', The user requests portal is 'portal'.
  2336. * @param $sUrlMakerClass
  2337. */
  2338. static public function RegisterURLMakerClass($sPortalId, $sUrlMakerClass)
  2339. {
  2340. self::$aPortalToURLMaker[$sPortalId] = $sUrlMakerClass;
  2341. }
  2342. // To be optionaly overloaded
  2343. protected function OnInsert()
  2344. {
  2345. }
  2346. // To be optionaly overloaded
  2347. protected function AfterInsert()
  2348. {
  2349. }
  2350. // To be optionaly overloaded
  2351. protected function OnUpdate()
  2352. {
  2353. }
  2354. // To be optionaly overloaded
  2355. protected function AfterUpdate()
  2356. {
  2357. }
  2358. // To be optionaly overloaded
  2359. protected function OnDelete()
  2360. {
  2361. }
  2362. // To be optionaly overloaded
  2363. protected function AfterDelete()
  2364. {
  2365. }
  2366. /**
  2367. * Common to the recording of link set changes (add/remove/modify)
  2368. */
  2369. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  2370. {
  2371. if ($iLinkSetOwnerId <= 0)
  2372. {
  2373. return null;
  2374. }
  2375. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  2376. {
  2377. // The link set owner class does not keep track of its history
  2378. return null;
  2379. }
  2380. // Determine the linked item class and id
  2381. //
  2382. if ($oLinkSet->IsIndirect())
  2383. {
  2384. // The "item" is on the other end (N-N links)
  2385. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  2386. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  2387. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  2388. if ($aOriginalValues)
  2389. {
  2390. // Get the value from the original values
  2391. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  2392. }
  2393. else
  2394. {
  2395. $iItemId = $this->Get($sExtKeyToRemote);
  2396. }
  2397. }
  2398. else
  2399. {
  2400. // I am the "item" (1-N links)
  2401. $sItemClass = get_class($this);
  2402. $iItemId = $this->GetKey();
  2403. }
  2404. // Get the remote object, to determine its exact class
  2405. // 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!
  2406. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  2407. if ($oOwner)
  2408. {
  2409. $sLinkSetOwnerClass = get_class($oOwner);
  2410. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  2411. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  2412. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  2413. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  2414. $oMyChangeOp->Set("item_class", $sItemClass);
  2415. $oMyChangeOp->Set("item_id", $iItemId);
  2416. return $oMyChangeOp;
  2417. }
  2418. else
  2419. {
  2420. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  2421. return null;
  2422. }
  2423. }
  2424. /**
  2425. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  2426. */
  2427. private function RecordLinkSetListChange($bAdd = true)
  2428. {
  2429. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2430. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2431. {
  2432. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2433. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2434. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2435. if ($oMyChangeOp)
  2436. {
  2437. if ($bAdd)
  2438. {
  2439. $oMyChangeOp->Set("type", "added");
  2440. }
  2441. else
  2442. {
  2443. $oMyChangeOp->Set("type", "removed");
  2444. }
  2445. $iId = $oMyChangeOp->DBInsertNoReload();
  2446. }
  2447. }
  2448. }
  2449. protected function RecordObjCreation()
  2450. {
  2451. $this->RecordLinkSetListChange(true);
  2452. }
  2453. protected function RecordObjDeletion($objkey)
  2454. {
  2455. $this->RecordLinkSetListChange(false);
  2456. }
  2457. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  2458. {
  2459. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2460. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2461. {
  2462. if (array_key_exists($sExtKeyAttCode, $aValues))
  2463. {
  2464. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2465. // Keep track of link added/removed
  2466. //
  2467. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  2468. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2469. if ($oMyChangeOp)
  2470. {
  2471. $oMyChangeOp->Set("type", "added");
  2472. $oMyChangeOp->DBInsertNoReload();
  2473. }
  2474. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  2475. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  2476. if ($oMyChangeOp)
  2477. {
  2478. $oMyChangeOp->Set("type", "removed");
  2479. $oMyChangeOp->DBInsertNoReload();
  2480. }
  2481. }
  2482. else
  2483. {
  2484. // Keep track of link changes
  2485. //
  2486. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  2487. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2488. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  2489. if ($oMyChangeOp)
  2490. {
  2491. $oMyChangeOp->Set("link_id", $this->GetKey());
  2492. $iId = $oMyChangeOp->DBInsertNoReload();
  2493. }
  2494. }
  2495. }
  2496. }
  2497. // Return an empty set for the parent of all
  2498. // May be overloaded.
  2499. // Anyhow, this way of implementing the relations suffers limitations (not handling the redundancy)
  2500. // and you should consider defining those things in XML.
  2501. public static function GetRelationQueries($sRelCode)
  2502. {
  2503. return array();
  2504. }
  2505. // Reserved: do not overload
  2506. public static function GetRelationQueriesEx($sRelCode)
  2507. {
  2508. return array();
  2509. }
  2510. /**
  2511. * Will be deprecated soon - use GetRelatedObjectsDown/Up instead to take redundancy into account
  2512. */
  2513. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  2514. {
  2515. // Temporary patch: until the impact analysis GUI gets rewritten,
  2516. // let's consider that "depends on" is equivalent to "impacts/up"
  2517. // The current patch has been implemented in DBObject and MetaModel
  2518. $sHackedRelCode = $sRelCode;
  2519. $bDown = true;
  2520. if ($sRelCode == 'depends on')
  2521. {
  2522. $sHackedRelCode = 'impacts';
  2523. $bDown = false;
  2524. }
  2525. foreach (MetaModel::EnumRelationQueries(get_class($this), $sHackedRelCode, $bDown) as $sDummy => $aQueryInfo)
  2526. {
  2527. $sQuery = $bDown ? $aQueryInfo['sQueryDown'] : $aQueryInfo['sQueryUp'];
  2528. //$bPropagate = $aQueryInfo["bPropagate"];
  2529. //$iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  2530. $iDepth = $iMaxDepth - 1;
  2531. // Note: the loop over the result set has been written in an unusual way for error reporting purposes
  2532. // In the case of a wrong query parameter name, the error occurs on the first call to Fetch,
  2533. // thus we need to have this first call into the try/catch, but
  2534. // we do NOT want to nest the try/catch for the error message to be clear
  2535. try
  2536. {
  2537. $oFlt = DBObjectSearch::FromOQL($sQuery);
  2538. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgsForQuery());
  2539. $oObj = $oObjSet->Fetch();
  2540. }
  2541. catch (Exception $e)
  2542. {
  2543. $sClassOfDefinition = $aQueryInfo['_legacy_'] ? get_class($this).'(or a parent)::GetRelationQueries()' : $aQueryInfo['sDefinedInClass'];
  2544. throw new Exception("Wrong query for the relation $sRelCode/$sClassOfDefinition/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
  2545. }
  2546. if ($oObj)
  2547. {
  2548. do
  2549. {
  2550. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  2551. $sObjKey = $oObj->GetKey();
  2552. if (array_key_exists($sRootClass, $aResults))
  2553. {
  2554. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  2555. {
  2556. continue; // already visited, skip
  2557. }
  2558. }
  2559. $aResults[$sRootClass][$sObjKey] = $oObj;
  2560. if ($iDepth > 0)
  2561. {
  2562. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  2563. }
  2564. }
  2565. while ($oObj = $oObjSet->Fetch());
  2566. }
  2567. }
  2568. return $aResults;
  2569. }
  2570. /**
  2571. * Compute the "RelatedObjects" (forward or "down" direction) for the object
  2572. * for the specified relation
  2573. *
  2574. * @param string $sRelCode The code of the relation to use for the computation
  2575. * @param int $iMaxDepth Maximum recursion depth
  2576. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2577. *
  2578. * @return RelationGraph The graph of all the related objects
  2579. */
  2580. public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2581. {
  2582. $oGraph = new RelationGraph();
  2583. $oGraph->AddSourceObject($this);
  2584. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2585. return $oGraph;
  2586. }
  2587. /**
  2588. * Compute the "RelatedObjects" (reverse or "up" direction) for the object
  2589. * for the specified relation
  2590. *
  2591. * @param string $sRelCode The code of the relation to use for the computation
  2592. * @param int $iMaxDepth Maximum recursion depth
  2593. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2594. *
  2595. * @return RelationGraph The graph of all the related objects
  2596. */
  2597. public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2598. {
  2599. $oGraph = new RelationGraph();
  2600. $oGraph->AddSourceObject($this);
  2601. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2602. return $oGraph;
  2603. }
  2604. public function GetReferencingObjects($bAllowAllData = false)
  2605. {
  2606. $aDependentObjects = array();
  2607. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  2608. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  2609. {
  2610. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  2611. {
  2612. // skip if this external key is behind an external field
  2613. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  2614. $oSearch = new DBObjectSearch($sRemoteClass);
  2615. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  2616. if ($bAllowAllData)
  2617. {
  2618. $oSearch->AllowAllData();
  2619. }
  2620. $oSet = new CMDBObjectSet($oSearch);
  2621. if ($oSet->Count() > 0)
  2622. {
  2623. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  2624. 'attribute' => $oExtKeyAttDef,
  2625. 'objects' => $oSet,
  2626. );
  2627. }
  2628. }
  2629. }
  2630. return $aDependentObjects;
  2631. }
  2632. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  2633. {
  2634. static $iLoopTimeLimit = null;
  2635. if ($iLoopTimeLimit == null)
  2636. {
  2637. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2638. }
  2639. $sClass = get_class($this);
  2640. $iThisId = $this->GetKey();
  2641. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  2642. if (array_key_exists($sClass, $aVisited))
  2643. {
  2644. if (in_array($iThisId, $aVisited[$sClass]))
  2645. {
  2646. return;
  2647. }
  2648. }
  2649. $aVisited[$sClass] = $iThisId;
  2650. if ($iDeleteOption == DEL_MANUAL)
  2651. {
  2652. // Stop the recursion here
  2653. return;
  2654. }
  2655. // Check the node itself
  2656. $this->DoCheckToDelete($oDeletionPlan);
  2657. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  2658. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  2659. // Getting and setting time limit are not symetric:
  2660. // www.php.net/manual/fr/function.set-time-limit.php#72305
  2661. $iPreviousTimeLimit = ini_get('max_execution_time');
  2662. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  2663. {
  2664. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  2665. {
  2666. set_time_limit($iLoopTimeLimit);
  2667. $oAttDef = $aData['attribute'];
  2668. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  2669. $oDepSet = $aData['objects'];
  2670. $oDepSet->Rewind();
  2671. while ($oDependentObj = $oDepSet->fetch())
  2672. {
  2673. $iId = $oDependentObj->GetKey();
  2674. if ($oAttDef->IsNullAllowed())
  2675. {
  2676. // Optional external key, list to reset
  2677. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  2678. {
  2679. // Move the child up one level i.e. set the same parent as the current object
  2680. $iParentId = $this->Get($oAttDef->GetCode());
  2681. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  2682. }
  2683. else
  2684. {
  2685. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  2686. }
  2687. }
  2688. else
  2689. {
  2690. // Mandatory external key, list to delete
  2691. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  2692. }
  2693. }
  2694. }
  2695. }
  2696. set_time_limit($iPreviousTimeLimit);
  2697. }
  2698. /**
  2699. * WILL DEPRECATED SOON
  2700. * Caching relying on an object set is not efficient since 2.0.3
  2701. * Use GetSynchroData instead
  2702. *
  2703. * Get all the synchro replica related to this object
  2704. * @param none
  2705. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  2706. */
  2707. public function GetMasterReplica()
  2708. {
  2709. $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";
  2710. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2711. return $oReplicaSet;
  2712. }
  2713. /**
  2714. * Get all the synchro data related to this object
  2715. * @param none
  2716. * @return array of data_source_id => array
  2717. * 'source' => $oSource,
  2718. * 'attributes' => array of $oSynchroAttribute
  2719. * 'replica' => array of $oReplica (though only one should exist, misuse of the data sync can have this consequence)
  2720. */
  2721. public function GetSynchroData()
  2722. {
  2723. if (is_null($this->m_aSynchroData))
  2724. {
  2725. $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";
  2726. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2727. $this->m_aSynchroData = array();
  2728. while($aData = $oReplicaSet->FetchAssoc())
  2729. {
  2730. $iSourceId = $aData['datasource']->GetKey();
  2731. if (!array_key_exists($iSourceId, $this->m_aSynchroData))
  2732. {
  2733. $aAttributes = array();
  2734. $oAttrSet = $aData['datasource']->Get('attribute_list');
  2735. while($oSyncAttr = $oAttrSet->Fetch())
  2736. {
  2737. $aAttributes[$oSyncAttr->Get('attcode')] = $oSyncAttr;
  2738. }
  2739. $this->m_aSynchroData[$iSourceId] = array(
  2740. 'source' => $aData['datasource'],
  2741. 'attributes' => $aAttributes,
  2742. 'replica' => array()
  2743. );
  2744. }
  2745. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2746. $this->m_aSynchroData[$iSourceId]['replica'][] = $aData['replica'];
  2747. }
  2748. }
  2749. return $this->m_aSynchroData;
  2750. }
  2751. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2752. {
  2753. $iFlags = OPT_ATT_NORMAL;
  2754. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  2755. {
  2756. if ($iSourceId == SynchroExecution::GetCurrentTaskId())
  2757. {
  2758. // Ignore the current task (check to write => ok)
  2759. continue;
  2760. }
  2761. // Assumption: one replica - take the first one!
  2762. $oReplica = reset($aSourceData['replica']);
  2763. $oSource = $aSourceData['source'];
  2764. if (array_key_exists($sAttCode, $aSourceData['attributes']))
  2765. {
  2766. $oSyncAttr = $aSourceData['attributes'][$sAttCode];
  2767. if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2768. {
  2769. $iFlags |= OPT_ATT_SLAVE;
  2770. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2771. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2772. }
  2773. }
  2774. }
  2775. return $iFlags;
  2776. }
  2777. public function InSyncScope()
  2778. {
  2779. //
  2780. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2781. //
  2782. static $aSynchroClasses = null;
  2783. if (is_null($aSynchroClasses))
  2784. {
  2785. $aSynchroClasses = array();
  2786. $sOQL = "SELECT SynchroDataSource AS datasource";
  2787. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2788. while($oSource = $oSourceSet->Fetch())
  2789. {
  2790. $sTarget = $oSource->Get('scope_class');
  2791. $aSynchroClasses[] = $sTarget;
  2792. }
  2793. }
  2794. foreach($aSynchroClasses as $sClass)
  2795. {
  2796. if ($this instanceof $sClass)
  2797. {
  2798. return true;
  2799. }
  2800. }
  2801. return false;
  2802. }
  2803. /////////////////////////////////////////////////////////////////////////
  2804. //
  2805. // Experimental iDisplay implementation
  2806. //
  2807. /////////////////////////////////////////////////////////////////////////
  2808. public static function MapContextParam($sContextParam)
  2809. {
  2810. return null;
  2811. }
  2812. public function GetHilightClass()
  2813. {
  2814. $sCode = $this->ComputeHighlightCode();
  2815. if($sCode != '')
  2816. {
  2817. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  2818. if (array_key_exists($sCode, $aHighlightScale))
  2819. {
  2820. return $aHighlightScale[$sCode]['color'];
  2821. }
  2822. }
  2823. return HILIGHT_CLASS_NONE;
  2824. }
  2825. public function DisplayDetails(WebPage $oPage, $bEditMode = false)
  2826. {
  2827. $oPage->add('<h1>'.MetaModel::GetName(get_class($this)).': '.$this->GetName().'</h1>');
  2828. $aValues = array();
  2829. $aList = MetaModel::FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2830. if (empty($aList))
  2831. {
  2832. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2833. }
  2834. foreach($aList as $sAttCode)
  2835. {
  2836. $aValues[$sAttCode] = array('label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode));
  2837. }
  2838. $oPage->details($aValues);
  2839. }
  2840. const CALLBACK_AFTERINSERT = 0;
  2841. /**
  2842. * Register a call back that will be called when some internal event happens
  2843. *
  2844. * @param $iType string Any of the CALLBACK_x constants
  2845. * @param $callback callable Call specification like a function name, or array('<class>', '<method>') or array($object, '<method>')
  2846. * @param $aParameters Array Values that will be passed to the callback, after $this
  2847. */
  2848. public function RegisterCallback($iType, $callback, $aParameters = array())
  2849. {
  2850. $sCallBackName = '';
  2851. if (!is_callable($callback, false, $sCallBackName))
  2852. {
  2853. throw new Exception('Registering an unknown/protected function or wrong syntax for the call spec: '.$sCallBackName);
  2854. }
  2855. $this->m_aCallbacks[$iType][] = array(
  2856. 'callback' => $callback,
  2857. 'params' => $aParameters
  2858. );
  2859. }
  2860. /**
  2861. * Computes a text-like fingerprint identifying the content of the object
  2862. * but excluding the specified columns
  2863. * @param $aExcludedColumns array The list of columns to exclude
  2864. * @return string
  2865. */
  2866. public function Fingerprint($aExcludedColumns = array())
  2867. {
  2868. $sFingerprint = '';
  2869. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2870. {
  2871. if (!in_array($sAttCode, $aExcludedColumns))
  2872. {
  2873. if ($oAttDef->IsPartOfFingerprint())
  2874. {
  2875. $sFingerprint .= chr(0).$oAttDef->Fingerprint($this->Get($sAttCode));
  2876. }
  2877. }
  2878. }
  2879. return $sFingerprint;
  2880. }
  2881. /**
  2882. * Execute a set of scripted actions onto the current object
  2883. * See ExecAction for the syntax and features of the scripted actions
  2884. *
  2885. * @param $aActions array of statements (e.g. "set(name, Made after $source->name$)")
  2886. * @param $aSourceObjects Array of Alias => Context objects (Convention: some statements require the 'source' element
  2887. * @throws Exception
  2888. */
  2889. public function ExecActions($aActions, $aSourceObjects)
  2890. {
  2891. foreach($aActions as $sAction)
  2892. {
  2893. try
  2894. {
  2895. if (preg_match('/^(\S*)\s*\((.*)\)$/ms', $sAction, $aMatches)) // multiline and newline matched by a dot
  2896. {
  2897. $sVerb = trim($aMatches[1]);
  2898. $sParams = $aMatches[2];
  2899. // the coma is the separator for the parameters
  2900. // comas can be escaped: \,
  2901. $sParams = str_replace(array("\\\\", "\\,"), array("__backslash__", "__coma__"), $sParams);
  2902. $sParams = trim($sParams);
  2903. if (strlen($sParams) == 0)
  2904. {
  2905. $aParams = array();
  2906. }
  2907. else
  2908. {
  2909. $aParams = explode(',', $sParams);
  2910. foreach ($aParams as &$sParam)
  2911. {
  2912. $sParam = str_replace(array("__backslash__", "__coma__"), array("\\", ","), $sParam);
  2913. $sParam = trim($sParam);
  2914. }
  2915. }
  2916. $this->ExecAction($sVerb, $aParams, $aSourceObjects);
  2917. }
  2918. else
  2919. {
  2920. throw new Exception("Invalid syntax");
  2921. }
  2922. }
  2923. catch(Exception $e)
  2924. {
  2925. throw new Exception('Action: '.$sAction.' - '.$e->getMessage());
  2926. }
  2927. }
  2928. }
  2929. /**
  2930. * Helper to copy an attribute between two objects (in memory)
  2931. * Originally designed for ExecAction()
  2932. */
  2933. public function CopyAttribute($oSourceObject, $sSourceAttCode, $sDestAttCode)
  2934. {
  2935. if ($sSourceAttCode == 'id')
  2936. {
  2937. $oSourceAttDef = null;
  2938. }
  2939. else
  2940. {
  2941. if (!MetaModel::IsValidAttCode(get_class($this), $sDestAttCode))
  2942. {
  2943. throw new Exception("Unknown attribute ".get_class($this)."::".$sDestAttCode);
  2944. }
  2945. if (!MetaModel::IsValidAttCode(get_class($oSourceObject), $sSourceAttCode))
  2946. {
  2947. throw new Exception("Unknown attribute ".get_class($oSourceObject)."::".$sSourceAttCode);
  2948. }
  2949. $oSourceAttDef = MetaModel::GetAttributeDef(get_class($oSourceObject), $sSourceAttCode);
  2950. }
  2951. if (is_object($oSourceAttDef) && $oSourceAttDef->IsLinkSet())
  2952. {
  2953. // The copy requires that we create a new object set (the semantic of DBObject::Set is unclear about link sets)
  2954. $oDestSet = DBObjectSet::FromScratch($oSourceAttDef->GetLinkedClass());
  2955. $oSourceSet = $oSourceObject->Get($sSourceAttCode);
  2956. $oSourceSet->Rewind();
  2957. while ($oSourceLink = $oSourceSet->Fetch())
  2958. {
  2959. // Clone the link
  2960. $sLinkClass = get_class($oSourceLink);
  2961. $oLinkClone = MetaModel::NewObject($sLinkClass);
  2962. foreach(MetaModel::ListAttributeDefs($sLinkClass) as $sAttCode => $oAttDef)
  2963. {
  2964. // As of now, ignore other attribute (do not attempt to recurse!)
  2965. if ($oAttDef->IsScalar())
  2966. {
  2967. $oLinkClone->Set($sAttCode, $oSourceLink->Get($sAttCode));
  2968. }
  2969. }
  2970. // Not necessary - this will be handled by DBObject
  2971. // $oLinkClone->Set($oSourceAttDef->GetExtKeyToMe(), 0);
  2972. $oDestSet->AddObject($oLinkClone);
  2973. }
  2974. $this->Set($sDestAttCode, $oDestSet);
  2975. }
  2976. else
  2977. {
  2978. $this->Set($sDestAttCode, $oSourceObject->Get($sSourceAttCode));
  2979. }
  2980. }
  2981. /**
  2982. * Execute a scripted action onto the current object
  2983. * - clone (att1, att2, att3, ...)
  2984. * - clone_scalars ()
  2985. * - copy (source_att, dest_att)
  2986. * - reset (att)
  2987. * - nullify (att)
  2988. * - set (att, value (placeholders $source->att$ or $current_date$, or $current_contact_id$, ...))
  2989. * - append (att, value (placeholders $source->att$ or $current_date$, or $current_contact_id$, ...))
  2990. * - add_to_list (source_key_att, dest_att)
  2991. * - add_to_list (source_key_att, dest_att, lnk_att, lnk_att_value)
  2992. * - apply_stimulus (stimulus)
  2993. * - call_method (method_name)
  2994. *
  2995. * @param $sVerb string Any of the verb listed above (e.g. "set")
  2996. * @param $aParams array of strings (e.g. array('name', 'copied from $source->name$')
  2997. * @param $aSourceObjects Array of Alias => Context objects (Convention: some statements require the 'source' element
  2998. * @throws CoreException
  2999. * @throws CoreUnexpectedValue
  3000. * @throws Exception
  3001. */
  3002. public function ExecAction($sVerb, $aParams, $aSourceObjects)
  3003. {
  3004. switch($sVerb)
  3005. {
  3006. case 'clone':
  3007. if (!array_key_exists('source', $aSourceObjects))
  3008. {
  3009. throw new Exception('Missing conventional "source" object');
  3010. }
  3011. $oObjectToRead = $aSourceObjects['source'];
  3012. foreach($aParams as $sAttCode)
  3013. {
  3014. $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
  3015. }
  3016. break;
  3017. case 'clone_scalars':
  3018. if (!array_key_exists('source', $aSourceObjects))
  3019. {
  3020. throw new Exception('Missing conventional "source" object');
  3021. }
  3022. $oObjectToRead = $aSourceObjects['source'];
  3023. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  3024. {
  3025. if ($oAttDef->IsScalar())
  3026. {
  3027. $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
  3028. }
  3029. }
  3030. break;
  3031. case 'copy':
  3032. if (!array_key_exists('source', $aSourceObjects))
  3033. {
  3034. throw new Exception('Missing conventional "source" object');
  3035. }
  3036. $oObjectToRead = $aSourceObjects['source'];
  3037. if (!array_key_exists(0, $aParams))
  3038. {
  3039. throw new Exception('Missing argument #1: source attribute');
  3040. }
  3041. $sSourceAttCode = $aParams[0];
  3042. if (!array_key_exists(1, $aParams))
  3043. {
  3044. throw new Exception('Missing argument #2: target attribute');
  3045. }
  3046. $sDestAttCode = $aParams[1];
  3047. $this->CopyAttribute($oObjectToRead, $sSourceAttCode, $sDestAttCode);
  3048. break;
  3049. case 'reset':
  3050. if (!array_key_exists(0, $aParams))
  3051. {
  3052. throw new Exception('Missing argument #1: target attribute');
  3053. }
  3054. $sAttCode = $aParams[0];
  3055. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3056. {
  3057. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3058. }
  3059. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  3060. $this->Set($sAttCode, $oAttDef->GetDefaultValue());
  3061. break;
  3062. case 'nullify':
  3063. if (!array_key_exists(0, $aParams))
  3064. {
  3065. throw new Exception('Missing argument #1: target attribute');
  3066. }
  3067. $sAttCode = $aParams[0];
  3068. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3069. {
  3070. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3071. }
  3072. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  3073. $this->Set($sAttCode, $oAttDef->GetNullValue());
  3074. break;
  3075. case 'set':
  3076. if (!array_key_exists(0, $aParams))
  3077. {
  3078. throw new Exception('Missing argument #1: target attribute');
  3079. }
  3080. $sAttCode = $aParams[0];
  3081. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3082. {
  3083. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3084. }
  3085. if (!array_key_exists(1, $aParams))
  3086. {
  3087. throw new Exception('Missing argument #2: value to set');
  3088. }
  3089. $sRawValue = $aParams[1];
  3090. $aContext = array();
  3091. foreach ($aSourceObjects as $sAlias => $oObject)
  3092. {
  3093. $aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
  3094. }
  3095. $aContext['current_contact_id'] = UserRights::GetContactId();
  3096. $aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
  3097. $aContext['current_date'] = date(AttributeDate::GetSQLFormat());
  3098. $aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
  3099. $sValue = MetaModel::ApplyParams($sRawValue, $aContext);
  3100. $this->Set($sAttCode, $sValue);
  3101. break;
  3102. case 'append':
  3103. if (!array_key_exists(0, $aParams))
  3104. {
  3105. throw new Exception('Missing argument #1: target attribute');
  3106. }
  3107. $sAttCode = $aParams[0];
  3108. if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
  3109. {
  3110. throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
  3111. }
  3112. if (!array_key_exists(1, $aParams))
  3113. {
  3114. throw new Exception('Missing argument #2: value to append');
  3115. }
  3116. $sRawAddendum = $aParams[1];
  3117. $aContext = array();
  3118. foreach ($aSourceObjects as $sAlias => $oObject)
  3119. {
  3120. $aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
  3121. }
  3122. $aContext['current_contact_id'] = UserRights::GetContactId();
  3123. $aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
  3124. $aContext['current_date'] = date(AttributeDate::GetSQLFormat());
  3125. $aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
  3126. $sAddendum = MetaModel::ApplyParams($sRawAddendum, $aContext);
  3127. $this->Set($sAttCode, $this->Get($sAttCode).$sAddendum);
  3128. break;
  3129. case 'add_to_list':
  3130. if (!array_key_exists('source', $aSourceObjects))
  3131. {
  3132. throw new Exception('Missing conventional "source" object');
  3133. }
  3134. $oObjectToRead = $aSourceObjects['source'];
  3135. if (!array_key_exists(0, $aParams))
  3136. {
  3137. throw new Exception('Missing argument #1: source attribute');
  3138. }
  3139. $sSourceKeyAttCode = $aParams[0];
  3140. if (($sSourceKeyAttCode != 'id') && !MetaModel::IsValidAttCode(get_class($oObjectToRead), $sSourceKeyAttCode))
  3141. {
  3142. throw new Exception("Unknown attribute ".get_class($oObjectToRead)."::".$sSourceKeyAttCode);
  3143. }
  3144. if (!array_key_exists(1, $aParams))
  3145. {
  3146. throw new Exception('Missing argument #2: target attribute (link set)');
  3147. }
  3148. $sTargetListAttCode = $aParams[1]; // indirect !!!
  3149. if (!MetaModel::IsValidAttCode(get_class($this), $sTargetListAttCode))
  3150. {
  3151. throw new Exception("Unknown attribute ".get_class($this)."::".$sTargetListAttCode);
  3152. }
  3153. if (isset($aParams[2]) && isset($aParams[3]))
  3154. {
  3155. $sRoleAttCode = $aParams[2];
  3156. $sRoleValue = $aParams[3];
  3157. }
  3158. $iObjKey = $oObjectToRead->Get($sSourceKeyAttCode);
  3159. if ($iObjKey > 0)
  3160. {
  3161. $oLinkSet = $this->Get($sTargetListAttCode);
  3162. $oListAttDef = MetaModel::GetAttributeDef(get_class($this), $sTargetListAttCode);
  3163. $oLnk = MetaModel::NewObject($oListAttDef->GetLinkedClass());
  3164. $oLnk->Set($oListAttDef->GetExtKeyToRemote(), $iObjKey);
  3165. if (isset($sRoleAttCode))
  3166. {
  3167. if (!MetaModel::IsValidAttCode(get_class($oLnk), $sRoleAttCode))
  3168. {
  3169. throw new Exception("Unknown attribute ".get_class($oLnk)."::".$sRoleAttCode);
  3170. }
  3171. $oLnk->Set($sRoleAttCode, $sRoleValue);
  3172. }
  3173. $oLinkSet->AddObject($oLnk);
  3174. $this->Set($sTargetListAttCode, $oLinkSet);
  3175. }
  3176. break;
  3177. case 'apply_stimulus':
  3178. if (!array_key_exists(0, $aParams))
  3179. {
  3180. throw new Exception('Missing argument #1: stimulus');
  3181. }
  3182. $sStimulus = $aParams[0];
  3183. if (!in_array($sStimulus, MetaModel::EnumStimuli(get_class($this))))
  3184. {
  3185. throw new Exception("Unknown stimulus ".get_class($this)."::".$sStimulus);
  3186. }
  3187. $this->ApplyStimulus($sStimulus);
  3188. break;
  3189. case 'call_method':
  3190. if (!array_key_exists('source', $aSourceObjects))
  3191. {
  3192. throw new Exception('Missing conventional "source" object');
  3193. }
  3194. $oObjectToRead = $aSourceObjects['source'];
  3195. if (!array_key_exists(0, $aParams))
  3196. {
  3197. throw new Exception('Missing argument #1: method name');
  3198. }
  3199. $sMethod = $aParams[0];
  3200. $aCallSpec = array($this, $sMethod);
  3201. if (!is_callable($aCallSpec))
  3202. {
  3203. throw new Exception("Unknown method ".get_class($this)."::".$sMethod.'()');
  3204. }
  3205. // Note: $oObjectToRead has been preserved when adding $aSourceObjects, so as to remain backward compatible with methods having only 1 parameter ($oObjectToRead�
  3206. call_user_func($aCallSpec, $oObjectToRead, $aSourceObjects);
  3207. break;
  3208. default:
  3209. throw new Exception("Invalid verb");
  3210. }
  3211. }
  3212. }