dbobject.class.php 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334
  1. <?php
  2. // Copyright (C) 2010-2012 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. * Class dbObject: the root of persistent classes
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('metamodel.class.php');
  25. require_once('deletionplan.class.inc.php');
  26. /**
  27. * A persistent object, as defined by the metamodel
  28. *
  29. * @package iTopORM
  30. */
  31. abstract class DBObject
  32. {
  33. private static $m_aMemoryObjectsByClass = array();
  34. private static $m_aBulkInsertItems = array(); // class => array of ('table' => array of (array of <sql_value>))
  35. private static $m_aBulkInsertCols = array(); // class => array of ('table' => array of <sql_column>)
  36. private static $m_bBulkInsert = false;
  37. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  38. private $m_iKey = null;
  39. private $m_aCurrValues = array();
  40. protected $m_aOrigValues = array();
  41. protected $m_aExtendedData = null;
  42. private $m_bDirty = false; // Means: "a modification is ongoing"
  43. // The object may have incorrect external keys, then any attempt of reload must be avoided
  44. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  45. // if null, then the check has to be performed again to know the status
  46. protected $m_bSecurityIssue = null;
  47. protected $m_aCheckIssues = null;
  48. protected $m_aDeleteIssues = null;
  49. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  50. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  51. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  52. protected $m_oMasterReplicaSet = null; // Set of SynchroReplica related to this object
  53. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  54. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  55. {
  56. if (!empty($aRow))
  57. {
  58. $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  59. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  60. return;
  61. }
  62. // Creation of a brand new object
  63. //
  64. $this->m_iKey = self::GetNextTempId(get_class($this));
  65. // set default values
  66. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  67. {
  68. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  69. $this->m_aOrigValues[$sAttCode] = null;
  70. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  71. {
  72. // This field has to be read from the DB
  73. // Leave the flag unset (optimization)
  74. }
  75. else
  76. {
  77. // No need to trigger a reload for that attribute
  78. // Let's consider it as being already fully loaded
  79. $this->m_aLoadedAtt[$sAttCode] = true;
  80. }
  81. }
  82. }
  83. // Read-only <=> Written once (archive)
  84. public function RegisterAsDirty()
  85. {
  86. // While the object may be written to the DB, it is NOT possible to reload it
  87. // or at least not possible to reload it the same way
  88. $this->m_bDirty = true;
  89. }
  90. public function IsNew()
  91. {
  92. return (!$this->m_bIsInDB);
  93. }
  94. // Returns an Id for memory objects
  95. static protected function GetNextTempId($sClass)
  96. {
  97. $sRootClass = MetaModel::GetRootClass($sClass);
  98. if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
  99. {
  100. self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
  101. }
  102. self::$m_aMemoryObjectsByClass[$sRootClass]++;
  103. return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
  104. }
  105. public function __toString()
  106. {
  107. $sRet = '';
  108. $sClass = get_class($this);
  109. $sRootClass = MetaModel::GetRootClass($sClass);
  110. $iPKey = $this->GetKey();
  111. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  112. $sRet .= "<ul class=\"treeview\">\n";
  113. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  114. {
  115. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  116. }
  117. $sRet .= "</ul>";
  118. return $sRet;
  119. }
  120. // Restore initial values... mmmm, to be discussed
  121. public function DBRevert()
  122. {
  123. $this->Reload();
  124. }
  125. protected function IsFullyLoaded()
  126. {
  127. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  128. {
  129. if (!$oAttDef->LoadInObject()) continue;
  130. if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
  131. {
  132. return false;
  133. }
  134. }
  135. return true;
  136. }
  137. public function Reload()
  138. {
  139. assert($this->m_bIsInDB);
  140. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false/*, $this->m_bAllowAllData*/);
  141. if (empty($aRow))
  142. {
  143. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  144. }
  145. $this->FromRow($aRow);
  146. // Process linked set attributes
  147. //
  148. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  149. {
  150. if (!$oAttDef->IsLinkSet()) continue;
  151. // Load the link information
  152. $sLinkClass = $oAttDef->GetLinkedClass();
  153. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  154. // The class to target is not the current class, because if this is a derived class,
  155. // it may differ from the target class, then things start to become confusing
  156. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  157. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  158. $oMyselfSearch = new DBObjectSearch($sMyClass);
  159. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  160. $oLinkSearch = new DBObjectSearch($sLinkClass);
  161. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  162. $oLinks = new DBObjectSet($oLinkSearch);
  163. $this->m_aCurrValues[$sAttCode] = $oLinks;
  164. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  165. $this->m_aLoadedAtt[$sAttCode] = true;
  166. }
  167. $this->m_bFullyLoaded = true;
  168. }
  169. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  170. {
  171. if (strlen($sClassAlias) == 0)
  172. {
  173. // Default to the current class
  174. $sClassAlias = get_class($this);
  175. }
  176. $this->m_iKey = null;
  177. $this->m_bIsInDB = true;
  178. $this->m_aCurrValues = array();
  179. $this->m_aOrigValues = array();
  180. $this->m_aLoadedAtt = array();
  181. $this->m_bCheckStatus = true;
  182. // Get the key
  183. //
  184. $sKeyField = $sClassAlias."id";
  185. if (!array_key_exists($sKeyField, $aRow))
  186. {
  187. // #@# Bug ?
  188. throw new CoreException("Missing key for class '".get_class($this)."'");
  189. }
  190. $iPKey = $aRow[$sKeyField];
  191. if (!self::IsValidPKey($iPKey))
  192. {
  193. if (is_null($iPKey))
  194. {
  195. throw new CoreException("Missing object id in query result (found null)");
  196. }
  197. else
  198. {
  199. throw new CoreException("An object id must be an integer value ($iPKey)");
  200. }
  201. }
  202. $this->m_iKey = $iPKey;
  203. // Build the object from an array of "attCode"=>"value")
  204. //
  205. $bFullyLoaded = true; // ... set to false if any attribute is not found
  206. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  207. {
  208. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  209. }
  210. else
  211. {
  212. $aAttList = $aAttToLoad[$sClassAlias];
  213. }
  214. foreach($aAttList as $sAttCode=>$oAttDef)
  215. {
  216. // Skip links (could not be loaded by the mean of this query)
  217. if ($oAttDef->IsLinkSet()) continue;
  218. if (!$oAttDef->LoadInObject()) continue;
  219. // Note: we assume that, for a given attribute, if it can be loaded,
  220. // then one column will be found with an empty suffix, the others have a suffix
  221. // Take care: the function isset will return false in case the value is null,
  222. // which is something that could happen on open joins
  223. $sAttRef = $sClassAlias.$sAttCode;
  224. if (array_key_exists($sAttRef, $aRow))
  225. {
  226. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  227. $this->m_aCurrValues[$sAttCode] = $value;
  228. if (is_object($value))
  229. {
  230. $this->m_aOrigValues[$sAttCode] = clone $value;
  231. }
  232. else
  233. {
  234. $this->m_aOrigValues[$sAttCode] = $value;
  235. }
  236. $this->m_aLoadedAtt[$sAttCode] = true;
  237. }
  238. else
  239. {
  240. // This attribute was expected and not found in the query columns
  241. $bFullyLoaded = false;
  242. }
  243. }
  244. // Load extended data
  245. if ($aExtendedDataSpec != null)
  246. {
  247. $aExtendedDataSpec['table'];
  248. foreach($aExtendedDataSpec['fields'] as $sColumn)
  249. {
  250. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  251. if (array_key_exists($sColRef, $aRow))
  252. {
  253. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  254. }
  255. }
  256. }
  257. return $bFullyLoaded;
  258. }
  259. public function Set($sAttCode, $value)
  260. {
  261. if ($sAttCode == 'finalclass')
  262. {
  263. // Ignore it - this attribute is set upon object creation and that's it
  264. return;
  265. }
  266. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  267. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  268. {
  269. // First time Set is called... ensure that the object gets fully loaded
  270. // Otherwise we would lose the values on a further Reload
  271. // + consistency does not make sense !
  272. $this->Reload();
  273. }
  274. if ($oAttDef->IsExternalKey())
  275. {
  276. if (is_object($value))
  277. {
  278. // Setting an external key with a whole object (instead of just an ID)
  279. // let's initialize also the external fields that depend on it
  280. // (useful when building objects in memory and not from a query)
  281. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  282. {
  283. 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");
  284. }
  285. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  286. {
  287. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  288. {
  289. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  290. }
  291. }
  292. }
  293. else if ($this->m_aCurrValues[$sAttCode] != $value)
  294. {
  295. // Setting an external key, but no any other information is available...
  296. // Invalidate the corresponding fields so that they get reloaded in case they are needed (See Get())
  297. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  298. {
  299. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  300. {
  301. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  302. unset($this->m_aLoadedAtt[$sCode]);
  303. }
  304. }
  305. }
  306. }
  307. if(!$oAttDef->IsScalar() && !is_object($value))
  308. {
  309. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  310. }
  311. if($oAttDef->IsLinkSet())
  312. {
  313. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  314. {
  315. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  316. }
  317. $oObjectSet = $value;
  318. $sSetClass = $oObjectSet->GetClass();
  319. $sLinkClass = $oAttDef->GetLinkedClass();
  320. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  321. if ($sSetClass != $sLinkClass)
  322. {
  323. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  324. }
  325. }
  326. $realvalue = $oAttDef->MakeRealValue($value, $this);
  327. $this->m_aCurrValues[$sAttCode] = $realvalue;
  328. // The object has changed, reset caches
  329. $this->m_bCheckStatus = null;
  330. $this->m_aAsArgs = null;
  331. // Make sure we do not reload it anymore... before saving it
  332. $this->RegisterAsDirty();
  333. }
  334. public function GetLabel($sAttCode)
  335. {
  336. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  337. return $oAttDef->GetLabel();
  338. }
  339. public function Get($sAttCode)
  340. {
  341. if (($iPos = strpos($sAttCode, '->')) === false)
  342. {
  343. return $this->GetStrict($sAttCode);
  344. }
  345. else
  346. {
  347. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  348. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  349. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  350. {
  351. throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
  352. }
  353. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  354. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  355. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  356. if (is_null($oRemoteObj))
  357. {
  358. return '';
  359. }
  360. else
  361. {
  362. return $oRemoteObj->Get($sRemoteAttCode);
  363. }
  364. }
  365. }
  366. public function GetStrict($sAttCode)
  367. {
  368. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  369. if (!$oAttDef->LoadInObject())
  370. {
  371. $sParentAttCode = $oAttDef->GetParentAttCode();
  372. $parentValue = $this->GetStrict($sParentAttCode);
  373. $value = $oAttDef->GetValue($parentValue, $this);
  374. }
  375. else
  376. {
  377. if (isset($this->m_aLoadedAtt[$sAttCode]))
  378. {
  379. // Standard case... we have the information directly
  380. }
  381. elseif ($this->m_bIsInDB && !$this->m_bDirty)
  382. {
  383. // Lazy load (polymorphism): complete by reloading the entire object
  384. // #@# non-scalar attributes.... handle that differently?
  385. $oKPI = new ExecutionKPI();
  386. $this->Reload();
  387. $oKPI->ComputeStats('Reload', get_class($this).'/'.$sAttCode);
  388. }
  389. elseif ($sAttCode == 'friendlyname')
  390. {
  391. // The friendly name is not computed and the object is dirty
  392. // Todo: implement the computation of the friendly name based on sprintf()
  393. //
  394. $this->m_aCurrValues[$sAttCode] = '';
  395. }
  396. else
  397. {
  398. // Not loaded... is it related to an external key?
  399. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  400. {
  401. // Let's get the object and compute all of the corresponding attributes
  402. // (i.e not only the requested attribute)
  403. //
  404. $sExtKeyAttCode = $oAttDef->GetKeyAttCode();
  405. if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
  406. {
  407. $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  408. // Note: "allow all data" must be enabled because the external fields are always visible
  409. // to the current user even if this is not the case for the remote object
  410. // This is consistent with the behavior of the lists
  411. $oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
  412. }
  413. else
  414. {
  415. $oRemote = null;
  416. }
  417. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  418. {
  419. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sExtKeyAttCode))
  420. {
  421. if ($oRemote)
  422. {
  423. $this->m_aCurrValues[$sCode] = $oRemote->Get($oDef->GetExtAttCode());
  424. }
  425. else
  426. {
  427. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  428. }
  429. $this->m_aLoadedAtt[$sCode] = true;
  430. }
  431. }
  432. }
  433. }
  434. $value = $this->m_aCurrValues[$sAttCode];
  435. }
  436. if ($value instanceof DBObjectSet)
  437. {
  438. $value->Rewind();
  439. }
  440. return $value;
  441. }
  442. public function GetOriginal($sAttCode)
  443. {
  444. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  445. {
  446. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  447. }
  448. return $this->m_aOrigValues[$sAttCode];
  449. }
  450. /**
  451. * Returns data loaded by the mean of a dynamic and explicit JOIN
  452. */
  453. public function GetExtendedData()
  454. {
  455. return $this->m_aExtendedData;
  456. }
  457. /**
  458. * Updates the value of an external field by (re)loading the object
  459. * corresponding to the external key and getting the value from it
  460. *
  461. * UNUSED ?
  462. *
  463. * @param string $sAttCode Attribute code of the external field to update
  464. * @return void
  465. */
  466. protected function UpdateExternalField($sAttCode)
  467. {
  468. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  469. if ($oAttDef->IsExternalField())
  470. {
  471. $sTargetClass = $oAttDef->GetTargetClass();
  472. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  473. // Note: "allow all data" must be enabled because the external fields are always visible
  474. // to the current user even if this is not the case for the remote object
  475. // This is consistent with the behavior of the lists
  476. $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
  477. if (is_object($oObj))
  478. {
  479. $value = $oObj->Get($oAttDef->GetExtAttCode());
  480. $this->Set($sAttCode, $value);
  481. }
  482. }
  483. }
  484. public function ComputeValues()
  485. {
  486. }
  487. // Compute scalar attributes that depend on any other type of attribute
  488. final public function DoComputeValues()
  489. {
  490. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  491. // First check that we are not currently computing the fields
  492. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  493. foreach (debug_backtrace() as $aCallInfo)
  494. {
  495. if (!array_key_exists("class", $aCallInfo)) continue;
  496. if ($aCallInfo["class"] != get_class($this)) continue;
  497. if ($aCallInfo["function"] != "ComputeValues") continue;
  498. return; //skip!
  499. }
  500. $this->ComputeValues();
  501. }
  502. public function GetAsHTML($sAttCode, $bLocalize = true)
  503. {
  504. $sClass = get_class($this);
  505. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  506. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  507. {
  508. //return $this->Get($sAttCode.'_friendlyname');
  509. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  510. $iTargetKey = $this->Get($sAttCode);
  511. if ($iTargetKey < 0)
  512. {
  513. // the key points to an object that exists only in memory... no hyperlink points to it yet
  514. return '';
  515. }
  516. else
  517. {
  518. $sLabel = $this->Get($sAttCode.'_friendlyname');
  519. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  520. }
  521. }
  522. // That's a standard attribute (might be an ext field or a direct field, etc.)
  523. return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
  524. }
  525. public function GetEditValue($sAttCode)
  526. {
  527. $sClass = get_class($this);
  528. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  529. if ($oAtt->IsExternalKey())
  530. {
  531. $sTargetClass = $oAtt->GetTargetClass();
  532. if ($this->IsNew())
  533. {
  534. // The current object exists only in memory, don't try to query it in the DB !
  535. // instead let's query for the object pointed by the external key, and get its name
  536. $targetObjId = $this->Get($sAttCode);
  537. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  538. if (is_object($oTargetObj))
  539. {
  540. $sEditValue = $oTargetObj->GetName();
  541. }
  542. else
  543. {
  544. $sEditValue = 0;
  545. }
  546. }
  547. else
  548. {
  549. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  550. }
  551. }
  552. else
  553. {
  554. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
  555. }
  556. return $sEditValue;
  557. }
  558. public function GetAsXML($sAttCode, $bLocalize = true)
  559. {
  560. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  561. return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
  562. }
  563. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  564. {
  565. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  566. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  567. }
  568. public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
  569. {
  570. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  571. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
  572. }
  573. public function GetOriginalAsXML($sAttCode, $bLocalize = true)
  574. {
  575. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  576. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
  577. }
  578. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  579. {
  580. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  581. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  582. }
  583. public static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true)
  584. {
  585. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  586. // Safety net
  587. //
  588. if (empty($sLabel))
  589. {
  590. // If the object if not issued from a query but constructed programmatically
  591. // the label may be empty. In this case run a query to get the object's friendly name
  592. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
  593. if (is_object($oTmpObj))
  594. {
  595. $sLabel = $oTmpObj->GetName();
  596. }
  597. else
  598. {
  599. // May happen in case the target object is not in the list of allowed values for this attribute
  600. $sLabel = "<em>$sObjClass::$sObjKey</em>";
  601. }
  602. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  603. }
  604. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  605. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  606. if (strlen($sUrl) > 0)
  607. {
  608. return "<a href=\"$sUrl\" title=\"$sHint\">$sLabel</a>";
  609. }
  610. else
  611. {
  612. return $sLabel;
  613. }
  614. }
  615. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  616. {
  617. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext);
  618. }
  619. public static function ComputeStandardUIPage($sClass)
  620. {
  621. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  622. if (!isset($aUIPagesCache[$sClass]))
  623. {
  624. $UIPage = false;
  625. if (is_callable("$sClass::GetUIPage"))
  626. {
  627. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  628. }
  629. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  630. }
  631. $sPage = $aUIPagesCache[$sClass];
  632. return $sPage;
  633. }
  634. public static function GetUIPage()
  635. {
  636. return 'UI.php';
  637. }
  638. // could be in the metamodel ?
  639. public static function IsValidPKey($value)
  640. {
  641. return ((string)$value === (string)(int)$value);
  642. }
  643. public function GetKey()
  644. {
  645. return $this->m_iKey;
  646. }
  647. public function SetKey($iNewKey)
  648. {
  649. if (!self::IsValidPKey($iNewKey))
  650. {
  651. throw new CoreException("An object id must be an integer value ($iNewKey)");
  652. }
  653. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  654. {
  655. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  656. }
  657. $this->m_iKey = $iNewKey;
  658. }
  659. /**
  660. * Get the icon representing this object
  661. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  662. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  663. */
  664. public function GetIcon($bImgTag = true)
  665. {
  666. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  667. }
  668. /**
  669. * Gets the name of an object in a safe manner for displaying inside a web page
  670. * @return string
  671. */
  672. public function GetName()
  673. {
  674. return htmlentities($this->GetRawName(), ENT_QUOTES, 'UTF-8');
  675. }
  676. /**
  677. * Gets the raw name of an object, this is not safe for displaying inside a web page
  678. * since the " < > characters are not escaped and the name may contain some XSS script
  679. * instructions.
  680. * Use this function only for internal computations or for an output to a non-HTML destination
  681. * @return string
  682. */
  683. public function GetRawName()
  684. {
  685. return $this->Get('friendlyname');
  686. }
  687. public function GetState()
  688. {
  689. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  690. if (empty($sStateAttCode))
  691. {
  692. return '';
  693. }
  694. else
  695. {
  696. return $this->Get($sStateAttCode);
  697. }
  698. }
  699. public function GetStateLabel()
  700. {
  701. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  702. if (empty($sStateAttCode))
  703. {
  704. return '';
  705. }
  706. else
  707. {
  708. $sStateValue = $this->Get($sStateAttCode);
  709. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  710. }
  711. }
  712. public function GetStateDescription()
  713. {
  714. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  715. if (empty($sStateAttCode))
  716. {
  717. return '';
  718. }
  719. else
  720. {
  721. $sStateValue = $this->Get($sStateAttCode);
  722. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  723. }
  724. }
  725. /**
  726. * Overridable - Define attributes read-only from the end-user perspective
  727. *
  728. * @return array List of attcodes
  729. */
  730. public static function GetReadOnlyAttributes()
  731. {
  732. return null;
  733. }
  734. /**
  735. * Overridable - Get predefined objects (could be hardcoded)
  736. * The predefined objects will be synchronized with the DB at each install/upgrade
  737. * As soon as a class has predefined objects, then nobody can create nor delete objects
  738. * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
  739. */
  740. public static function GetPredefinedObjects()
  741. {
  742. return null;
  743. }
  744. /**
  745. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  746. * for the given attribute in the current state of the object
  747. * @param $sAttCode string $sAttCode The code of the attribute
  748. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  749. * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
  750. * @return integer Flags: the binary combination of the flags applicable to this attribute
  751. */
  752. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  753. {
  754. $iFlags = 0; // By default (if no life cycle) no flag at all
  755. $aReadOnlyAtts = $this->GetReadOnlyAttributes();
  756. if ($aReadOnlyAtts != null)
  757. {
  758. if (in_array($sAttCode, $aReadOnlyAtts))
  759. {
  760. return OPT_ATT_READONLY;
  761. }
  762. }
  763. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  764. if (!empty($sStateAttCode))
  765. {
  766. if ($sTargetState != '')
  767. {
  768. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  769. }
  770. else
  771. {
  772. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  773. }
  774. }
  775. $aReasons = array();
  776. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  777. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  778. }
  779. /**
  780. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  781. * for the given attribute for the current state of the object considered as an INITIAL state
  782. * @param string $sAttCode The code of the attribute
  783. * @return integer Flags: the binary combination of the flags applicable to this attribute
  784. */
  785. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  786. {
  787. $iFlags = 0;
  788. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  789. if (!empty($sStateAttCode))
  790. {
  791. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  792. }
  793. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  794. }
  795. // check if the given (or current) value is suitable for the attribute
  796. // return true if successfull
  797. // return the error desciption otherwise
  798. public function CheckValue($sAttCode, $value = null)
  799. {
  800. if (!is_null($value))
  801. {
  802. $toCheck = $value;
  803. }
  804. else
  805. {
  806. $toCheck = $this->Get($sAttCode);
  807. }
  808. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  809. if (!$oAtt->IsWritable())
  810. {
  811. return true;
  812. }
  813. elseif ($oAtt->IsNull($toCheck))
  814. {
  815. if ($oAtt->IsNullAllowed())
  816. {
  817. return true;
  818. }
  819. else
  820. {
  821. return "Null not allowed";
  822. }
  823. }
  824. elseif ($oAtt->IsExternalKey())
  825. {
  826. if (!MetaModel::SkipCheckExtKeys())
  827. {
  828. $sTargetClass = $oAtt->GetTargetClass();
  829. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  830. if (is_null($oTargetObj))
  831. {
  832. return "Target object not found ($sTargetClass::$toCheck)";
  833. }
  834. }
  835. if ($oAtt->IsHierarchicalKey())
  836. {
  837. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  838. if ($toCheck == $this->GetKey())
  839. {
  840. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  841. }
  842. }
  843. }
  844. elseif ($oAtt->IsScalar())
  845. {
  846. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  847. if (count($aValues) > 0)
  848. {
  849. if (!array_key_exists($toCheck, $aValues))
  850. {
  851. return "Value not allowed [$toCheck]";
  852. }
  853. }
  854. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  855. {
  856. $iLen = strlen($toCheck);
  857. if ($iLen > $iMaxSize)
  858. {
  859. return "String too long (found $iLen, limited to $iMaxSize)";
  860. }
  861. }
  862. if (!$oAtt->CheckFormat($toCheck))
  863. {
  864. return "Wrong format [$toCheck]";
  865. }
  866. }
  867. return true;
  868. }
  869. // check attributes together
  870. public function CheckConsistency()
  871. {
  872. return true;
  873. }
  874. // check integrity rules (before inserting or updating the object)
  875. // a displayable error is returned
  876. public function DoCheckToWrite()
  877. {
  878. $this->DoComputeValues();
  879. $this->m_aCheckIssues = array();
  880. $aChanges = $this->ListChanges();
  881. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  882. {
  883. $res = $this->CheckValue($sAttCode);
  884. if ($res !== true)
  885. {
  886. // $res contains the error description
  887. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  888. }
  889. }
  890. if (count($this->m_aCheckIssues) > 0)
  891. {
  892. // No need to check consistency between attributes if any of them has
  893. // an unexpected value
  894. return;
  895. }
  896. $res = $this->CheckConsistency();
  897. if ($res !== true)
  898. {
  899. // $res contains the error description
  900. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  901. }
  902. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  903. //
  904. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  905. {
  906. foreach($aChanges as $sAttCode => $value)
  907. {
  908. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  909. if ($iFlags & OPT_ATT_SLAVE)
  910. {
  911. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  912. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  913. $sAttLabel = $oAttDef->GetLabel();
  914. foreach($aReasons as $aReasonInfo)
  915. {
  916. // Todo: associate the attribute code with the error
  917. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  918. }
  919. }
  920. }
  921. }
  922. }
  923. final public function CheckToWrite()
  924. {
  925. if (MetaModel::SkipCheckToWrite())
  926. {
  927. return array(true, array());
  928. }
  929. if (is_null($this->m_bCheckStatus))
  930. {
  931. $oKPI = new ExecutionKPI();
  932. $this->DoCheckToWrite();
  933. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  934. if (count($this->m_aCheckIssues) == 0)
  935. {
  936. $this->m_bCheckStatus = true;
  937. }
  938. else
  939. {
  940. $this->m_bCheckStatus = false;
  941. }
  942. }
  943. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  944. }
  945. // check if it is allowed to delete the existing object from the database
  946. // a displayable error is returned
  947. protected function DoCheckToDelete(&$oDeletionPlan)
  948. {
  949. $this->m_aDeleteIssues = array(); // Ok
  950. if ($this->InSyncScope())
  951. {
  952. $oReplicaSet = $this->GetMasterReplica();
  953. if ($oReplicaSet->Count() > 0)
  954. {
  955. while($aData = $oReplicaSet->FetchAssoc())
  956. {
  957. $oDataSource = $aData['datasource'];
  958. $oReplica = $aData['replica'];
  959. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  960. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  961. {
  962. // The current task has the right to delete the object
  963. continue;
  964. }
  965. if ($oReplica->Get('status_dest_creator') != 1)
  966. {
  967. // The object is not owned by the task
  968. continue;
  969. }
  970. $sLink = $oDataSource->GetName();
  971. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  972. switch($sUserDeletePolicy)
  973. {
  974. case 'nobody':
  975. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  976. break;
  977. case 'administrators':
  978. if (!UserRights::IsAdministrator())
  979. {
  980. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  981. }
  982. break;
  983. case 'everybody':
  984. default:
  985. // Ok
  986. break;
  987. }
  988. }
  989. }
  990. }
  991. }
  992. final public function CheckToDelete(&$oDeletionPlan)
  993. {
  994. $this->MakeDeletionPlan($oDeletionPlan);
  995. $oDeletionPlan->ComputeResults();
  996. return (!$oDeletionPlan->FoundStopper());
  997. }
  998. protected function ListChangedValues(array $aProposal)
  999. {
  1000. $aDelta = array();
  1001. foreach ($aProposal as $sAtt => $proposedValue)
  1002. {
  1003. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1004. {
  1005. // The value was not set
  1006. $aDelta[$sAtt] = $proposedValue;
  1007. }
  1008. elseif(is_object($proposedValue))
  1009. {
  1010. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1011. // The value is an object, the comparison is not strict
  1012. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  1013. {
  1014. $aDelta[$sAtt] = $proposedValue;
  1015. }
  1016. }
  1017. else
  1018. {
  1019. // The value is a scalar, the comparison must be 100% strict
  1020. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1021. {
  1022. //echo "$sAtt:<pre>\n";
  1023. //var_dump($this->m_aOrigValues[$sAtt]);
  1024. //var_dump($proposedValue);
  1025. //echo "</pre>\n";
  1026. $aDelta[$sAtt] = $proposedValue;
  1027. }
  1028. }
  1029. }
  1030. return $aDelta;
  1031. }
  1032. // List the attributes that have been changed
  1033. // Returns an array of attname => currentvalue
  1034. public function ListChanges()
  1035. {
  1036. if ($this->m_bIsInDB)
  1037. {
  1038. return $this->ListChangedValues($this->m_aCurrValues);
  1039. }
  1040. else
  1041. {
  1042. return $this->m_aCurrValues;
  1043. }
  1044. }
  1045. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1046. public function IsModified()
  1047. {
  1048. $aChanges = $this->ListChanges();
  1049. return (count($aChanges) != 0);
  1050. }
  1051. public function Equals($oSibling)
  1052. {
  1053. if (get_class($oSibling) != get_class($this))
  1054. {
  1055. return false;
  1056. }
  1057. if ($this->GetKey() != $oSibling->GetKey())
  1058. {
  1059. return false;
  1060. }
  1061. if ($this->m_bIsInDB)
  1062. {
  1063. // If one has changed, then consider them as being different
  1064. if ($this->IsModified() || $oSibling->IsModified())
  1065. {
  1066. return false;
  1067. }
  1068. }
  1069. else
  1070. {
  1071. // Todo - implement this case (loop on every attribute)
  1072. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1073. //{
  1074. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1075. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1076. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1077. //{
  1078. //return false;
  1079. //}
  1080. //}
  1081. return false;
  1082. }
  1083. return true;
  1084. }
  1085. // used both by insert/update
  1086. private function DBWriteLinks()
  1087. {
  1088. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1089. {
  1090. if (!$oAttDef->IsLinkSet()) continue;
  1091. $oLinks = $this->Get($sAttCode);
  1092. $oLinks->Rewind();
  1093. while ($oLinkedObject = $oLinks->Fetch())
  1094. {
  1095. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1096. if ($oLinkedObject->IsModified())
  1097. {
  1098. $oLinkedObject->DBWrite();
  1099. }
  1100. }
  1101. // Delete the objects that were initialy present and disappeared from the list
  1102. // (if any)
  1103. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  1104. if ($oOriginalSet != null)
  1105. {
  1106. $aOriginalList = $oOriginalSet->ToArray();
  1107. $aNewSet = $oLinks->ToArray();
  1108. foreach($aOriginalList as $iId => $oObject)
  1109. {
  1110. if (!array_key_exists($iId, $aNewSet))
  1111. {
  1112. // It disappeared from the list
  1113. $oObject->DBDelete();
  1114. }
  1115. }
  1116. }
  1117. }
  1118. }
  1119. // Note: this is experimental - it was designed to speed up the setup of iTop
  1120. // Known limitations:
  1121. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1122. // - the id of the object is not updated
  1123. static public final function BulkInsertStart()
  1124. {
  1125. self::$m_bBulkInsert = true;
  1126. }
  1127. static public final function BulkInsertFlush()
  1128. {
  1129. if (!self::$m_bBulkInsert) return;
  1130. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1131. {
  1132. foreach ($aTables as $sTable => $sColumns)
  1133. {
  1134. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1135. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1136. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1137. }
  1138. }
  1139. // Reset
  1140. self::$m_aBulkInsertItems = array();
  1141. self::$m_aBulkInsertCols = array();
  1142. self::$m_bBulkInsert = false;
  1143. }
  1144. private function DBInsertSingleTable($sTableClass)
  1145. {
  1146. $sTable = MetaModel::DBGetTable($sTableClass);
  1147. // Abstract classes or classes having no specific attribute do not have an associated table
  1148. if ($sTable == '') return;
  1149. $sClass = get_class($this);
  1150. // fields in first array, values in the second
  1151. $aFieldsToWrite = array();
  1152. $aValuesToWrite = array();
  1153. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1154. {
  1155. // Add it to the list of fields to write
  1156. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1157. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1158. }
  1159. $aHierarchicalKeys = array();
  1160. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1161. {
  1162. // Skip this attribute if not defined in this table
  1163. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1164. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1165. foreach($aAttColumns as $sColumn => $sValue)
  1166. {
  1167. $aFieldsToWrite[] = "`$sColumn`";
  1168. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1169. }
  1170. if ($oAttDef->IsHierarchicalKey())
  1171. {
  1172. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1173. }
  1174. }
  1175. if (count($aValuesToWrite) == 0) return false;
  1176. if (MetaModel::DBIsReadOnly())
  1177. {
  1178. $iNewKey = -1;
  1179. }
  1180. else
  1181. {
  1182. if (self::$m_bBulkInsert)
  1183. {
  1184. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1185. {
  1186. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1187. }
  1188. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1189. $iNewKey = 999999; // TODO - compute next id....
  1190. }
  1191. else
  1192. {
  1193. if (count($aHierarchicalKeys) > 0)
  1194. {
  1195. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1196. {
  1197. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1198. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1199. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1200. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1201. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1202. }
  1203. }
  1204. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1205. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1206. }
  1207. }
  1208. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1209. if (empty($this->m_iKey))
  1210. {
  1211. // Take the autonumber
  1212. $this->m_iKey = $iNewKey;
  1213. }
  1214. return $this->m_iKey;
  1215. }
  1216. // Insert of record for the new object into the database
  1217. // Returns the key of the newly created object
  1218. public function DBInsertNoReload()
  1219. {
  1220. if ($this->m_bIsInDB)
  1221. {
  1222. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1223. }
  1224. $sClass = get_class($this);
  1225. $sRootClass = MetaModel::GetRootClass($sClass);
  1226. // Ensure the update of the values (we are accessing the data directly)
  1227. $this->DoComputeValues();
  1228. $this->OnInsert();
  1229. if ($this->m_iKey < 0)
  1230. {
  1231. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1232. $this->m_iKey = null;
  1233. }
  1234. // If not automatically computed, then check that the key is given by the caller
  1235. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1236. {
  1237. if (empty($this->m_iKey))
  1238. {
  1239. 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));
  1240. }
  1241. }
  1242. // Ultimate check - ensure DB integrity
  1243. list($bRes, $aIssues) = $this->CheckToWrite();
  1244. if (!$bRes)
  1245. {
  1246. $sIssues = implode(', ', $aIssues);
  1247. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1248. }
  1249. // Stop watches
  1250. $sState = $this->GetState();
  1251. if ($sState != '')
  1252. {
  1253. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1254. {
  1255. if ($oAttDef instanceof AttributeStopWatch)
  1256. {
  1257. if (in_array($sState, $oAttDef->GetStates()))
  1258. {
  1259. // Start the stop watch and compute the deadlines
  1260. $oSW = $this->Get($sAttCode);
  1261. $oSW->Start($this, $oAttDef);
  1262. $oSW->ComputeDeadlines($this, $oAttDef);
  1263. $this->Set($sAttCode, $oSW);
  1264. }
  1265. }
  1266. }
  1267. }
  1268. // First query built upon on the root class, because the ID must be created first
  1269. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1270. // Then do the leaf class, if different from the root class
  1271. if ($sClass != $sRootClass)
  1272. {
  1273. $this->DBInsertSingleTable($sClass);
  1274. }
  1275. // Then do the other classes
  1276. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1277. {
  1278. if ($sParentClass == $sRootClass) continue;
  1279. $this->DBInsertSingleTable($sParentClass);
  1280. }
  1281. $this->DBWriteLinks();
  1282. $this->m_bIsInDB = true;
  1283. $this->m_bDirty = false;
  1284. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  1285. $this->m_aAsArgs = null;
  1286. $this->AfterInsert();
  1287. // Activate any existing trigger
  1288. $sClass = get_class($this);
  1289. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1290. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1291. while ($oTrigger = $oSet->Fetch())
  1292. {
  1293. $oTrigger->DoActivate($this->ToArgs('this'));
  1294. }
  1295. $this->RecordObjCreation();
  1296. return $this->m_iKey;
  1297. }
  1298. public function DBInsert()
  1299. {
  1300. $this->DBInsertNoReload();
  1301. $this->Reload();
  1302. return $this->m_iKey;
  1303. }
  1304. public function DBInsertTracked(CMDBChange $oChange)
  1305. {
  1306. CMDBObject::SetCurrentChange($oChange);
  1307. return $this->DBInsert();
  1308. }
  1309. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1310. {
  1311. CMDBObject::SetCurrentChange($oChange);
  1312. return $this->DBInsertNoReload();
  1313. }
  1314. // Creates a copy of the current object into the database
  1315. // Returns the id of the newly created object
  1316. public function DBClone($iNewKey = null)
  1317. {
  1318. $this->m_bIsInDB = false;
  1319. $this->m_iKey = $iNewKey;
  1320. $ret = $this->DBInsert();
  1321. $this->RecordObjCreation();
  1322. return $ret;
  1323. }
  1324. /**
  1325. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1326. * The purpose of this method is to reset the appropriate attributes of the object in
  1327. * order to make sure that the newly cloned object is really distinct from its clone
  1328. */
  1329. public function __clone()
  1330. {
  1331. $this->m_bIsInDB = false;
  1332. $this->m_bDirty = true;
  1333. $this->m_iKey = self::GetNextTempId(get_class($this));
  1334. }
  1335. // Update a record
  1336. public function DBUpdate()
  1337. {
  1338. if (!$this->m_bIsInDB)
  1339. {
  1340. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1341. }
  1342. // Stop watches
  1343. $sState = $this->GetState();
  1344. if ($sState != '')
  1345. {
  1346. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1347. {
  1348. if ($oAttDef instanceof AttributeStopWatch)
  1349. {
  1350. if (in_array($sState, $oAttDef->GetStates()))
  1351. {
  1352. // Compute or recompute the deadlines
  1353. $oSW = $this->Get($sAttCode);
  1354. $oSW->ComputeDeadlines($this, $oAttDef);
  1355. $this->Set($sAttCode, $oSW);
  1356. }
  1357. }
  1358. }
  1359. }
  1360. $this->DoComputeValues();
  1361. $this->OnUpdate();
  1362. $aChanges = $this->ListChanges();
  1363. if (count($aChanges) == 0)
  1364. {
  1365. // Attempting to update an unchanged object
  1366. return;
  1367. }
  1368. // Ultimate check - ensure DB integrity
  1369. list($bRes, $aIssues) = $this->CheckToWrite();
  1370. if (!$bRes)
  1371. {
  1372. $sIssues = implode(', ', $aIssues);
  1373. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1374. }
  1375. // Save the original values (will be reset to the new values when the object get written to the DB)
  1376. $aOriginalValues = $this->m_aOrigValues;
  1377. $bHasANewExternalKeyValue = false;
  1378. $aHierarchicalKeys = array();
  1379. foreach($aChanges as $sAttCode => $valuecurr)
  1380. {
  1381. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1382. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1383. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1384. if ($oAttDef->IsHierarchicalKey())
  1385. {
  1386. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1387. }
  1388. }
  1389. if (!MetaModel::DBIsReadOnly())
  1390. {
  1391. // Update the left & right indexes for each hierarchical key
  1392. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1393. {
  1394. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1395. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1396. $aRes = CMDBSource::QueryToArray($sSQL);
  1397. $iMyLeft = $aRes[0]['left'];
  1398. $iMyRight = $aRes[0]['right'];
  1399. $iDelta =$iMyRight - $iMyLeft + 1;
  1400. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1401. if ($aChanges[$sAttCode] == 0)
  1402. {
  1403. // No new parent, insert completely at the right of the tree
  1404. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1405. $aRes = CMDBSource::QueryToArray($sSQL);
  1406. if (count($aRes) == 0)
  1407. {
  1408. $iNewLeft = 1;
  1409. }
  1410. else
  1411. {
  1412. $iNewLeft = $aRes[0]['max']+1;
  1413. }
  1414. }
  1415. else
  1416. {
  1417. // Insert at the right of the specified parent
  1418. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aChanges[$sAttCode]);
  1419. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1420. }
  1421. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1422. $aHKChanges = array();
  1423. $aHKChanges[$sAttCode] = $aChanges[$sAttCode];
  1424. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1425. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1426. $aChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1427. }
  1428. // Update scalar attributes
  1429. if (count($aChanges) != 0)
  1430. {
  1431. $oFilter = new DBObjectSearch(get_class($this));
  1432. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1433. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1434. CMDBSource::Query($sSQL);
  1435. }
  1436. }
  1437. $this->DBWriteLinks();
  1438. $this->m_bDirty = false;
  1439. $this->AfterUpdate();
  1440. // Reload to get the external attributes
  1441. if ($bHasANewExternalKeyValue)
  1442. {
  1443. $this->Reload();
  1444. }
  1445. else
  1446. {
  1447. // Reset original values although the object has not been reloaded
  1448. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1449. {
  1450. if ($bLoaded)
  1451. {
  1452. $value = $this->m_aCurrValues[$sAttCode];
  1453. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1454. }
  1455. }
  1456. }
  1457. if (count($aChanges) != 0)
  1458. {
  1459. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1460. }
  1461. return $this->m_iKey;
  1462. }
  1463. public function DBUpdateTracked(CMDBChange $oChange)
  1464. {
  1465. CMDBObject::SetCurrentChange($oChange);
  1466. return $this->DBUpdate();
  1467. }
  1468. // Make the current changes persistent - clever wrapper for Insert or Update
  1469. public function DBWrite()
  1470. {
  1471. if ($this->m_bIsInDB)
  1472. {
  1473. return $this->DBUpdate();
  1474. }
  1475. else
  1476. {
  1477. return $this->DBInsert();
  1478. }
  1479. }
  1480. private function DBDeleteSingleTable($sTableClass)
  1481. {
  1482. $sTable = MetaModel::DBGetTable($sTableClass);
  1483. // Abstract classes or classes having no specific attribute do not have an associated table
  1484. if ($sTable == '') return;
  1485. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1486. $sKey = CMDBSource::Quote($this->m_iKey);
  1487. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1488. CMDBSource::DeleteFrom($sDeleteSQL);
  1489. }
  1490. protected function DBDeleteSingleObject()
  1491. {
  1492. if (!MetaModel::DBIsReadOnly())
  1493. {
  1494. $this->OnDelete();
  1495. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1496. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1497. {
  1498. if ($oAttDef->IsHierarchicalKey())
  1499. {
  1500. // Update the left & right indexes for each hierarchical key
  1501. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1502. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1503. $aRes = CMDBSource::QueryToArray($sSQL);
  1504. $iMyLeft = $aRes[0]['left'];
  1505. $iMyRight = $aRes[0]['right'];
  1506. $iDelta =$iMyRight - $iMyLeft + 1;
  1507. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1508. // No new parent for now, insert completely at the right of the tree
  1509. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1510. $aRes = CMDBSource::QueryToArray($sSQL);
  1511. if (count($aRes) == 0)
  1512. {
  1513. $iNewLeft = 1;
  1514. }
  1515. else
  1516. {
  1517. $iNewLeft = $aRes[0]['max']+1;
  1518. }
  1519. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1520. }
  1521. }
  1522. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1523. {
  1524. $this->DBDeleteSingleTable($sParentClass);
  1525. }
  1526. $this->AfterDelete();
  1527. $this->m_bIsInDB = false;
  1528. $this->m_iKey = null;
  1529. }
  1530. }
  1531. // Delete an object... and guarantee data integrity
  1532. //
  1533. public function DBDelete(&$oDeletionPlan = null)
  1534. {
  1535. if (is_null($oDeletionPlan))
  1536. {
  1537. $oDeletionPlan = new DeletionPlan();
  1538. }
  1539. $this->MakeDeletionPlan($oDeletionPlan);
  1540. $oDeletionPlan->ComputeResults();
  1541. if ($oDeletionPlan->FoundStopper())
  1542. {
  1543. $aIssues = $oDeletionPlan->GetIssues();
  1544. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1545. }
  1546. else
  1547. {
  1548. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1549. {
  1550. foreach ($aToDelete as $iId => $aData)
  1551. {
  1552. $oToDelete = $aData['to_delete'];
  1553. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1554. // because for each object we would try to update all the preceding ones... that are already deleted
  1555. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1556. // As a temporary fix: delete only the objects that are still to be deleted...
  1557. if ($oToDelete->m_bIsInDB)
  1558. {
  1559. $oToDelete->DBDeleteSingleObject();
  1560. }
  1561. }
  1562. }
  1563. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1564. {
  1565. foreach ($aToUpdate as $iId => $aData)
  1566. {
  1567. $oToUpdate = $aData['to_reset'];
  1568. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1569. {
  1570. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1571. $oToUpdate->DBUpdate();
  1572. }
  1573. }
  1574. }
  1575. }
  1576. return $oDeletionPlan;
  1577. }
  1578. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1579. {
  1580. CMDBObject::SetCurrentChange($oChange);
  1581. $this->DBDelete($oDeletionPlan);
  1582. }
  1583. public function EnumTransitions()
  1584. {
  1585. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1586. if (empty($sStateAttCode)) return array();
  1587. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1588. return MetaModel::EnumTransitions(get_class($this), $sState);
  1589. }
  1590. /**
  1591. * Designed as an action to be called when a stop watch threshold times out
  1592. * or from within the framework
  1593. */
  1594. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  1595. {
  1596. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1597. if (empty($sStateAttCode)) return false;
  1598. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1599. $aStateTransitions = $this->EnumTransitions();
  1600. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  1601. {
  1602. // This simulus has no effect in the current state... do nothing
  1603. return;
  1604. }
  1605. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1606. // Change the state before proceeding to the actions, this is necessary because an action might
  1607. // trigger another stimuli (alternative: push the stimuli into a queue)
  1608. $sPreviousState = $this->Get($sStateAttCode);
  1609. $sNewState = $aTransitionDef['target_state'];
  1610. $this->Set($sStateAttCode, $sNewState);
  1611. // $aTransitionDef is an
  1612. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1613. $bSuccess = true;
  1614. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1615. {
  1616. // std PHP spec
  1617. $aActionCallSpec = array($this, $sActionHandler);
  1618. if (!is_callable($aActionCallSpec))
  1619. {
  1620. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1621. return;
  1622. }
  1623. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1624. // if one call fails, the whole is considered as failed
  1625. if (!$bRet) $bSuccess = false;
  1626. }
  1627. if ($bSuccess)
  1628. {
  1629. $sClass = get_class($this);
  1630. // Stop watches
  1631. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1632. {
  1633. if ($oAttDef instanceof AttributeStopWatch)
  1634. {
  1635. $oSW = $this->Get($sAttCode);
  1636. if (in_array($sNewState, $oAttDef->GetStates()))
  1637. {
  1638. $oSW->Start($this, $oAttDef);
  1639. }
  1640. else
  1641. {
  1642. $oSW->Stop($this, $oAttDef);
  1643. }
  1644. $this->Set($sAttCode, $oSW);
  1645. }
  1646. }
  1647. if (!$bDoNotWrite)
  1648. {
  1649. $this->DBWrite();
  1650. }
  1651. // Change state triggers...
  1652. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1653. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1654. while ($oTrigger = $oSet->Fetch())
  1655. {
  1656. $oTrigger->DoActivate($this->ToArgs('this'));
  1657. }
  1658. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1659. while ($oTrigger = $oSet->Fetch())
  1660. {
  1661. $oTrigger->DoActivate($this->ToArgs('this'));
  1662. }
  1663. }
  1664. return $bSuccess;
  1665. }
  1666. /**
  1667. * Designed as an action to be called when a stop watch threshold times out
  1668. */
  1669. public function ResetStopWatch($sAttCode)
  1670. {
  1671. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1672. if (!$oAttDef instanceof AttributeStopWatch)
  1673. {
  1674. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  1675. }
  1676. $oSW = $this->Get($sAttCode);
  1677. $oSW->Reset($this, $oAttDef);
  1678. $this->Set($sAttCode, $oSW);
  1679. }
  1680. // Make standard context arguments
  1681. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1682. // Several options here:
  1683. // 1) cache the result
  1684. // 2) set only the object ref and resolve the values iif needed from contextual templates and queries (easy for the queries, not for the templates)
  1685. public function ToArgs($sArgName = 'this')
  1686. {
  1687. if (is_null($this->m_aAsArgs))
  1688. {
  1689. $oKPI = new ExecutionKPI();
  1690. $aScalarArgs = array();
  1691. $aScalarArgs[$sArgName] = $this->GetKey();
  1692. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1693. $aScalarArgs[$sArgName.'->object()'] = $this;
  1694. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink('iTopStandardURLMaker', false);
  1695. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = $this->GetHyperlink('PortalURLMaker', false);
  1696. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1697. $sClass = get_class($this);
  1698. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1699. {
  1700. if ($oAttDef instanceof AttributeCaseLog)
  1701. {
  1702. $oCaseLog = $this->Get($sAttCode);
  1703. $aScalarArgs[$sArgName.'->'.$sAttCode] = $oCaseLog->GetText();
  1704. $aScalarArgs[$sArgName.'->head('.$sAttCode.')'] = $oCaseLog->GetLatestEntry();
  1705. }
  1706. elseif ($oAttDef->IsScalar())
  1707. {
  1708. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1709. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1710. $sAsHtml = $this->GetAsHtml($sAttCode);
  1711. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1712. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = $this->GetEditValue($sAttCode); // "Nice" display value, but without HTML tags and entities
  1713. }
  1714. elseif ($oAttDef->IsLinkSet())
  1715. {
  1716. $sRemoteName = $oAttDef->IsIndirect() ? $oAttDef->GetExtKeyToRemote().'_friendlyname' : 'friendlyname';
  1717. // Since we want to limit the number of item, it is not feasible to simply rely on Get() to build the link set
  1718. // $oLinkSet = $this->Get($sAttCode);
  1719. $sLinkedClass = $oAttDef->GetLinkedClass();
  1720. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1721. $oSearch = DBObjectSearch::FromOQL("SELECT $sLinkedClass WHERE $sExtKeyToMe = :this");
  1722. $oLinkSet = new DBObjectSet($oSearch, array(), array('this' => $this->GetKey()));
  1723. $iLimit = MetaModel::GetConfig()->Get('max_linkset_output');
  1724. if ($iLimit > 0)
  1725. {
  1726. $oLinkSet->SetLimit($iLimit);
  1727. }
  1728. $aNames = $oLinkSet->GetColumnAsArray($sRemoteName);
  1729. if ($iLimit > 0)
  1730. {
  1731. $iTotal = $oLinkSet->Count();
  1732. if ($iTotal > count($aNames))
  1733. {
  1734. $aNames[] = '... '.Dict::Format('UI:TruncatedResults', count($aNames), $iTotal);
  1735. }
  1736. }
  1737. $sNames = implode("\n", $aNames);
  1738. $aScalarArgs[$sArgName.'->'.$sAttCode] = $sNames;
  1739. }
  1740. }
  1741. $this->m_aAsArgs = $aScalarArgs;
  1742. $oKPI->ComputeStats('ToArgs', get_class($this));
  1743. }
  1744. return $this->m_aAsArgs;
  1745. }
  1746. // To be optionaly overloaded
  1747. protected function OnInsert()
  1748. {
  1749. }
  1750. // To be optionaly overloaded
  1751. protected function AfterInsert()
  1752. {
  1753. }
  1754. // To be optionaly overloaded
  1755. protected function OnUpdate()
  1756. {
  1757. }
  1758. // To be optionaly overloaded
  1759. protected function AfterUpdate()
  1760. {
  1761. }
  1762. // To be optionaly overloaded
  1763. protected function OnDelete()
  1764. {
  1765. }
  1766. // To be optionaly overloaded
  1767. protected function AfterDelete()
  1768. {
  1769. }
  1770. /**
  1771. * Common to the recording of link set changes (add/remove/modify)
  1772. */
  1773. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  1774. {
  1775. if ($iLinkSetOwnerId <= 0)
  1776. {
  1777. return null;
  1778. }
  1779. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  1780. {
  1781. // The link set owner class does not keep track of its history
  1782. return null;
  1783. }
  1784. // Determine the linked item class and id
  1785. //
  1786. if ($oLinkSet->IsIndirect())
  1787. {
  1788. // The "item" is on the other end (N-N links)
  1789. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  1790. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  1791. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  1792. if ($aOriginalValues)
  1793. {
  1794. // Get the value from the original values
  1795. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  1796. }
  1797. else
  1798. {
  1799. $iItemId = $this->Get($sExtKeyToRemote);
  1800. }
  1801. }
  1802. else
  1803. {
  1804. // I am the "item" (1-N links)
  1805. $sItemClass = get_class($this);
  1806. $iItemId = $this->GetKey();
  1807. }
  1808. // Get the remote object, to determine its exact class
  1809. // 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!
  1810. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  1811. if ($oOwner)
  1812. {
  1813. $sLinkSetOwnerClass = get_class($oOwner);
  1814. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  1815. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  1816. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  1817. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  1818. $oMyChangeOp->Set("item_class", $sItemClass);
  1819. $oMyChangeOp->Set("item_id", $iItemId);
  1820. return $oMyChangeOp;
  1821. }
  1822. else
  1823. {
  1824. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  1825. return null;
  1826. }
  1827. }
  1828. /**
  1829. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  1830. */
  1831. private function RecordLinkSetListChange($bAdd = true)
  1832. {
  1833. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1834. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1835. {
  1836. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1837. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  1838. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  1839. if ($oMyChangeOp)
  1840. {
  1841. if ($bAdd)
  1842. {
  1843. $oMyChangeOp->Set("type", "added");
  1844. }
  1845. else
  1846. {
  1847. $oMyChangeOp->Set("type", "removed");
  1848. }
  1849. $iId = $oMyChangeOp->DBInsertNoReload();
  1850. }
  1851. }
  1852. }
  1853. protected function RecordObjCreation()
  1854. {
  1855. $this->RecordLinkSetListChange(true);
  1856. }
  1857. protected function RecordObjDeletion($objkey)
  1858. {
  1859. $this->RecordLinkSetListChange(false);
  1860. }
  1861. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  1862. {
  1863. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1864. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1865. {
  1866. if (array_key_exists($sExtKeyAttCode, $aValues))
  1867. {
  1868. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1869. // Keep track of link added/removed
  1870. //
  1871. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  1872. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  1873. if ($oMyChangeOp)
  1874. {
  1875. $oMyChangeOp->Set("type", "added");
  1876. $oMyChangeOp->DBInsertNoReload();
  1877. }
  1878. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  1879. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  1880. if ($oMyChangeOp)
  1881. {
  1882. $oMyChangeOp->Set("type", "removed");
  1883. $oMyChangeOp->DBInsertNoReload();
  1884. }
  1885. }
  1886. else
  1887. {
  1888. // Keep track of link changes
  1889. //
  1890. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  1891. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  1892. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  1893. if ($oMyChangeOp)
  1894. {
  1895. $oMyChangeOp->Set("link_id", $this->GetKey());
  1896. $iId = $oMyChangeOp->DBInsertNoReload();
  1897. }
  1898. }
  1899. }
  1900. }
  1901. // Return an empty set for the parent of all
  1902. public static function GetRelationQueries($sRelCode)
  1903. {
  1904. return array();
  1905. }
  1906. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1907. {
  1908. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1909. {
  1910. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1911. $sQuery = $aQueryInfo["sQuery"];
  1912. $bPropagate = $aQueryInfo["bPropagate"];
  1913. $iDistance = $aQueryInfo["iDistance"];
  1914. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1915. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1916. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1917. while ($oObj = $oObjSet->Fetch())
  1918. {
  1919. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1920. $sObjKey = $oObj->GetKey();
  1921. if (array_key_exists($sRootClass, $aResults))
  1922. {
  1923. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1924. {
  1925. continue; // already visited, skip
  1926. }
  1927. }
  1928. $aResults[$sRootClass][$sObjKey] = $oObj;
  1929. if ($iDepth > 0)
  1930. {
  1931. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1932. }
  1933. }
  1934. }
  1935. return $aResults;
  1936. }
  1937. public function GetReferencingObjects($bAllowAllData = false)
  1938. {
  1939. $aDependentObjects = array();
  1940. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1941. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1942. {
  1943. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1944. {
  1945. // skip if this external key is behind an external field
  1946. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1947. $oSearch = new DBObjectSearch($sRemoteClass);
  1948. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1949. if ($bAllowAllData)
  1950. {
  1951. $oSearch->AllowAllData();
  1952. }
  1953. $oSet = new CMDBObjectSet($oSearch);
  1954. if ($oSet->Count() > 0)
  1955. {
  1956. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1957. 'attribute' => $oExtKeyAttDef,
  1958. 'objects' => $oSet,
  1959. );
  1960. }
  1961. }
  1962. }
  1963. return $aDependentObjects;
  1964. }
  1965. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  1966. {
  1967. $sClass = get_class($this);
  1968. $iThisId = $this->GetKey();
  1969. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  1970. if (array_key_exists($sClass, $aVisited))
  1971. {
  1972. if (in_array($iThisId, $aVisited[$sClass]))
  1973. {
  1974. return;
  1975. }
  1976. }
  1977. $aVisited[$sClass] = $iThisId;
  1978. if ($iDeleteOption == DEL_MANUAL)
  1979. {
  1980. // Stop the recursion here
  1981. return;
  1982. }
  1983. // Check the node itself
  1984. $this->DoCheckToDelete($oDeletionPlan);
  1985. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  1986. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  1987. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1988. {
  1989. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1990. {
  1991. $oAttDef = $aData['attribute'];
  1992. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1993. $oDepSet = $aData['objects'];
  1994. $oDepSet->Rewind();
  1995. while ($oDependentObj = $oDepSet->fetch())
  1996. {
  1997. $iId = $oDependentObj->GetKey();
  1998. if ($oAttDef->IsNullAllowed())
  1999. {
  2000. // Optional external key, list to reset
  2001. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  2002. {
  2003. // Move the child up one level i.e. set the same parent as the current object
  2004. $iParentId = $this->Get($oAttDef->GetCode());
  2005. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  2006. }
  2007. else
  2008. {
  2009. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  2010. }
  2011. }
  2012. else
  2013. {
  2014. // Mandatory external key, list to delete
  2015. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  2016. }
  2017. }
  2018. }
  2019. }
  2020. }
  2021. /**
  2022. * Get all the synchro replica related to this object
  2023. * @param none
  2024. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  2025. */
  2026. public function GetMasterReplica()
  2027. {
  2028. if ($this->m_oMasterReplicaSet == null)
  2029. {
  2030. //$aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  2031. //$sClassesList = "'".implode("','", $aParentClasses)."'";
  2032. $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";
  2033. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2034. $this->m_oMasterReplicaSet = $oReplicaSet;
  2035. }
  2036. else
  2037. {
  2038. $this->m_oMasterReplicaSet->Rewind();
  2039. }
  2040. return $this->m_oMasterReplicaSet;
  2041. }
  2042. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2043. {
  2044. $iFlags = OPT_ATT_NORMAL;
  2045. $oSet = $this->GetMasterReplica();
  2046. while($aData = $oSet->FetchAssoc())
  2047. {
  2048. if ($aData['datasource']->GetKey() == SynchroExecution::GetCurrentTaskId())
  2049. {
  2050. // Ignore the current task (check to write => ok)
  2051. continue;
  2052. }
  2053. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2054. $oReplica = $aData['replica'];
  2055. $oSource = $aData['datasource'];
  2056. $oAttrSet = $oSource->Get('attribute_list');
  2057. while($oSyncAttr = $oAttrSet->Fetch())
  2058. {
  2059. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2060. {
  2061. $iFlags |= OPT_ATT_SLAVE;
  2062. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2063. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2064. }
  2065. }
  2066. }
  2067. return $iFlags;
  2068. }
  2069. public function InSyncScope()
  2070. {
  2071. return true;
  2072. // TODO - FINALIZE THIS OPTIMIZATION
  2073. //
  2074. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2075. //
  2076. static $aSynchroClasses = null;
  2077. if (is_null($aSynchroClasses))
  2078. {
  2079. $aSynchroClasses = array();
  2080. $sOQL = "SELECT SynchroDataSource AS datasource";
  2081. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2082. while($oSource = $oSourceSet->Fetch())
  2083. {
  2084. $sTarget = $oSource->Get('scope_class');
  2085. $aSynchroClasses[] = $oSource;
  2086. }
  2087. }
  2088. // to be continued...
  2089. }
  2090. }
  2091. ?>