dbobject.class.php 105 KB

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