dbobject.class.php 106 KB

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