dbobject.class.php 112 KB

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