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. $sFriendlyname = $this->Get('friendlyname');
  149. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey ($sFriendlyname)<br/>\n";
  150. return $sRet;
  151. }
  152. // Restore initial values... mmmm, to be discussed
  153. public function DBRevert()
  154. {
  155. $this->Reload();
  156. }
  157. protected function IsFullyLoaded()
  158. {
  159. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  160. {
  161. if (!$oAttDef->LoadInObject()) continue;
  162. if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
  163. {
  164. return false;
  165. }
  166. }
  167. return true;
  168. }
  169. /**
  170. * @param bool $bAllowAllData DEPRECATED: the reload must never fail!
  171. * @throws CoreException
  172. */
  173. public function Reload($bAllowAllData = false)
  174. {
  175. assert($this->m_bIsInDB);
  176. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false /* must be found */, true /* AllowAllData */);
  177. if (empty($aRow))
  178. {
  179. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  180. }
  181. $this->FromRow($aRow);
  182. // Process linked set attributes
  183. //
  184. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  185. {
  186. if (!$oAttDef->IsLinkSet()) continue;
  187. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue($this);
  188. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  189. $this->m_aLoadedAtt[$sAttCode] = true;
  190. }
  191. $this->m_bFullyLoaded = true;
  192. $this->m_aTouchedAtt = array();
  193. $this->m_aModifiedAtt = array();
  194. }
  195. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  196. {
  197. if (strlen($sClassAlias) == 0)
  198. {
  199. // Default to the current class
  200. $sClassAlias = get_class($this);
  201. }
  202. $this->m_iKey = null;
  203. $this->m_bIsInDB = true;
  204. $this->m_aCurrValues = array();
  205. $this->m_aOrigValues = array();
  206. $this->m_aLoadedAtt = array();
  207. $this->m_bCheckStatus = true;
  208. // Get the key
  209. //
  210. $sKeyField = $sClassAlias."id";
  211. if (!array_key_exists($sKeyField, $aRow))
  212. {
  213. // #@# Bug ?
  214. throw new CoreException("Missing key for class '".get_class($this)."'");
  215. }
  216. $iPKey = $aRow[$sKeyField];
  217. if (!self::IsValidPKey($iPKey))
  218. {
  219. if (is_null($iPKey))
  220. {
  221. throw new CoreException("Missing object id in query result (found null)");
  222. }
  223. else
  224. {
  225. throw new CoreException("An object id must be an integer value ($iPKey)");
  226. }
  227. }
  228. $this->m_iKey = $iPKey;
  229. // Build the object from an array of "attCode"=>"value")
  230. //
  231. $bFullyLoaded = true; // ... set to false if any attribute is not found
  232. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  233. {
  234. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  235. }
  236. else
  237. {
  238. $aAttList = $aAttToLoad[$sClassAlias];
  239. }
  240. foreach($aAttList as $sAttCode=>$oAttDef)
  241. {
  242. // Skip links (could not be loaded by the mean of this query)
  243. if ($oAttDef->IsLinkSet()) continue;
  244. if (!$oAttDef->LoadInObject()) continue;
  245. unset($value);
  246. $bIsDefined = false;
  247. if ($oAttDef->LoadFromDB())
  248. {
  249. // Note: we assume that, for a given attribute, if it can be loaded,
  250. // then one column will be found with an empty suffix, the others have a suffix
  251. // Take care: the function isset will return false in case the value is null,
  252. // which is something that could happen on open joins
  253. $sAttRef = $sClassAlias.$sAttCode;
  254. if (array_key_exists($sAttRef, $aRow))
  255. {
  256. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  257. $bIsDefined = true;
  258. }
  259. }
  260. else
  261. {
  262. $value = $oAttDef->ReadValue($this);
  263. $bIsDefined = true;
  264. }
  265. if ($bIsDefined)
  266. {
  267. $this->m_aCurrValues[$sAttCode] = $value;
  268. if (is_object($value))
  269. {
  270. $this->m_aOrigValues[$sAttCode] = clone $value;
  271. }
  272. else
  273. {
  274. $this->m_aOrigValues[$sAttCode] = $value;
  275. }
  276. $this->m_aLoadedAtt[$sAttCode] = true;
  277. }
  278. else
  279. {
  280. // This attribute was expected and not found in the query columns
  281. $bFullyLoaded = false;
  282. }
  283. }
  284. // Load extended data
  285. if ($aExtendedDataSpec != null)
  286. {
  287. $aExtendedDataSpec['table'];
  288. foreach($aExtendedDataSpec['fields'] as $sColumn)
  289. {
  290. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  291. if (array_key_exists($sColRef, $aRow))
  292. {
  293. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  294. }
  295. }
  296. }
  297. return $bFullyLoaded;
  298. }
  299. protected function _Set($sAttCode, $value)
  300. {
  301. $this->m_aCurrValues[$sAttCode] = $value;
  302. $this->m_aTouchedAtt[$sAttCode] = true;
  303. unset($this->m_aModifiedAtt[$sAttCode]);
  304. }
  305. public function Set($sAttCode, $value)
  306. {
  307. if ($sAttCode == 'finalclass')
  308. {
  309. // Ignore it - this attribute is set upon object creation and that's it
  310. return false;
  311. }
  312. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  313. if (!$oAttDef->IsWritable())
  314. {
  315. $sClass = get_class($this);
  316. throw new Exception("Attempting to set the value on the read-only attribute $sClass::$sAttCode");
  317. }
  318. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  319. {
  320. // First time Set is called... ensure that the object gets fully loaded
  321. // Otherwise we would lose the values on a further Reload
  322. // + consistency does not make sense !
  323. $this->Reload();
  324. }
  325. if ($oAttDef->IsExternalKey())
  326. {
  327. if (is_object($value))
  328. {
  329. // Setting an external key with a whole object (instead of just an ID)
  330. // let's initialize also the external fields that depend on it
  331. // (useful when building objects in memory and not from a query)
  332. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  333. {
  334. 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");
  335. }
  336. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  337. {
  338. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  339. {
  340. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  341. $this->m_aLoadedAtt[$sCode] = true;
  342. }
  343. }
  344. }
  345. else if ($this->m_aCurrValues[$sAttCode] != $value)
  346. {
  347. // Setting an external key, but no any other information is available...
  348. // Invalidate the corresponding fields so that they get reloaded in case they are needed (See Get())
  349. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  350. {
  351. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  352. {
  353. $this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode);
  354. unset($this->m_aLoadedAtt[$sCode]);
  355. }
  356. }
  357. }
  358. }
  359. if ($oAttDef->IsLinkSet() && ($value != null))
  360. {
  361. $realvalue = clone $this->m_aCurrValues[$sAttCode];
  362. $realvalue->UpdateFromCompleteList($value);
  363. }
  364. else
  365. {
  366. $realvalue = $oAttDef->MakeRealValue($value, $this);
  367. }
  368. $this->_Set($sAttCode, $realvalue);
  369. foreach (MetaModel::ListMetaAttributes(get_class($this), $sAttCode) as $sMetaAttCode => $oMetaAttDef)
  370. {
  371. $this->_Set($sMetaAttCode, $oMetaAttDef->MapValue($this));
  372. }
  373. // The object has changed, reset caches
  374. $this->m_bCheckStatus = null;
  375. // Make sure we do not reload it anymore... before saving it
  376. $this->RegisterAsDirty();
  377. // This function is eligible as a lifecycle action: returning true upon success is a must
  378. return true;
  379. }
  380. public function SetTrim($sAttCode, $sValue)
  381. {
  382. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  383. $iMaxSize = $oAttDef->GetMaxSize();
  384. if ($iMaxSize && (strlen($sValue) > $iMaxSize))
  385. {
  386. $sValue = substr($sValue, 0, $iMaxSize);
  387. }
  388. $this->Set($sAttCode, $sValue);
  389. }
  390. public function GetLabel($sAttCode)
  391. {
  392. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  393. return $oAttDef->GetLabel();
  394. }
  395. public function Get($sAttCode)
  396. {
  397. if (($iPos = strpos($sAttCode, '->')) === false)
  398. {
  399. return $this->GetStrict($sAttCode);
  400. }
  401. else
  402. {
  403. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  404. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  405. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  406. {
  407. throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
  408. }
  409. $oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode);
  410. if (!is_null($oExtFieldAtt))
  411. {
  412. return $this->GetStrict($oExtFieldAtt->GetCode());
  413. }
  414. else
  415. {
  416. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  417. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  418. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  419. if (is_null($oRemoteObj))
  420. {
  421. return '';
  422. }
  423. else
  424. {
  425. return $oRemoteObj->Get($sRemoteAttCode);
  426. }
  427. }
  428. }
  429. }
  430. public function GetStrict($sAttCode)
  431. {
  432. if ($sAttCode == 'id')
  433. {
  434. return $this->m_iKey;
  435. }
  436. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  437. if (!$oAttDef->LoadInObject())
  438. {
  439. $value = $oAttDef->GetValue($this);
  440. }
  441. else
  442. {
  443. if (isset($this->m_aLoadedAtt[$sAttCode]))
  444. {
  445. // Standard case... we have the information directly
  446. }
  447. elseif ($this->m_bIsInDB && !$this->m_bDirty)
  448. {
  449. // Lazy load (polymorphism): complete by reloading the entire object
  450. // #@# non-scalar attributes.... handle that differently?
  451. $oKPI = new ExecutionKPI();
  452. $this->Reload();
  453. $oKPI->ComputeStats('Reload', get_class($this).'/'.$sAttCode);
  454. }
  455. elseif ($sAttCode == 'friendlyname')
  456. {
  457. // The friendly name is not computed and the object is dirty
  458. // Todo: implement the computation of the friendly name based on sprintf()
  459. //
  460. $this->m_aCurrValues[$sAttCode] = '';
  461. }
  462. else
  463. {
  464. // Not loaded... is it related to an external key?
  465. if ($oAttDef->IsExternalField())
  466. {
  467. // Let's get the object and compute all of the corresponding attributes
  468. // (i.e not only the requested attribute)
  469. //
  470. $sExtKeyAttCode = $oAttDef->GetKeyAttCode();
  471. if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
  472. {
  473. $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  474. // Note: "allow all data" must be enabled because the external fields are always visible
  475. // to the current user even if this is not the case for the remote object
  476. // This is consistent with the behavior of the lists
  477. $oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
  478. }
  479. else
  480. {
  481. $oRemote = null;
  482. }
  483. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  484. {
  485. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sExtKeyAttCode))
  486. {
  487. if ($oRemote)
  488. {
  489. $this->m_aCurrValues[$sCode] = $oRemote->Get($oDef->GetExtAttCode());
  490. }
  491. else
  492. {
  493. $this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode);
  494. }
  495. $this->m_aLoadedAtt[$sCode] = true;
  496. }
  497. }
  498. }
  499. }
  500. $value = $this->m_aCurrValues[$sAttCode];
  501. }
  502. if ($value instanceof ormLinkSet)
  503. {
  504. $value->Rewind();
  505. }
  506. return $value;
  507. }
  508. public function GetOriginal($sAttCode)
  509. {
  510. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  511. {
  512. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  513. }
  514. return $this->m_aOrigValues[$sAttCode];
  515. }
  516. /**
  517. * Returns the default value of the $sAttCode. By default, returns the default value of the AttributeDefinition.
  518. * Overridable.
  519. *
  520. * @param $sAttCode
  521. * @return mixed
  522. */
  523. public function GetDefaultValue($sAttCode)
  524. {
  525. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  526. return $oAttDef->GetDefaultValue($this);
  527. }
  528. /**
  529. * Returns data loaded by the mean of a dynamic and explicit JOIN
  530. */
  531. public function GetExtendedData()
  532. {
  533. return $this->m_aExtendedData;
  534. }
  535. /**
  536. * Set the HighlightCode if the given code has a greater rank than the current HilightCode
  537. * @param string $sCode
  538. * @return void
  539. */
  540. protected function SetHighlightCode($sCode)
  541. {
  542. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  543. $fCurrentRank = 0.0;
  544. if (($this->m_sHighlightCode !== null) && array_key_exists($this->m_sHighlightCode, $aHighlightScale))
  545. {
  546. $fCurrentRank = $aHighlightScale[$this->m_sHighlightCode]['rank'];
  547. }
  548. if (array_key_exists($sCode, $aHighlightScale))
  549. {
  550. $fRank = $aHighlightScale[$sCode]['rank'];
  551. if ($fRank > $fCurrentRank)
  552. {
  553. $this->m_sHighlightCode = $sCode;
  554. }
  555. }
  556. }
  557. /**
  558. * Get the current HighlightCode
  559. * @return string The Hightlight code (null if none set, meaning rank = 0)
  560. */
  561. protected function GetHighlightCode()
  562. {
  563. return $this->m_sHighlightCode;
  564. }
  565. protected function ComputeHighlightCode()
  566. {
  567. // First if the state defines a HiglightCode, apply it
  568. $sState = $this->GetState();
  569. if ($sState != '')
  570. {
  571. $sCode = MetaModel::GetHighlightCode(get_class($this), $sState);
  572. $this->SetHighlightCode($sCode);
  573. }
  574. // The check for each StopWatch if a HighlightCode is effective
  575. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  576. {
  577. if ($oAttDef instanceof AttributeStopWatch)
  578. {
  579. $oStopWatch = $this->Get($sAttCode);
  580. $sCode = $oStopWatch->GetHighlightCode();
  581. if ($sCode !== '')
  582. {
  583. $this->SetHighlightCode($sCode);
  584. }
  585. }
  586. }
  587. return $this->GetHighlightCode();
  588. }
  589. /**
  590. * Updates the value of an external field by (re)loading the object
  591. * corresponding to the external key and getting the value from it
  592. *
  593. * UNUSED ?
  594. *
  595. * @param string $sAttCode Attribute code of the external field to update
  596. * @return void
  597. */
  598. protected function UpdateExternalField($sAttCode)
  599. {
  600. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  601. if ($oAttDef->IsExternalField())
  602. {
  603. $sTargetClass = $oAttDef->GetTargetClass();
  604. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  605. // Note: "allow all data" must be enabled because the external fields are always visible
  606. // to the current user even if this is not the case for the remote object
  607. // This is consistent with the behavior of the lists
  608. $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
  609. if (is_object($oObj))
  610. {
  611. $value = $oObj->Get($oAttDef->GetExtAttCode());
  612. $this->Set($sAttCode, $value);
  613. }
  614. }
  615. }
  616. public function ComputeValues()
  617. {
  618. }
  619. // Compute scalar attributes that depend on any other type of attribute
  620. final public function DoComputeValues()
  621. {
  622. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  623. // First check that we are not currently computing the fields
  624. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  625. foreach (debug_backtrace() as $aCallInfo)
  626. {
  627. if (!array_key_exists("class", $aCallInfo)) continue;
  628. if ($aCallInfo["class"] != get_class($this)) continue;
  629. if ($aCallInfo["function"] != "ComputeValues") continue;
  630. return; //skip!
  631. }
  632. // Set the "null-not-allowed" datetimes (and dates) whose value is not initialized
  633. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  634. {
  635. // AttributeDate is derived from AttributeDateTime
  636. if (($oAttDef instanceof AttributeDateTime) && (!$oAttDef->IsNullAllowed()) && ($this->Get($sAttCode) == $oAttDef->GetNullValue()))
  637. {
  638. $this->Set($sAttCode, date($oAttDef->GetInternalFormat()));
  639. }
  640. }
  641. $this->ComputeValues();
  642. }
  643. public function GetAsHTML($sAttCode, $bLocalize = true)
  644. {
  645. $sClass = get_class($this);
  646. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  647. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  648. {
  649. //return $this->Get($sAttCode.'_friendlyname');
  650. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  651. $iTargetKey = $this->Get($sAttCode);
  652. if ($iTargetKey < 0)
  653. {
  654. // the key points to an object that exists only in memory... no hyperlink points to it yet
  655. return '';
  656. }
  657. else
  658. {
  659. $sHtmlLabel = htmlentities($this->Get($sAttCode.'_friendlyname'), ENT_QUOTES, 'UTF-8');
  660. $bArchived = $this->IsArchived($sAttCode);
  661. $bObsolete = $this->IsObsolete($sAttCode);
  662. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sHtmlLabel, null, true, $bArchived, $bObsolete);
  663. }
  664. }
  665. // That's a standard attribute (might be an ext field or a direct field, etc.)
  666. return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
  667. }
  668. public function GetEditValue($sAttCode)
  669. {
  670. $sClass = get_class($this);
  671. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  672. if ($oAtt->IsExternalKey())
  673. {
  674. $sTargetClass = $oAtt->GetTargetClass();
  675. if ($this->IsNew())
  676. {
  677. // The current object exists only in memory, don't try to query it in the DB !
  678. // instead let's query for the object pointed by the external key, and get its name
  679. $targetObjId = $this->Get($sAttCode);
  680. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  681. if (is_object($oTargetObj))
  682. {
  683. $sEditValue = $oTargetObj->GetName();
  684. }
  685. else
  686. {
  687. $sEditValue = 0;
  688. }
  689. }
  690. else
  691. {
  692. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  693. }
  694. }
  695. else
  696. {
  697. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
  698. }
  699. return $sEditValue;
  700. }
  701. public function GetAsXML($sAttCode, $bLocalize = true)
  702. {
  703. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  704. return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
  705. }
  706. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false)
  707. {
  708. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  709. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText);
  710. }
  711. public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
  712. {
  713. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  714. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
  715. }
  716. public function GetOriginalAsXML($sAttCode, $bLocalize = true)
  717. {
  718. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  719. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
  720. }
  721. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false)
  722. {
  723. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  724. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText);
  725. }
  726. /**
  727. * @param $sObjClass
  728. * @param $sObjKey
  729. * @param string $sHtmlLabel Label with HTML entities escaped (< escaped as &lt;)
  730. * @param null $sUrlMakerClass
  731. * @param bool|true $bWithNavigationContext
  732. * @param bool|false $bArchived
  733. * @param bool|false $bObsolete
  734. * @return string
  735. * @throws DictExceptionMissingString
  736. */
  737. public static function MakeHyperLink($sObjClass, $sObjKey, $sHtmlLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true, $bArchived = false, $bObsolete = false)
  738. {
  739. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  740. // Safety net
  741. //
  742. if (empty($sHtmlLabel))
  743. {
  744. // If the object if not issued from a query but constructed programmatically
  745. // the label may be empty. In this case run a query to get the object's friendly name
  746. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
  747. if (is_object($oTmpObj))
  748. {
  749. $sHtmlLabel = $oTmpObj->GetName();
  750. }
  751. else
  752. {
  753. // May happen in case the target object is not in the list of allowed values for this attribute
  754. $sHtmlLabel = "<em>$sObjClass::$sObjKey</em>";
  755. }
  756. }
  757. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  758. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  759. $bClickable = !$bArchived || utils::IsArchiveMode();
  760. if ($bArchived)
  761. {
  762. $sSpanClass = 'archived';
  763. $sFA = 'fa-archive object-archived';
  764. $sHint = Dict::S('ObjectRef:Archived');
  765. }
  766. elseif ($bObsolete)
  767. {
  768. $sSpanClass = 'obsolete';
  769. $sFA = 'fa-eye-slash object-obsolete';
  770. $sHint = Dict::S('ObjectRef:Obsolete');
  771. }
  772. else
  773. {
  774. $sSpanClass = '';
  775. $sFA = '';
  776. }
  777. if ($sFA == '')
  778. {
  779. $sIcon = '';
  780. }
  781. else
  782. {
  783. if ($bClickable)
  784. {
  785. $sIcon = "<span class=\"object-ref-icon fa $sFA fa-1x fa-fw\"></span>";
  786. }
  787. else
  788. {
  789. $sIcon = "<span class=\"object-ref-icon-disabled fa $sFA fa-1x fa-fw\"></span>";
  790. }
  791. }
  792. if ($bClickable && (strlen($sUrl) > 0))
  793. {
  794. $sHLink = "<a class=\"object-ref-link\" href=\"$sUrl\">$sIcon$sHtmlLabel</a>";
  795. }
  796. else
  797. {
  798. $sHLink = $sIcon.$sHtmlLabel;
  799. }
  800. $sRet = "<span class=\"object-ref $sSpanClass\" title=\"$sHint\">$sHLink</span>";
  801. return $sRet;
  802. }
  803. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  804. {
  805. $bArchived = $this->IsArchived();
  806. $bObsolete = $this->IsObsolete();
  807. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext, $bArchived, $bObsolete);
  808. }
  809. public static function ComputeStandardUIPage($sClass)
  810. {
  811. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  812. if (!isset($aUIPagesCache[$sClass]))
  813. {
  814. $UIPage = false;
  815. if (is_callable("$sClass::GetUIPage"))
  816. {
  817. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  818. }
  819. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  820. }
  821. $sPage = $aUIPagesCache[$sClass];
  822. return $sPage;
  823. }
  824. public static function GetUIPage()
  825. {
  826. return 'UI.php';
  827. }
  828. // could be in the metamodel ?
  829. public static function IsValidPKey($value)
  830. {
  831. return ((string)$value === (string)(int)$value);
  832. }
  833. public function GetKey()
  834. {
  835. return $this->m_iKey;
  836. }
  837. public function SetKey($iNewKey)
  838. {
  839. if (!self::IsValidPKey($iNewKey))
  840. {
  841. throw new CoreException("An object id must be an integer value ($iNewKey)");
  842. }
  843. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  844. {
  845. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  846. }
  847. $this->m_iKey = $iNewKey;
  848. }
  849. /**
  850. * Get the icon representing this object
  851. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  852. * @return string Either the full IMG tag ($bImgTag == true) or just the URL to the icon file
  853. */
  854. public function GetIcon($bImgTag = true)
  855. {
  856. $sCode = $this->ComputeHighlightCode();
  857. if($sCode != '')
  858. {
  859. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  860. if (array_key_exists($sCode, $aHighlightScale))
  861. {
  862. $sIconUrl = $aHighlightScale[$sCode]['icon'];
  863. if($bImgTag)
  864. {
  865. return "<img src=\"$sIconUrl\" style=\"vertical-align:middle\"/>";
  866. }
  867. else
  868. {
  869. return $sIconUrl;
  870. }
  871. }
  872. }
  873. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  874. }
  875. /**
  876. * Gets the name of an object in a safe manner for displaying inside a web page
  877. * @return string
  878. */
  879. public function GetName()
  880. {
  881. return htmlentities($this->GetRawName(), ENT_QUOTES, 'UTF-8');
  882. }
  883. /**
  884. * Gets the raw name of an object, this is not safe for displaying inside a web page
  885. * since the " < > characters are not escaped and the name may contain some XSS script
  886. * instructions.
  887. * Use this function only for internal computations or for an output to a non-HTML destination
  888. * @return string
  889. */
  890. public function GetRawName()
  891. {
  892. return $this->Get('friendlyname');
  893. }
  894. public function GetState()
  895. {
  896. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  897. if (empty($sStateAttCode))
  898. {
  899. return '';
  900. }
  901. else
  902. {
  903. return $this->Get($sStateAttCode);
  904. }
  905. }
  906. public function GetStateLabel()
  907. {
  908. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  909. if (empty($sStateAttCode))
  910. {
  911. return '';
  912. }
  913. else
  914. {
  915. $sStateValue = $this->Get($sStateAttCode);
  916. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  917. }
  918. }
  919. public function GetStateDescription()
  920. {
  921. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  922. if (empty($sStateAttCode))
  923. {
  924. return '';
  925. }
  926. else
  927. {
  928. $sStateValue = $this->Get($sStateAttCode);
  929. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  930. }
  931. }
  932. /**
  933. * Overridable - Define attributes read-only from the end-user perspective
  934. *
  935. * @return array List of attcodes
  936. */
  937. public static function GetReadOnlyAttributes()
  938. {
  939. return null;
  940. }
  941. /**
  942. * Overridable - Get predefined objects (could be hardcoded)
  943. * The predefined objects will be synchronized with the DB at each install/upgrade
  944. * As soon as a class has predefined objects, then nobody can create nor delete objects
  945. * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
  946. */
  947. public static function GetPredefinedObjects()
  948. {
  949. return null;
  950. }
  951. /**
  952. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  953. * for the given attribute in the current state of the object
  954. * @param $sAttCode string $sAttCode The code of the attribute
  955. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  956. * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
  957. * @return integer Flags: the binary combination of the flags applicable to this attribute
  958. */
  959. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  960. {
  961. $iFlags = 0; // By default (if no life cycle) no flag at all
  962. $aReadOnlyAtts = $this->GetReadOnlyAttributes();
  963. if ($aReadOnlyAtts != null)
  964. {
  965. if (in_array($sAttCode, $aReadOnlyAtts))
  966. {
  967. return OPT_ATT_READONLY;
  968. }
  969. }
  970. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  971. if (!empty($sStateAttCode))
  972. {
  973. if ($sTargetState != '')
  974. {
  975. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  976. }
  977. else
  978. {
  979. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  980. }
  981. }
  982. $aReasons = array();
  983. $iSynchroFlags = 0;
  984. if ($this->InSyncScope())
  985. {
  986. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  987. }
  988. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  989. }
  990. /**
  991. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  992. * for the given attribute in a transition
  993. * @param $sAttCode string $sAttCode The code of the attribute
  994. * @param $sStimulus string The stimulus code to apply
  995. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  996. * @param $sOriginState string The state from which to apply $sStimulus, if empty current state will be used
  997. * @return integer Flags: the binary combination of the flags applicable to this attribute
  998. */
  999. public function GetTransitionFlags($sAttCode, $sStimulus, &$aReasons = array(), $sOriginState = '')
  1000. {
  1001. $iFlags = 0; // By default (if no lifecycle) no flag at all
  1002. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1003. // If no state attribute, there is no lifecycle
  1004. if (empty($sStateAttCode))
  1005. {
  1006. return $iFlags;
  1007. }
  1008. // Retrieving current state if necessary
  1009. if ($sOriginState === '')
  1010. {
  1011. $sOriginState = $this->Get($sStateAttCode);
  1012. }
  1013. // Retrieving attribute flags
  1014. $iAttributeFlags = $this->GetAttributeFlags($sAttCode, $aReasons, $sOriginState);
  1015. // Retrieving transition flags
  1016. $iTransitionFlags = MetaModel::GetTransitionFlags(get_class($this), $sOriginState, $sStimulus, $sAttCode);
  1017. // Merging transition flags with attribute flags
  1018. $iFlags = $iTransitionFlags | $iAttributeFlags;
  1019. return $iFlags;
  1020. }
  1021. /**
  1022. * Returns an array of attribute codes (with their flags) when $sStimulus is applied on the object in the $sOriginState state.
  1023. * Note: Attributes (and flags) from the target state and the transition are combined.
  1024. *
  1025. * @param $sStimulus string
  1026. * @param $sOriginState string Default is current state
  1027. * @return array
  1028. */
  1029. public function GetTransitionAttributes($sStimulus, $sOriginState = null)
  1030. {
  1031. $sObjClass = get_class($this);
  1032. // Defining current state as origin state if not specified
  1033. if($sOriginState === null)
  1034. {
  1035. $sOriginState = $this->GetState();
  1036. }
  1037. $aAttributes = MetaModel::GetTransitionAttributes($sObjClass, $sStimulus, $sOriginState);
  1038. return $aAttributes;
  1039. }
  1040. /**
  1041. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  1042. * for the given attribute for the current state of the object considered as an INITIAL state
  1043. * @param string $sAttCode The code of the attribute
  1044. * @return integer Flags: the binary combination of the flags applicable to this attribute
  1045. */
  1046. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  1047. {
  1048. $iFlags = 0;
  1049. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1050. if (!empty($sStateAttCode))
  1051. {
  1052. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  1053. }
  1054. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  1055. }
  1056. // check if the given (or current) value is suitable for the attribute
  1057. // return true if successfull
  1058. // return the error desciption otherwise
  1059. public function CheckValue($sAttCode, $value = null)
  1060. {
  1061. if (!is_null($value))
  1062. {
  1063. $toCheck = $value;
  1064. }
  1065. else
  1066. {
  1067. $toCheck = $this->Get($sAttCode);
  1068. }
  1069. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1070. if (!$oAtt->IsWritable())
  1071. {
  1072. return true;
  1073. }
  1074. elseif ($oAtt->IsNull($toCheck))
  1075. {
  1076. if ($oAtt->IsNullAllowed())
  1077. {
  1078. return true;
  1079. }
  1080. else
  1081. {
  1082. return "Null not allowed";
  1083. }
  1084. }
  1085. elseif ($oAtt->IsExternalKey())
  1086. {
  1087. // Hierachical keys are always tested because an infinite loop can be created.
  1088. if (!MetaModel::SkipCheckExtKeys() || $oAtt->IsHierarchicalKey())
  1089. {
  1090. // Check allowed values
  1091. $aValues = $oAtt->GetAllowedValues(array('this' => $this));
  1092. if (!array_key_exists($toCheck, $aValues))
  1093. {
  1094. // TODO Better error message
  1095. return "Value not allowed [$toCheck]";
  1096. }
  1097. }
  1098. }
  1099. elseif ($oAtt->IsScalar())
  1100. {
  1101. $aValues = $oAtt->GetAllowedValues($this->ToArgsForQuery());
  1102. if (count($aValues) > 0)
  1103. {
  1104. if (!array_key_exists($toCheck, $aValues))
  1105. {
  1106. return "Value not allowed [$toCheck]";
  1107. }
  1108. }
  1109. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  1110. {
  1111. $iLen = strlen($toCheck);
  1112. if ($iLen > $iMaxSize)
  1113. {
  1114. return "String too long (found $iLen, limited to $iMaxSize)";
  1115. }
  1116. }
  1117. if (!$oAtt->CheckFormat($toCheck))
  1118. {
  1119. return "Wrong format [$toCheck]";
  1120. }
  1121. }
  1122. else
  1123. {
  1124. return $oAtt->CheckValue($this, $toCheck);
  1125. }
  1126. return true;
  1127. }
  1128. // check attributes together
  1129. public function CheckConsistency()
  1130. {
  1131. return true;
  1132. }
  1133. // check integrity rules (before inserting or updating the object)
  1134. // a displayable error is returned
  1135. public function DoCheckToWrite()
  1136. {
  1137. $this->DoComputeValues();
  1138. $aChanges = $this->ListChanges();
  1139. foreach($aChanges as $sAttCode => $value)
  1140. {
  1141. $res = $this->CheckValue($sAttCode);
  1142. if ($res !== true)
  1143. {
  1144. // $res contains the error description
  1145. $sAttributeName = Dict::S('Class:'.get_class($this).'/Attribute:'.$sAttCode);
  1146. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttributeName': $res";
  1147. }
  1148. }
  1149. if (count($this->m_aCheckIssues) > 0)
  1150. {
  1151. // No need to check consistency between attributes if any of them has
  1152. // an unexpected value
  1153. return;
  1154. }
  1155. $res = $this->CheckConsistency();
  1156. if ($res !== true)
  1157. {
  1158. // $res contains the error description
  1159. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  1160. }
  1161. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  1162. //
  1163. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  1164. {
  1165. foreach($aChanges as $sAttCode => $value)
  1166. {
  1167. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  1168. if ($iFlags & OPT_ATT_SLAVE)
  1169. {
  1170. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  1171. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1172. $sAttLabel = $oAttDef->GetLabel();
  1173. foreach($aReasons as $aReasonInfo)
  1174. {
  1175. // Todo: associate the attribute code with the error
  1176. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. final public function CheckToWrite()
  1183. {
  1184. if (MetaModel::SkipCheckToWrite())
  1185. {
  1186. return array(true, array());
  1187. }
  1188. if (is_null($this->m_bCheckStatus))
  1189. {
  1190. $this->m_aCheckIssues = array();
  1191. $oKPI = new ExecutionKPI();
  1192. $this->DoCheckToWrite();
  1193. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  1194. if (count($this->m_aCheckIssues) == 0)
  1195. {
  1196. $this->m_bCheckStatus = true;
  1197. }
  1198. else
  1199. {
  1200. $this->m_bCheckStatus = false;
  1201. }
  1202. }
  1203. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  1204. }
  1205. // check if it is allowed to delete the existing object from the database
  1206. // a displayable error is returned
  1207. protected function DoCheckToDelete(&$oDeletionPlan)
  1208. {
  1209. $this->m_aDeleteIssues = array(); // Ok
  1210. if ($this->InSyncScope())
  1211. {
  1212. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  1213. {
  1214. foreach ($aSourceData['replica'] as $oReplica)
  1215. {
  1216. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  1217. }
  1218. $oDataSource = $aSourceData['source'];
  1219. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  1220. {
  1221. // The current task has the right to delete the object
  1222. continue;
  1223. }
  1224. $oReplica = reset($aSourceData['replica']); // Take the first one
  1225. if ($oReplica->Get('status_dest_creator') != 1)
  1226. {
  1227. // The object is not owned by the task
  1228. continue;
  1229. }
  1230. $sLink = $oDataSource->GetName();
  1231. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  1232. switch($sUserDeletePolicy)
  1233. {
  1234. case 'nobody':
  1235. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1236. break;
  1237. case 'administrators':
  1238. if (!UserRights::IsAdministrator())
  1239. {
  1240. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1241. }
  1242. break;
  1243. case 'everybody':
  1244. default:
  1245. // Ok
  1246. break;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. public function CheckToDelete(&$oDeletionPlan)
  1252. {
  1253. $this->MakeDeletionPlan($oDeletionPlan);
  1254. $oDeletionPlan->ComputeResults();
  1255. return (!$oDeletionPlan->FoundStopper());
  1256. }
  1257. protected function ListChangedValues(array $aProposal)
  1258. {
  1259. $aDelta = array();
  1260. foreach ($aProposal as $sAtt => $proposedValue)
  1261. {
  1262. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1263. {
  1264. // The value was not set
  1265. $aDelta[$sAtt] = $proposedValue;
  1266. }
  1267. elseif(!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false))
  1268. {
  1269. // This attCode was never set, cannot be modified
  1270. // or the same value - as the original value - was set, and has been verified as equivalent to the original value
  1271. continue;
  1272. }
  1273. else if (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true)
  1274. {
  1275. // We already know that the value is really modified
  1276. $aDelta[$sAtt] = $proposedValue;
  1277. }
  1278. elseif(is_object($proposedValue))
  1279. {
  1280. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1281. // The value is an object, the comparison is not strict
  1282. if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue))
  1283. {
  1284. $aDelta[$sAtt] = $proposedValue;
  1285. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1286. }
  1287. else
  1288. {
  1289. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1290. }
  1291. }
  1292. else
  1293. {
  1294. // The value is a scalar, the comparison must be 100% strict
  1295. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1296. {
  1297. //echo "$sAtt:<pre>\n";
  1298. //var_dump($this->m_aOrigValues[$sAtt]);
  1299. //var_dump($proposedValue);
  1300. //echo "</pre>\n";
  1301. $aDelta[$sAtt] = $proposedValue;
  1302. $this->m_aModifiedAtt[$sAtt] = true; // Really modified
  1303. }
  1304. else
  1305. {
  1306. $this->m_aModifiedAtt[$sAtt] = false; // Not really modified
  1307. }
  1308. }
  1309. }
  1310. return $aDelta;
  1311. }
  1312. // List the attributes that have been changed
  1313. // Returns an array of attname => currentvalue
  1314. public function ListChanges()
  1315. {
  1316. if ($this->m_bIsInDB)
  1317. {
  1318. return $this->ListChangedValues($this->m_aCurrValues);
  1319. }
  1320. else
  1321. {
  1322. return $this->m_aCurrValues;
  1323. }
  1324. }
  1325. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1326. public function IsModified()
  1327. {
  1328. $aChanges = $this->ListChanges();
  1329. return (count($aChanges) != 0);
  1330. }
  1331. public function Equals($oSibling)
  1332. {
  1333. if (get_class($oSibling) != get_class($this))
  1334. {
  1335. return false;
  1336. }
  1337. if ($this->GetKey() != $oSibling->GetKey())
  1338. {
  1339. return false;
  1340. }
  1341. if ($this->m_bIsInDB)
  1342. {
  1343. // If one has changed, then consider them as being different
  1344. if ($this->IsModified() || $oSibling->IsModified())
  1345. {
  1346. return false;
  1347. }
  1348. }
  1349. else
  1350. {
  1351. // Todo - implement this case (loop on every attribute)
  1352. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1353. //{
  1354. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1355. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1356. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1357. //{
  1358. //return false;
  1359. //}
  1360. //}
  1361. return false;
  1362. }
  1363. return true;
  1364. }
  1365. // used only by insert
  1366. protected function OnObjectKeyReady()
  1367. {
  1368. // Meant to be overloaded
  1369. }
  1370. // used both by insert/update
  1371. private function DBWriteLinks()
  1372. {
  1373. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1374. {
  1375. if (!$oAttDef->IsLinkSet()) continue;
  1376. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1377. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1378. $oLinkSet = $this->m_aCurrValues[$sAttCode];
  1379. $oLinkSet->DBWrite($this);
  1380. }
  1381. }
  1382. // used both by insert/update
  1383. private function WriteExternalAttributes()
  1384. {
  1385. foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1386. {
  1387. if (!$oAttDef->LoadInObject()) continue;
  1388. if ($oAttDef->LoadFromDB()) continue;
  1389. if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
  1390. if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
  1391. $oAttDef->WriteValue($this, $this->m_aCurrValues[$sAttCode]);
  1392. }
  1393. }
  1394. // Note: this is experimental - it was designed to speed up the setup of iTop
  1395. // Known limitations:
  1396. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1397. // - the id of the object is not updated
  1398. static public final function BulkInsertStart()
  1399. {
  1400. self::$m_bBulkInsert = true;
  1401. }
  1402. static public final function BulkInsertFlush()
  1403. {
  1404. if (!self::$m_bBulkInsert) return;
  1405. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1406. {
  1407. foreach ($aTables as $sTable => $sColumns)
  1408. {
  1409. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1410. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1411. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1412. }
  1413. }
  1414. // Reset
  1415. self::$m_aBulkInsertItems = array();
  1416. self::$m_aBulkInsertCols = array();
  1417. self::$m_bBulkInsert = false;
  1418. }
  1419. private function DBInsertSingleTable($sTableClass)
  1420. {
  1421. $sTable = MetaModel::DBGetTable($sTableClass);
  1422. // Abstract classes or classes having no specific attribute do not have an associated table
  1423. if ($sTable == '') return;
  1424. $sClass = get_class($this);
  1425. // fields in first array, values in the second
  1426. $aFieldsToWrite = array();
  1427. $aValuesToWrite = array();
  1428. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1429. {
  1430. // Add it to the list of fields to write
  1431. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1432. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1433. }
  1434. $aHierarchicalKeys = array();
  1435. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1436. {
  1437. // Skip this attribute if not defined in this table
  1438. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1439. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1440. foreach($aAttColumns as $sColumn => $sValue)
  1441. {
  1442. $aFieldsToWrite[] = "`$sColumn`";
  1443. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1444. }
  1445. if ($oAttDef->IsHierarchicalKey())
  1446. {
  1447. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1448. }
  1449. }
  1450. if (count($aValuesToWrite) == 0) return false;
  1451. if (MetaModel::DBIsReadOnly())
  1452. {
  1453. $iNewKey = -1;
  1454. }
  1455. else
  1456. {
  1457. if (self::$m_bBulkInsert)
  1458. {
  1459. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1460. {
  1461. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1462. }
  1463. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1464. $iNewKey = 999999; // TODO - compute next id....
  1465. }
  1466. else
  1467. {
  1468. if (count($aHierarchicalKeys) > 0)
  1469. {
  1470. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1471. {
  1472. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1473. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1474. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1475. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1476. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1477. }
  1478. }
  1479. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1480. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1481. }
  1482. }
  1483. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1484. if (empty($this->m_iKey))
  1485. {
  1486. // Take the autonumber
  1487. $this->m_iKey = $iNewKey;
  1488. }
  1489. return $this->m_iKey;
  1490. }
  1491. // Insert of record for the new object into the database
  1492. // Returns the key of the newly created object
  1493. public function DBInsertNoReload()
  1494. {
  1495. if ($this->m_bIsInDB)
  1496. {
  1497. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1498. }
  1499. $sClass = get_class($this);
  1500. $sRootClass = MetaModel::GetRootClass($sClass);
  1501. // Ensure the update of the values (we are accessing the data directly)
  1502. $this->DoComputeValues();
  1503. $this->OnInsert();
  1504. if ($this->m_iKey < 0)
  1505. {
  1506. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1507. $this->m_iKey = null;
  1508. }
  1509. // If not automatically computed, then check that the key is given by the caller
  1510. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1511. {
  1512. if (empty($this->m_iKey))
  1513. {
  1514. 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));
  1515. }
  1516. }
  1517. // Ultimate check - ensure DB integrity
  1518. list($bRes, $aIssues) = $this->CheckToWrite();
  1519. if (!$bRes)
  1520. {
  1521. $sIssues = implode(', ', $aIssues);
  1522. $sClassName = Dict::S('Class:'.get_class($this));
  1523. throw new CoreException("Object not following integrity rules", array('<br>issues' => $sIssues, '<br>class' => $sClassName, '<br>id' => $this->GetKey()));
  1524. }
  1525. // Stop watches
  1526. $sState = $this->GetState();
  1527. if ($sState != '')
  1528. {
  1529. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1530. {
  1531. if ($oAttDef instanceof AttributeStopWatch)
  1532. {
  1533. if (in_array($sState, $oAttDef->GetStates()))
  1534. {
  1535. // Start the stop watch and compute the deadlines
  1536. $oSW = $this->Get($sAttCode);
  1537. $oSW->Start($this, $oAttDef);
  1538. $oSW->ComputeDeadlines($this, $oAttDef);
  1539. $this->Set($sAttCode, $oSW);
  1540. }
  1541. }
  1542. }
  1543. }
  1544. // First query built upon on the root class, because the ID must be created first
  1545. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1546. // Then do the leaf class, if different from the root class
  1547. if ($sClass != $sRootClass)
  1548. {
  1549. $this->DBInsertSingleTable($sClass);
  1550. }
  1551. // Then do the other classes
  1552. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1553. {
  1554. if ($sParentClass == $sRootClass) continue;
  1555. $this->DBInsertSingleTable($sParentClass);
  1556. }
  1557. $this->OnObjectKeyReady();
  1558. $this->DBWriteLinks();
  1559. $this->WriteExternalAttributes();
  1560. $this->m_bIsInDB = true;
  1561. $this->m_bDirty = false;
  1562. foreach ($this->m_aCurrValues as $sAttCode => $value)
  1563. {
  1564. if (is_object($value))
  1565. {
  1566. $value = clone $value;
  1567. }
  1568. $this->m_aOrigValues[$sAttCode] = $value;
  1569. }
  1570. $this->AfterInsert();
  1571. // Activate any existing trigger
  1572. $sClass = get_class($this);
  1573. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1574. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1575. while ($oTrigger = $oSet->Fetch())
  1576. {
  1577. $oTrigger->DoActivate($this->ToArgs('this'));
  1578. }
  1579. // Callbacks registered with RegisterCallback
  1580. if (isset($this->m_aCallbacks[self::CALLBACK_AFTERINSERT]))
  1581. {
  1582. foreach ($this->m_aCallbacks[self::CALLBACK_AFTERINSERT] as $aCallBackData)
  1583. {
  1584. call_user_func_array($aCallBackData['callback'], $aCallBackData['params']);
  1585. }
  1586. }
  1587. $this->RecordObjCreation();
  1588. return $this->m_iKey;
  1589. }
  1590. protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
  1591. {
  1592. $sTable = MetaModel::DBGetTable($sTableClass);
  1593. // Abstract classes or classes having no specific attribute do not have an associated table
  1594. if ($sTable == '') return;
  1595. $sClass = get_class($this);
  1596. // fields in first array, values in the second
  1597. $aFieldsToWrite = array();
  1598. $aValuesToWrite = array();
  1599. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1600. {
  1601. // Add it to the list of fields to write
  1602. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1603. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1604. }
  1605. $aHierarchicalKeys = array();
  1606. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1607. {
  1608. // Skip this attribute if not defined in this table
  1609. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1610. // Skip link set that can still be undefined though the object is 100% loaded
  1611. if ($oAttDef->IsLinkSet()) continue;
  1612. $value = $this->m_aCurrValues[$sAttCode];
  1613. if ($oAttDef->IsExternalKey())
  1614. {
  1615. $sTargetClass = $oAttDef->GetTargetClass();
  1616. if (is_array($aAuthorizedExtKeys))
  1617. {
  1618. if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
  1619. {
  1620. $value = 0;
  1621. }
  1622. }
  1623. }
  1624. $aAttColumns = $oAttDef->GetSQLValues($value);
  1625. foreach($aAttColumns as $sColumn => $sValue)
  1626. {
  1627. $aFieldsToWrite[] = "`$sColumn`";
  1628. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1629. }
  1630. if ($oAttDef->IsHierarchicalKey())
  1631. {
  1632. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1633. }
  1634. }
  1635. if (count($aValuesToWrite) == 0) return false;
  1636. if (count($aHierarchicalKeys) > 0)
  1637. {
  1638. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1639. {
  1640. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1641. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1642. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1643. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1644. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1645. }
  1646. }
  1647. $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
  1648. }
  1649. public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
  1650. {
  1651. $sClass = get_class($this);
  1652. $sRootClass = MetaModel::GetRootClass($sClass);
  1653. // First query built upon on the root class, because the ID must be created first
  1654. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
  1655. // Then do the leaf class, if different from the root class
  1656. if ($sClass != $sRootClass)
  1657. {
  1658. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
  1659. }
  1660. // Then do the other classes
  1661. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1662. {
  1663. if ($sParentClass == $sRootClass) continue;
  1664. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
  1665. }
  1666. }
  1667. public function DBInsert()
  1668. {
  1669. $this->DBInsertNoReload();
  1670. $this->Reload();
  1671. return $this->m_iKey;
  1672. }
  1673. public function DBInsertTracked(CMDBChange $oChange)
  1674. {
  1675. CMDBObject::SetCurrentChange($oChange);
  1676. return $this->DBInsert();
  1677. }
  1678. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1679. {
  1680. CMDBObject::SetCurrentChange($oChange);
  1681. return $this->DBInsertNoReload();
  1682. }
  1683. // Creates a copy of the current object into the database
  1684. // Returns the id of the newly created object
  1685. public function DBClone($iNewKey = null)
  1686. {
  1687. $this->m_bIsInDB = false;
  1688. $this->m_iKey = $iNewKey;
  1689. $ret = $this->DBInsert();
  1690. $this->RecordObjCreation();
  1691. return $ret;
  1692. }
  1693. /**
  1694. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1695. * The purpose of this method is to reset the appropriate attributes of the object in
  1696. * order to make sure that the newly cloned object is really distinct from its clone
  1697. */
  1698. public function __clone()
  1699. {
  1700. $this->m_bIsInDB = false;
  1701. $this->m_bDirty = true;
  1702. $this->m_iKey = self::GetNextTempId(get_class($this));
  1703. }
  1704. // Update a record
  1705. public function DBUpdate()
  1706. {
  1707. if (!$this->m_bIsInDB)
  1708. {
  1709. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1710. }
  1711. // Protect against reentrance (e.g. cascading the update of ticket logs)
  1712. static $aUpdateReentrance = array();
  1713. $sKey = get_class($this).'::'.$this->GetKey();
  1714. if (array_key_exists($sKey, $aUpdateReentrance))
  1715. {
  1716. return;
  1717. }
  1718. $aUpdateReentrance[$sKey] = true;
  1719. try
  1720. {
  1721. // Stop watches
  1722. $sState = $this->GetState();
  1723. if ($sState != '')
  1724. {
  1725. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1726. {
  1727. if ($oAttDef instanceof AttributeStopWatch)
  1728. {
  1729. if (in_array($sState, $oAttDef->GetStates()))
  1730. {
  1731. // Compute or recompute the deadlines
  1732. $oSW = $this->Get($sAttCode);
  1733. $oSW->ComputeDeadlines($this, $oAttDef);
  1734. $this->Set($sAttCode, $oSW);
  1735. }
  1736. }
  1737. }
  1738. }
  1739. $this->DoComputeValues();
  1740. $this->OnUpdate();
  1741. $aChanges = $this->ListChanges();
  1742. if (count($aChanges) == 0)
  1743. {
  1744. // Attempting to update an unchanged object
  1745. unset($aUpdateReentrance[$sKey]);
  1746. return $this->m_iKey;
  1747. }
  1748. // Ultimate check - ensure DB integrity
  1749. list($bRes, $aIssues) = $this->CheckToWrite();
  1750. if (!$bRes)
  1751. {
  1752. $sIssues = implode(', ', $aIssues);
  1753. $sClassName = Dict::S('Class:'.get_class($this));
  1754. throw new CoreException("Object not following integrity rules", array('<br>issues' => $sIssues, '<br>class' => $sClassName, '<br>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. }