dbobject.class.php 112 KB

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