dbobjectsearch.class.php 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Define filters for a given class of objects (formerly named "filter")
  20. *
  21. * @copyright Copyright (C) 2010-2017 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. // Dev hack for disabling the some query build optimizations (Folding/Merging)
  25. define('ENABLE_OPT', true);
  26. class DBObjectSearch extends DBSearch
  27. {
  28. private $m_aClasses; // queried classes (alias => class name), the first item is the class corresponding to this filter (the rest is coming from subfilters)
  29. private $m_aSelectedClasses; // selected for the output (alias => class name)
  30. private $m_oSearchCondition;
  31. private $m_aParams;
  32. private $m_aFullText;
  33. private $m_aPointingTo;
  34. private $m_aReferencedBy;
  35. // By default, some information may be hidden to the current user
  36. // But it may happen that we need to disable that feature
  37. protected $m_bAllowAllData = false;
  38. protected $m_bDataFiltered = false;
  39. public function __construct($sClass, $sClassAlias = null)
  40. {
  41. parent::__construct();
  42. if (is_null($sClassAlias)) $sClassAlias = $sClass;
  43. if(!is_string($sClass)) throw new Exception('DBObjectSearch::__construct called with a non-string parameter: $sClass = '.print_r($sClass, true));
  44. if(!MetaModel::IsValidClass($sClass)) throw new Exception('DBObjectSearch::__construct called for an invalid class: "'.$sClass.'"');
  45. $this->m_aSelectedClasses = array($sClassAlias => $sClass);
  46. $this->m_aClasses = array($sClassAlias => $sClass);
  47. $this->m_oSearchCondition = new TrueExpression;
  48. $this->m_aParams = array();
  49. $this->m_aFullText = array();
  50. $this->m_aPointingTo = array();
  51. $this->m_aReferencedBy = array();
  52. }
  53. public function AllowAllData($bAllowAllData = true) {$this->m_bAllowAllData = $bAllowAllData;}
  54. public function IsAllDataAllowed() {return $this->m_bAllowAllData;}
  55. protected function IsDataFiltered() {return $this->m_bDataFiltered; }
  56. protected function SetDataFiltered() {$this->m_bDataFiltered = true;}
  57. // Create a search definition that leads to 0 result, still a valid search object
  58. static public function FromEmptySet($sClass)
  59. {
  60. $oResultFilter = new DBObjectSearch($sClass);
  61. $oResultFilter->m_oSearchCondition = new FalseExpression;
  62. return $oResultFilter;
  63. }
  64. public function GetJoinedClasses() {return $this->m_aClasses;}
  65. public function GetClassName($sAlias)
  66. {
  67. if (array_key_exists($sAlias, $this->m_aSelectedClasses))
  68. {
  69. return $this->m_aSelectedClasses[$sAlias];
  70. }
  71. else
  72. {
  73. throw new CoreException("Invalid class alias '$sAlias'");
  74. }
  75. }
  76. public function GetClass()
  77. {
  78. return reset($this->m_aSelectedClasses);
  79. }
  80. public function GetClassAlias()
  81. {
  82. reset($this->m_aSelectedClasses);
  83. return key($this->m_aSelectedClasses);
  84. }
  85. public function GetFirstJoinedClass()
  86. {
  87. return reset($this->m_aClasses);
  88. }
  89. public function GetFirstJoinedClassAlias()
  90. {
  91. reset($this->m_aClasses);
  92. return key($this->m_aClasses);
  93. }
  94. /**
  95. * Change the class (only subclasses are supported as of now, because the conditions must fit the new class)
  96. * Defaults to the first selected class (most of the time it is also the first joined class
  97. */
  98. public function ChangeClass($sNewClass, $sAlias = null)
  99. {
  100. if (is_null($sAlias))
  101. {
  102. $sAlias = $this->GetClassAlias();
  103. }
  104. else
  105. {
  106. if (!array_key_exists($sAlias, $this->m_aSelectedClasses))
  107. {
  108. // discard silently - necessary when recursing on the related nodes (see code below)
  109. return;
  110. }
  111. }
  112. $sCurrClass = $this->GetClassName($sAlias);
  113. if ($sNewClass == $sCurrClass)
  114. {
  115. // Skip silently
  116. return;
  117. }
  118. if (!MetaModel::IsParentClass($sCurrClass, $sNewClass))
  119. {
  120. throw new Exception("Could not change the search class from '$sCurrClass' to '$sNewClass'. Only child classes are permitted.");
  121. }
  122. // Change for this node
  123. //
  124. $this->m_aSelectedClasses[$sAlias] = $sNewClass;
  125. $this->m_aClasses[$sAlias] = $sNewClass;
  126. // Change for all the related node (yes, this was necessary with some queries - strange effects otherwise)
  127. //
  128. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  129. {
  130. foreach($aPointingTo as $iOperatorCode => $aFilter)
  131. {
  132. foreach($aFilter as $oExtFilter)
  133. {
  134. $oExtFilter->ChangeClass($sNewClass, $sAlias);
  135. }
  136. }
  137. }
  138. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  139. {
  140. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  141. {
  142. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  143. {
  144. foreach ($aFilters as $oForeignFilter)
  145. {
  146. $oForeignFilter->ChangeClass($sNewClass, $sAlias);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. public function GetSelectedClasses()
  153. {
  154. return $this->m_aSelectedClasses;
  155. }
  156. /**
  157. * @param array $aSelectedClasses array of aliases
  158. * @throws CoreException
  159. */
  160. public function SetSelectedClasses($aSelectedClasses)
  161. {
  162. $this->m_aSelectedClasses = array();
  163. foreach ($aSelectedClasses as $sAlias)
  164. {
  165. if (!array_key_exists($sAlias, $this->m_aClasses))
  166. {
  167. throw new CoreException("SetSelectedClasses: Invalid class alias $sAlias");
  168. }
  169. $this->m_aSelectedClasses[$sAlias] = $this->m_aClasses[$sAlias];
  170. }
  171. }
  172. /**
  173. * Change any alias of the query tree
  174. *
  175. * @param $sOldName
  176. * @param $sNewName
  177. * @return bool True if the alias has been found and changed
  178. */
  179. public function RenameAlias($sOldName, $sNewName)
  180. {
  181. $bFound = false;
  182. if (array_key_exists($sOldName, $this->m_aClasses))
  183. {
  184. $bFound = true;
  185. }
  186. if (array_key_exists($sNewName, $this->m_aClasses))
  187. {
  188. throw new Exception("RenameAlias: alias '$sNewName' already used");
  189. }
  190. $aClasses = array();
  191. foreach ($this->m_aClasses as $sAlias => $sClass)
  192. {
  193. if ($sAlias === $sOldName)
  194. {
  195. $aClasses[$sNewName] = $sClass;
  196. }
  197. else
  198. {
  199. $aClasses[$sAlias] = $sClass;
  200. }
  201. }
  202. $this->m_aClasses = $aClasses;
  203. $aSelectedClasses = array();
  204. foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
  205. {
  206. if ($sAlias === $sOldName)
  207. {
  208. $aSelectedClasses[$sNewName] = $sClass;
  209. }
  210. else
  211. {
  212. $aSelectedClasses[$sAlias] = $sClass;
  213. }
  214. }
  215. $this->m_aSelectedClasses = $aSelectedClasses;
  216. $this->m_oSearchCondition->RenameAlias($sOldName, $sNewName);
  217. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  218. {
  219. foreach($aPointingTo as $iOperatorCode => $aFilter)
  220. {
  221. foreach($aFilter as $oExtFilter)
  222. {
  223. $bFound = $oExtFilter->RenameAlias($sOldName, $sNewName) || $bFound;
  224. }
  225. }
  226. }
  227. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  228. {
  229. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  230. {
  231. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  232. {
  233. foreach ($aFilters as $oForeignFilter)
  234. {
  235. $bFound = $oForeignFilter->RenameAlias($sOldName, $sNewName) || $bFound;
  236. }
  237. }
  238. }
  239. }
  240. return $bFound;
  241. }
  242. public function SetModifierProperty($sPluginClass, $sProperty, $value)
  243. {
  244. $this->m_aModifierProperties[$sPluginClass][$sProperty] = $value;
  245. }
  246. public function GetModifierProperties($sPluginClass)
  247. {
  248. if (array_key_exists($sPluginClass, $this->m_aModifierProperties))
  249. {
  250. return $this->m_aModifierProperties[$sPluginClass];
  251. }
  252. else
  253. {
  254. return array();
  255. }
  256. }
  257. public function IsAny()
  258. {
  259. if (!$this->m_oSearchCondition->IsTrue()) return false;
  260. if (count($this->m_aFullText) > 0) return false;
  261. if (count($this->m_aPointingTo) > 0) return false;
  262. if (count($this->m_aReferencedBy) > 0) return false;
  263. return true;
  264. }
  265. protected function TransferConditionExpression($oFilter, $aTranslation)
  266. {
  267. // Prevent collisions in the parameter names by renaming them if needed
  268. foreach($this->m_aParams as $sParam => $value)
  269. {
  270. if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam]))
  271. {
  272. // Generate a new and unique name for the collinding parameter
  273. $index = 1;
  274. while(array_key_exists($sParam.$index, $oFilter->m_aParams))
  275. {
  276. $index++;
  277. }
  278. $secondValue = $oFilter->m_aParams[$sParam];
  279. $oFilter->RenameParam($sParam, $sParam.$index);
  280. unset($oFilter->m_aParams[$sParam]);
  281. $oFilter->m_aParams[$sParam.$index] = $secondValue;
  282. }
  283. }
  284. $oTranslated = $oFilter->GetCriteria()->Translate($aTranslation, false, false /* leave unresolved fields */);
  285. $this->AddConditionExpression($oTranslated);
  286. $this->m_aParams = array_merge($this->m_aParams, $oFilter->m_aParams);
  287. }
  288. protected function RenameParam($sOldName, $sNewName)
  289. {
  290. $this->m_oSearchCondition->RenameParam($sOldName, $sNewName);
  291. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  292. {
  293. foreach($aPointingTo as $iOperatorCode => $aFilter)
  294. {
  295. foreach($aFilter as $oExtFilter)
  296. {
  297. $oExtFilter->RenameParam($sOldName, $sNewName);
  298. }
  299. }
  300. }
  301. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  302. {
  303. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  304. {
  305. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  306. {
  307. foreach ($aFilters as $oForeignFilter)
  308. {
  309. $oForeignFilter->RenameParam($sOldName, $sNewName);
  310. }
  311. }
  312. }
  313. }
  314. }
  315. public function ResetCondition()
  316. {
  317. $this->m_oSearchCondition = new TrueExpression();
  318. // ? is that usefull/enough, do I need to rebuild the list after the subqueries ?
  319. }
  320. public function MergeConditionExpression($oExpression)
  321. {
  322. $this->m_oSearchCondition = $this->m_oSearchCondition->LogOr($oExpression);
  323. }
  324. public function AddConditionExpression($oExpression)
  325. {
  326. $this->m_oSearchCondition = $this->m_oSearchCondition->LogAnd($oExpression);
  327. }
  328. public function AddNameCondition($sName)
  329. {
  330. $oValueExpr = new ScalarExpression($sName);
  331. $oNameExpr = new FieldExpression('friendlyname', $this->GetClassAlias());
  332. $oNewCondition = new BinaryExpression($oNameExpr, '=', $oValueExpr);
  333. $this->AddConditionExpression($oNewCondition);
  334. }
  335. public function AddCondition($sFilterCode, $value, $sOpCode = null, $bParseSeachString = false)
  336. {
  337. MyHelpers::CheckKeyInArray('filter code in class: '.$this->GetClass(), $sFilterCode, MetaModel::GetClassFilterDefs($this->GetClass()));
  338. $oFilterDef = MetaModel::GetClassFilterDef($this->GetClass(), $sFilterCode);
  339. $oField = new FieldExpression($sFilterCode, $this->GetClassAlias());
  340. if (empty($sOpCode))
  341. {
  342. if ($sFilterCode == 'id')
  343. {
  344. $sOpCode = '=';
  345. }
  346. else
  347. {
  348. $oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sFilterCode);
  349. $oNewCondition = $oAttDef->GetSmartConditionExpression($value, $oField, $this->m_aParams, $bParseSeachString);
  350. $this->AddConditionExpression($oNewCondition);
  351. return;
  352. }
  353. }
  354. MyHelpers::CheckKeyInArray('operator', $sOpCode, $oFilterDef->GetOperators());
  355. // Parse search strings if needed and if the filter code corresponds to a valid attcode
  356. if($bParseSeachString && MetaModel::IsValidAttCode($this->GetClass(), $sFilterCode))
  357. {
  358. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  359. $value = $oAttDef->ParseSearchString($value);
  360. }
  361. // Preserve backward compatibility - quick n'dirty way to change that API semantic
  362. //
  363. switch($sOpCode)
  364. {
  365. case 'SameDay':
  366. case 'SameMonth':
  367. case 'SameYear':
  368. case 'Today':
  369. case '>|':
  370. case '<|':
  371. case '=|':
  372. throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', array('operator' => $sOpCode));
  373. break;
  374. case "IN":
  375. if (!is_array($value)) $value = array($value);
  376. if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
  377. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  378. $sOQLCondition = $oField->Render()." IN $sListExpr";
  379. break;
  380. case "NOTIN":
  381. if (!is_array($value)) $value = array($value);
  382. if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
  383. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  384. $sOQLCondition = $oField->Render()." NOT IN $sListExpr";
  385. break;
  386. case 'Contains':
  387. $this->m_aParams[$sFilterCode] = "%$value%";
  388. $sOperator = 'LIKE';
  389. break;
  390. case 'Begins with':
  391. $this->m_aParams[$sFilterCode] = "$value%";
  392. $sOperator = 'LIKE';
  393. break;
  394. case 'Finishes with':
  395. $this->m_aParams[$sFilterCode] = "%$value";
  396. $sOperator = 'LIKE';
  397. break;
  398. default:
  399. $this->m_aParams[$sFilterCode] = $value;
  400. $sOperator = $sOpCode;
  401. }
  402. switch($sOpCode)
  403. {
  404. case "IN":
  405. case "NOTIN":
  406. $oNewCondition = Expression::FromOQL($sOQLCondition);
  407. break;
  408. case 'Contains':
  409. case 'Begins with':
  410. case 'Finishes with':
  411. default:
  412. $oRightExpr = new VariableExpression($sFilterCode);
  413. $oNewCondition = new BinaryExpression($oField, $sOperator, $oRightExpr);
  414. }
  415. $this->AddConditionExpression($oNewCondition);
  416. }
  417. /**
  418. * Specify a condition on external keys or link sets
  419. * @param sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
  420. * Example: infra_list->ci_id->location_id->country
  421. * @param value The value to match (can be an array => IN(val1, val2...)
  422. * @return void
  423. */
  424. public function AddConditionAdvanced($sAttSpec, $value)
  425. {
  426. $sClass = $this->GetClass();
  427. $iPos = strpos($sAttSpec, '->');
  428. if ($iPos !== false)
  429. {
  430. $sAttCode = substr($sAttSpec, 0, $iPos);
  431. $sSubSpec = substr($sAttSpec, $iPos + 2);
  432. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  433. {
  434. throw new Exception("Invalid attribute code '$sClass/$sAttCode' in condition specification '$sAttSpec'");
  435. }
  436. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  437. if ($oAttDef->IsLinkSet())
  438. {
  439. $sTargetClass = $oAttDef->GetLinkedClass();
  440. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  441. $oNewFilter = new DBObjectSearch($sTargetClass);
  442. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  443. $this->AddCondition_ReferencedBy($oNewFilter, $sExtKeyToMe);
  444. }
  445. elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  446. {
  447. $sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE);
  448. $oNewFilter = new DBObjectSearch($sTargetClass);
  449. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  450. $this->AddCondition_PointingTo($oNewFilter, $sAttCode);
  451. }
  452. else
  453. {
  454. throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key");
  455. }
  456. }
  457. else
  458. {
  459. // $sAttSpec is an attribute code
  460. //
  461. if (is_array($value))
  462. {
  463. $oField = new FieldExpression($sAttSpec, $this->GetClass());
  464. $oListExpr = ListExpression::FromScalars($value);
  465. $oInValues = new BinaryExpression($oField, 'IN', $oListExpr);
  466. $this->AddConditionExpression($oInValues);
  467. }
  468. else
  469. {
  470. $this->AddCondition($sAttSpec, $value);
  471. }
  472. }
  473. }
  474. public function AddCondition_FullText($sFullText)
  475. {
  476. $this->m_aFullText[] = $sFullText;
  477. }
  478. protected function AddToNameSpace(&$aClassAliases, &$aAliasTranslation, $bTranslateMainAlias = true)
  479. {
  480. if ($bTranslateMainAlias)
  481. {
  482. $sOrigAlias = $this->GetFirstJoinedClassAlias();
  483. if (array_key_exists($sOrigAlias, $aClassAliases))
  484. {
  485. $sNewAlias = MetaModel::GenerateUniqueAlias($aClassAliases, $sOrigAlias, $this->GetFirstJoinedClass());
  486. if (isset($this->m_aSelectedClasses[$sOrigAlias]))
  487. {
  488. $this->m_aSelectedClasses[$sNewAlias] = $this->GetFirstJoinedClass();
  489. unset($this->m_aSelectedClasses[$sOrigAlias]);
  490. }
  491. // TEMPORARY ALGORITHM (m_aClasses is not correctly updated, it is not possible to add a subtree onto a subnode)
  492. // Replace the element at the same position (unset + set is not enough because the hash array is ordered)
  493. $aPrevList = $this->m_aClasses;
  494. $this->m_aClasses = array();
  495. foreach ($aPrevList as $sSomeAlias => $sSomeClass)
  496. {
  497. if ($sSomeAlias == $sOrigAlias)
  498. {
  499. $this->m_aClasses[$sNewAlias] = $sSomeClass; // note: GetFirstJoinedClass now returns '' !!!
  500. }
  501. else
  502. {
  503. $this->m_aClasses[$sSomeAlias] = $sSomeClass;
  504. }
  505. }
  506. // Translate the condition expression with the new alias
  507. $aAliasTranslation[$sOrigAlias]['*'] = $sNewAlias;
  508. }
  509. // add the alias into the filter aliases list
  510. $aClassAliases[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
  511. }
  512. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  513. {
  514. foreach($aPointingTo as $iOperatorCode => $aFilter)
  515. {
  516. foreach($aFilter as $oFilter)
  517. {
  518. $oFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  519. }
  520. }
  521. }
  522. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  523. {
  524. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  525. {
  526. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  527. {
  528. foreach ($aFilters as $oForeignFilter)
  529. {
  530. $oForeignFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  531. }
  532. }
  533. }
  534. }
  535. }
  536. // Browse the tree nodes recursively
  537. //
  538. protected function GetNode($sAlias)
  539. {
  540. if ($this->GetFirstJoinedClassAlias() == $sAlias)
  541. {
  542. return $this;
  543. }
  544. else
  545. {
  546. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  547. {
  548. foreach($aPointingTo as $iOperatorCode => $aFilter)
  549. {
  550. foreach($aFilter as $oFilter)
  551. {
  552. $ret = $oFilter->GetNode($sAlias);
  553. if (is_object($ret))
  554. {
  555. return $ret;
  556. }
  557. }
  558. }
  559. }
  560. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  561. {
  562. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  563. {
  564. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  565. {
  566. foreach ($aFilters as $oForeignFilter)
  567. {
  568. $ret = $oForeignFilter->GetNode($sAlias);
  569. if (is_object($ret))
  570. {
  571. return $ret;
  572. }
  573. }
  574. }
  575. }
  576. }
  577. }
  578. // Not found
  579. return null;
  580. }
  581. /**
  582. * Helper to
  583. * - convert a translation table (format optimized for the translation in an expression tree) into simple hash
  584. * - compile over an eventually existing map
  585. *
  586. * @param $aRealiasingMap Map to update
  587. * @param $aAliasTranslation Translation table resulting from calls to MergeWith_InNamespace
  588. * @return array of <old-alias> => <new-alias>
  589. */
  590. protected function UpdateRealiasingMap(&$aRealiasingMap, $aAliasTranslation)
  591. {
  592. if ($aRealiasingMap !== null)
  593. {
  594. foreach ($aAliasTranslation as $sPrevAlias => $aRules)
  595. {
  596. if (isset($aRules['*']))
  597. {
  598. $sNewAlias = $aRules['*'];
  599. $sOriginalAlias = array_search($sPrevAlias, $aRealiasingMap);
  600. if ($sOriginalAlias !== false)
  601. {
  602. $aRealiasingMap[$sOriginalAlias] = $sNewAlias;
  603. }
  604. else
  605. {
  606. $aRealiasingMap[$sPrevAlias] = $sNewAlias;
  607. }
  608. }
  609. }
  610. }
  611. }
  612. /**
  613. * Completes the list of alias=>class by browsing the whole structure recursively
  614. * This a workaround to handle some cases in which the list of classes is not correctly updated.
  615. * This code should disappear as soon as DBObjectSearch get split between a container search class and a Node class
  616. *
  617. * @param $aClasses List to be completed
  618. */
  619. protected function RecomputeClassList(&$aClasses)
  620. {
  621. $aClasses[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
  622. // Recurse in the query tree
  623. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  624. {
  625. foreach($aPointingTo as $iOperatorCode => $aFilter)
  626. {
  627. foreach($aFilter as $oFilter)
  628. {
  629. $oFilter->RecomputeClassList($aClasses);
  630. }
  631. }
  632. }
  633. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  634. {
  635. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  636. {
  637. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  638. {
  639. foreach ($aFilters as $oForeignFilter)
  640. {
  641. $oForeignFilter->RecomputeClassList($aClasses);
  642. }
  643. }
  644. }
  645. }
  646. }
  647. /**
  648. * @param DBObjectSearch $oFilter
  649. * @param $sExtKeyAttCode
  650. * @param int $iOperatorCode
  651. * @param null $aRealiasingMap array of <old-alias> => <new-alias>, for each alias that has changed
  652. * @throws CoreException
  653. * @throws CoreWarning
  654. */
  655. public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
  656. {
  657. if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode))
  658. {
  659. throw new CoreWarning("The attribute code '$sExtKeyAttCode' is not an external key of the class '{$this->GetClass()}'");
  660. }
  661. $oAttExtKey = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
  662. if(!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass()))
  663. {
  664. throw new CoreException("The specified filter (pointing to {$oFilter->GetClass()}) is not compatible with the key '{$this->GetClass()}::$sExtKeyAttCode', which is pointing to {$oAttExtKey->GetTargetClass()}");
  665. }
  666. if(($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey))
  667. {
  668. throw new CoreException("The specified tree operator $iOperatorCode is not applicable to the key '{$this->GetClass()}::$sExtKeyAttCode', which is not a HierarchicalKey");
  669. }
  670. // Note: though it seems to be a good practice to clone the given source filter
  671. // (as it was done and fixed an issue in Intersect())
  672. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  673. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  674. // NO: $oFilter = $oFilter->DeepClone();
  675. // See also: Trac #639, and self::AddCondition_ReferencedBy()
  676. $aAliasTranslation = array();
  677. $res = $this->AddCondition_PointingTo_InNameSpace($oFilter, $sExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
  678. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  679. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  680. if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass()))
  681. {
  682. if (isset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode]))
  683. {
  684. foreach ($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode] as $oRemoteFilter)
  685. {
  686. if ($this->GetClass() == $oRemoteFilter->GetClass())
  687. {
  688. // Optimization - fold sibling query
  689. $aAliasTranslation = array();
  690. $this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation);
  691. unset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode]);
  692. $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false);
  693. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  694. break;
  695. }
  696. }
  697. }
  698. }
  699. $this->RecomputeClassList($this->m_aClasses);
  700. return $res;
  701. }
  702. protected function AddCondition_PointingTo_InNameSpace(DBObjectSearch $oFilter, $sExtKeyAttCode, &$aClassAliases, &$aAliasTranslation, $iOperatorCode)
  703. {
  704. // Find the node on which the new tree must be attached (most of the time it is "this")
  705. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  706. $bMerged = false;
  707. if (ENABLE_OPT && isset($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode]))
  708. {
  709. foreach ($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode] as $oExisting)
  710. {
  711. if ($oExisting->GetClass() == $oFilter->GetClass())
  712. {
  713. $oExisting->MergeWith_InNamespace($oFilter, $oExisting->m_aClasses, $aAliasTranslation);
  714. $bMerged = true;
  715. break;
  716. }
  717. }
  718. }
  719. if (!$bMerged)
  720. {
  721. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  722. $oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode][] = $oFilter;
  723. }
  724. }
  725. /**
  726. * @param DBObjectSearch $oFilter
  727. * @param $sForeignExtKeyAttCode
  728. * @param int $iOperatorCode
  729. * @param null $aRealiasingMap array of <old-alias> => <new-alias>, for each alias that has changed
  730. */
  731. public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
  732. {
  733. $sForeignClass = $oFilter->GetClass();
  734. if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode))
  735. {
  736. throw new CoreException("The attribute code '$sForeignExtKeyAttCode' is not an external key of the class '{$sForeignClass}'");
  737. }
  738. $oAttExtKey = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  739. if(!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass()))
  740. {
  741. // à refaire en spécifique dans FromOQL
  742. throw new CoreException("The specified filter (objects referencing an object of class {$this->GetClass()}) is not compatible with the key '{$sForeignClass}::$sForeignExtKeyAttCode', which is pointing to {$oAttExtKey->GetTargetClass()}");
  743. }
  744. // Note: though it seems to be a good practice to clone the given source filter
  745. // (as it was done and fixed an issue in Intersect())
  746. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  747. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  748. // NO: $oFilter = $oFilter->DeepClone();
  749. // See also: Trac #639, and self::AddCondition_PointingTo()
  750. $aAliasTranslation = array();
  751. $res = $this->AddCondition_ReferencedBy_InNameSpace($oFilter, $sForeignExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
  752. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  753. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  754. if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass()))
  755. {
  756. if (isset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode]))
  757. {
  758. foreach ($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode] as $oRemoteFilter)
  759. {
  760. if ($this->GetClass() == $oRemoteFilter->GetClass())
  761. {
  762. // Optimization - fold sibling query
  763. $aAliasTranslation = array();
  764. $this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation);
  765. unset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode]);
  766. $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false);
  767. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  768. break;
  769. }
  770. }
  771. }
  772. }
  773. $this->RecomputeClassList($this->m_aClasses);
  774. return $res;
  775. }
  776. protected function AddCondition_ReferencedBy_InNameSpace(DBSearch $oFilter, $sForeignExtKeyAttCode, &$aClassAliases, &$aAliasTranslation, $iOperatorCode)
  777. {
  778. $sForeignClass = $oFilter->GetClass();
  779. // Find the node on which the new tree must be attached (most of the time it is "this")
  780. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  781. $bMerged = false;
  782. if (ENABLE_OPT && isset($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode]))
  783. {
  784. foreach ($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode] as $oExisting)
  785. {
  786. if ($oExisting->GetClass() == $oFilter->GetClass())
  787. {
  788. $oExisting->MergeWith_InNamespace($oFilter, $oExisting->m_aClasses, $aAliasTranslation);
  789. $bMerged = true;
  790. break;
  791. }
  792. }
  793. }
  794. if (!$bMerged)
  795. {
  796. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  797. $oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode][] = $oFilter;
  798. }
  799. }
  800. public function Intersect(DBSearch $oFilter)
  801. {
  802. if ($oFilter instanceof DBUnionSearch)
  803. {
  804. // Develop!
  805. $aFilters = $oFilter->GetSearches();
  806. }
  807. else
  808. {
  809. $aFilters = array($oFilter);
  810. }
  811. $aSearches = array();
  812. foreach ($aFilters as $oRightFilter)
  813. {
  814. // Limitation: the queried class must be the first declared class
  815. if ($this->GetFirstJoinedClassAlias() != $this->GetClassAlias())
  816. {
  817. throw new CoreException("Limitation: cannot merge two queries if the queried class ({$this->GetClass()} AS {$this->GetClassAlias()}) is not the first joined class ({$this->GetFirstJoinedClass()} AS {$this->GetFirstJoinedClassAlias()})");
  818. }
  819. if ($oRightFilter->GetFirstJoinedClassAlias() != $oRightFilter->GetClassAlias())
  820. {
  821. throw new CoreException("Limitation: cannot merge two queries if the queried class ({$oRightFilter->GetClass()} AS {$oRightFilter->GetClassAlias()}) is not the first joined class ({$oRightFilter->GetFirstJoinedClass()} AS {$oRightFilter->GetFirstJoinedClassAlias()})");
  822. }
  823. $oLeftFilter = $this->DeepClone();
  824. $oRightFilter = $oRightFilter->DeepClone();
  825. $bAllowAllData = ($oLeftFilter->IsAllDataAllowed() && $oRightFilter->IsAllDataAllowed());
  826. $oLeftFilter->AllowAllData($bAllowAllData);
  827. if ($oLeftFilter->GetClass() != $oRightFilter->GetClass())
  828. {
  829. if (MetaModel::IsParentClass($oLeftFilter->GetClass(), $oRightFilter->GetClass()))
  830. {
  831. // Specialize $oLeftFilter
  832. $oLeftFilter->ChangeClass($oRightFilter->GetClass());
  833. }
  834. elseif (MetaModel::IsParentClass($oRightFilter->GetClass(), $oLeftFilter->GetClass()))
  835. {
  836. // Specialize $oRightFilter
  837. $oRightFilter->ChangeClass($oLeftFilter->GetClass());
  838. }
  839. else
  840. {
  841. throw new CoreException("Attempting to merge a filter of class '{$oLeftFilter->GetClass()}' with a filter of class '{$oRightFilter->GetClass()}'");
  842. }
  843. }
  844. $aAliasTranslation = array();
  845. $oLeftFilter->MergeWith_InNamespace($oRightFilter, $oLeftFilter->m_aClasses, $aAliasTranslation);
  846. $oLeftFilter->TransferConditionExpression($oRightFilter, $aAliasTranslation);
  847. $aSearches[] = $oLeftFilter;
  848. }
  849. if (count($aSearches) == 1)
  850. {
  851. // return a DBObjectSearch
  852. return $aSearches[0];
  853. }
  854. else
  855. {
  856. return new DBUnionSearch($aSearches);
  857. }
  858. }
  859. protected function MergeWith_InNamespace($oFilter, &$aClassAliases, &$aAliasTranslation)
  860. {
  861. if ($this->GetClass() != $oFilter->GetClass())
  862. {
  863. throw new CoreException("Attempting to merge a filter of class '{$this->GetClass()}' with a filter of class '{$oFilter->GetClass()}'");
  864. }
  865. // Translate search condition into our aliasing scheme
  866. $aAliasTranslation[$oFilter->GetClassAlias()]['*'] = $this->GetClassAlias();
  867. $this->m_aFullText = array_merge($this->m_aFullText, $oFilter->m_aFullText);
  868. foreach($oFilter->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  869. {
  870. foreach($aPointingTo as $iOperatorCode => $aFilter)
  871. {
  872. foreach($aFilter as $oExtFilter)
  873. {
  874. $this->AddCondition_PointingTo_InNamespace($oExtFilter, $sExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
  875. }
  876. }
  877. }
  878. foreach($oFilter->m_aReferencedBy as $sForeignClass => $aReferences)
  879. {
  880. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  881. {
  882. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  883. {
  884. foreach ($aFilters as $oForeignFilter)
  885. {
  886. $this->AddCondition_ReferencedBy_InNamespace($oForeignFilter, $sForeignExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
  887. }
  888. }
  889. }
  890. }
  891. }
  892. public function GetCriteria() {return $this->m_oSearchCondition;}
  893. public function GetCriteria_FullText() {return $this->m_aFullText;}
  894. protected function GetCriteria_PointingTo($sKeyAttCode = "")
  895. {
  896. if (empty($sKeyAttCode))
  897. {
  898. return $this->m_aPointingTo;
  899. }
  900. if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) return array();
  901. return $this->m_aPointingTo[$sKeyAttCode];
  902. }
  903. protected function GetCriteria_ReferencedBy()
  904. {
  905. return $this->m_aReferencedBy;
  906. }
  907. public function SetInternalParams($aParams)
  908. {
  909. return $this->m_aParams = $aParams;
  910. }
  911. public function GetInternalParams()
  912. {
  913. return $this->m_aParams;
  914. }
  915. public function GetQueryParams($bExcludeMagicParams = true)
  916. {
  917. $aParams = array();
  918. $this->m_oSearchCondition->Render($aParams, true);
  919. if ($bExcludeMagicParams)
  920. {
  921. $aRet = array();
  922. // Make the list of acceptable arguments... could be factorized with run_query, into oSearch->GetQueryParams($bExclude magic params)
  923. $aNakedMagicArguments = array();
  924. foreach (MetaModel::PrepareQueryArguments(array()) as $sArgName => $value)
  925. {
  926. $iPos = strpos($sArgName, '->object()');
  927. if ($iPos === false)
  928. {
  929. $aNakedMagicArguments[$sArgName] = $value;
  930. }
  931. else
  932. {
  933. $aNakedMagicArguments[substr($sArgName, 0, $iPos)] = true;
  934. }
  935. }
  936. foreach ($aParams as $sParam => $foo)
  937. {
  938. $iPos = strpos($sParam, '->');
  939. if ($iPos === false)
  940. {
  941. $sRefName = $sParam;
  942. }
  943. else
  944. {
  945. $sRefName = substr($sParam, 0, $iPos);
  946. }
  947. if (!array_key_exists($sRefName, $aNakedMagicArguments))
  948. {
  949. $aRet[$sParam] = $foo;
  950. }
  951. }
  952. }
  953. return $aRet;
  954. }
  955. public function ListConstantFields()
  956. {
  957. return $this->m_oSearchCondition->ListConstantFields();
  958. }
  959. /**
  960. * Turn the parameters (:xxx) into scalar values in order to easily
  961. * serialize a search
  962. */
  963. public function ApplyParameters($aArgs)
  964. {
  965. return $this->m_oSearchCondition->ApplyParameters(array_merge($this->m_aParams, $aArgs));
  966. }
  967. public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false)
  968. {
  969. // Currently unused, but could be useful later
  970. $bRetrofitParams = false;
  971. if ($bDevelopParams)
  972. {
  973. if (is_null($aContextParams))
  974. {
  975. $aParams = array_merge($this->m_aParams);
  976. }
  977. else
  978. {
  979. $aParams = array_merge($aContextParams, $this->m_aParams);
  980. }
  981. $aParams = MetaModel::PrepareQueryArguments($aParams);
  982. }
  983. else
  984. {
  985. // Leave it as is, the rendering will be made with parameters in clear
  986. $aParams = null;
  987. }
  988. $aSelectedAliases = array();
  989. foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
  990. {
  991. $aSelectedAliases[] = '`' . $sAlias . '`';
  992. }
  993. $sSelectedClasses = implode(', ', $aSelectedAliases);
  994. $sRes = 'SELECT '.$sSelectedClasses.' FROM';
  995. $sRes .= ' ' . $this->GetFirstJoinedClass() . ' AS `' . $this->GetFirstJoinedClassAlias() . '`';
  996. $sRes .= $this->ToOQL_Joins();
  997. $sRes .= " WHERE ".$this->m_oSearchCondition->Render($aParams, $bRetrofitParams);
  998. // Temporary: add more info about other conditions, necessary to avoid strange behaviors with the cache
  999. foreach($this->m_aFullText as $sFullText)
  1000. {
  1001. $sRes .= " AND MATCHES '$sFullText'";
  1002. }
  1003. if ($bWithAllowAllFlag && $this->m_bAllowAllData)
  1004. {
  1005. $sRes .= " ALLOW ALL DATA";
  1006. }
  1007. return $sRes;
  1008. }
  1009. protected function OperatorCodeToOQL($iOperatorCode)
  1010. {
  1011. switch($iOperatorCode)
  1012. {
  1013. case TREE_OPERATOR_EQUALS:
  1014. $sOperator = ' = ';
  1015. break;
  1016. case TREE_OPERATOR_BELOW:
  1017. $sOperator = ' BELOW ';
  1018. break;
  1019. case TREE_OPERATOR_BELOW_STRICT:
  1020. $sOperator = ' BELOW STRICT ';
  1021. break;
  1022. case TREE_OPERATOR_NOT_BELOW:
  1023. $sOperator = ' NOT BELOW ';
  1024. break;
  1025. case TREE_OPERATOR_NOT_BELOW_STRICT:
  1026. $sOperator = ' NOT BELOW STRICT ';
  1027. break;
  1028. case TREE_OPERATOR_ABOVE:
  1029. $sOperator = ' ABOVE ';
  1030. break;
  1031. case TREE_OPERATOR_ABOVE_STRICT:
  1032. $sOperator = ' ABOVE STRICT ';
  1033. break;
  1034. case TREE_OPERATOR_NOT_ABOVE:
  1035. $sOperator = ' NOT ABOVE ';
  1036. break;
  1037. case TREE_OPERATOR_NOT_ABOVE_STRICT:
  1038. $sOperator = ' NOT ABOVE STRICT ';
  1039. break;
  1040. }
  1041. return $sOperator;
  1042. }
  1043. protected function ToOQL_Joins()
  1044. {
  1045. $sRes = '';
  1046. foreach($this->m_aPointingTo as $sExtKey => $aPointingTo)
  1047. {
  1048. foreach($aPointingTo as $iOperatorCode => $aFilter)
  1049. {
  1050. $sOperator = $this->OperatorCodeToOQL($iOperatorCode);
  1051. foreach($aFilter as $oFilter)
  1052. {
  1053. $sRes .= ' JOIN ' . $oFilter->GetFirstJoinedClass() . ' AS `' . $oFilter->GetFirstJoinedClassAlias() . '` ON `' . $this->GetFirstJoinedClassAlias() . '`.' . $sExtKey . $sOperator . '`' . $oFilter->GetFirstJoinedClassAlias() . '`.id';
  1054. $sRes .= $oFilter->ToOQL_Joins();
  1055. }
  1056. }
  1057. }
  1058. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  1059. {
  1060. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  1061. {
  1062. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  1063. {
  1064. $sOperator = $this->OperatorCodeToOQL($iOperatorCode);
  1065. foreach ($aFilters as $oForeignFilter)
  1066. {
  1067. $sRes .= ' JOIN ' . $oForeignFilter->GetFirstJoinedClass() . ' AS `' . $oForeignFilter->GetFirstJoinedClassAlias() . '` ON `' . $oForeignFilter->GetFirstJoinedClassAlias() . '`.' . $sForeignExtKeyAttCode . $sOperator . '`' . $this->GetFirstJoinedClassAlias() . '`.id';
  1068. $sRes .= $oForeignFilter->ToOQL_Joins();
  1069. }
  1070. }
  1071. }
  1072. }
  1073. return $sRes;
  1074. }
  1075. protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases)
  1076. {
  1077. if ($oExpression instanceof BinaryOqlExpression)
  1078. {
  1079. $sOperator = $oExpression->GetOperator();
  1080. $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
  1081. $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
  1082. return new BinaryExpression($oLeft, $sOperator, $oRight);
  1083. }
  1084. elseif ($oExpression instanceof FieldOqlExpression)
  1085. {
  1086. $sClassAlias = $oExpression->GetParent();
  1087. $sFltCode = $oExpression->GetName();
  1088. if (empty($sClassAlias))
  1089. {
  1090. // Need to find the right alias
  1091. // Build an array of field => array of aliases
  1092. $aFieldClasses = array();
  1093. foreach($aClassAliases as $sAlias => $sReal)
  1094. {
  1095. foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode)
  1096. {
  1097. $aFieldClasses[$sAnFltCode][] = $sAlias;
  1098. }
  1099. }
  1100. $sClassAlias = $aFieldClasses[$sFltCode][0];
  1101. }
  1102. return new FieldExpression($sFltCode, $sClassAlias);
  1103. }
  1104. elseif ($oExpression instanceof VariableOqlExpression)
  1105. {
  1106. return new VariableExpression($oExpression->GetName());
  1107. }
  1108. elseif ($oExpression instanceof TrueOqlExpression)
  1109. {
  1110. return new TrueExpression;
  1111. }
  1112. elseif ($oExpression instanceof ScalarOqlExpression)
  1113. {
  1114. return new ScalarExpression($oExpression->GetValue());
  1115. }
  1116. elseif ($oExpression instanceof ListOqlExpression)
  1117. {
  1118. $aItems = array();
  1119. foreach ($oExpression->GetItems() as $oItemExpression)
  1120. {
  1121. $aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases);
  1122. }
  1123. return new ListExpression($aItems);
  1124. }
  1125. elseif ($oExpression instanceof FunctionOqlExpression)
  1126. {
  1127. $aArgs = array();
  1128. foreach ($oExpression->GetArgs() as $oArgExpression)
  1129. {
  1130. $aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases);
  1131. }
  1132. return new FunctionExpression($oExpression->GetVerb(), $aArgs);
  1133. }
  1134. elseif ($oExpression instanceof IntervalOqlExpression)
  1135. {
  1136. return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit());
  1137. }
  1138. else
  1139. {
  1140. throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery));
  1141. }
  1142. }
  1143. public function InitFromOqlQuery(OqlQuery $oOqlQuery, $sQuery)
  1144. {
  1145. $oModelReflection = new ModelReflectionRuntime();
  1146. $sClass = $oOqlQuery->GetClass($oModelReflection);
  1147. $sClassAlias = $oOqlQuery->GetClassAlias();
  1148. $aAliases = array($sClassAlias => $sClass);
  1149. // Note: the condition must be built here, it may be altered later on when optimizing some joins
  1150. $oConditionTree = $oOqlQuery->GetCondition();
  1151. if ($oConditionTree instanceof Expression)
  1152. {
  1153. $aRawAliases = array($sClassAlias => $sClass);
  1154. $aJoinSpecs = $oOqlQuery->GetJoins();
  1155. if (is_array($aJoinSpecs))
  1156. {
  1157. foreach ($aJoinSpecs as $oJoinSpec)
  1158. {
  1159. $aRawAliases[$oJoinSpec->GetClassAlias()] = $oJoinSpec->GetClass();
  1160. }
  1161. }
  1162. $this->m_oSearchCondition = $this->OQLExpressionToCondition($sQuery, $oConditionTree, $aRawAliases);
  1163. }
  1164. // Maintain an array of filters, because the flat list is in fact referring to a tree
  1165. // And this will be an easy way to dispatch the conditions
  1166. // $this will be referenced by the other filters, or the other way around...
  1167. $aJoinItems = array($sClassAlias => $this);
  1168. $aJoinSpecs = $oOqlQuery->GetJoins();
  1169. if (is_array($aJoinSpecs))
  1170. {
  1171. $aAliasTranslation = array();
  1172. foreach ($aJoinSpecs as $oJoinSpec)
  1173. {
  1174. $sJoinClass = $oJoinSpec->GetClass();
  1175. $sJoinClassAlias = $oJoinSpec->GetClassAlias();
  1176. if (isset($aAliasTranslation[$sJoinClassAlias]['*']))
  1177. {
  1178. $sJoinClassAlias = $aAliasTranslation[$sJoinClassAlias]['*'];
  1179. }
  1180. // Assumption: ext key on the left only !!!
  1181. // normalization should take care of this
  1182. $oLeftField = $oJoinSpec->GetLeftField();
  1183. $sFromClass = $oLeftField->GetParent();
  1184. if (isset($aAliasTranslation[$sFromClass]['*']))
  1185. {
  1186. $sFromClass = $aAliasTranslation[$sFromClass]['*'];
  1187. }
  1188. $sExtKeyAttCode = $oLeftField->GetName();
  1189. $oRightField = $oJoinSpec->GetRightField();
  1190. $sToClass = $oRightField->GetParent();
  1191. if (isset($aAliasTranslation[$sToClass]['*']))
  1192. {
  1193. $sToClass = $aAliasTranslation[$sToClass]['*'];
  1194. }
  1195. $aAliases[$sJoinClassAlias] = $sJoinClass;
  1196. $aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias);
  1197. $sOperator = $oJoinSpec->GetOperator();
  1198. switch($sOperator)
  1199. {
  1200. case '=':
  1201. default:
  1202. $iOperatorCode = TREE_OPERATOR_EQUALS;
  1203. break;
  1204. case 'BELOW':
  1205. $iOperatorCode = TREE_OPERATOR_BELOW;
  1206. break;
  1207. case 'BELOW_STRICT':
  1208. $iOperatorCode = TREE_OPERATOR_BELOW_STRICT;
  1209. break;
  1210. case 'NOT_BELOW':
  1211. $iOperatorCode = TREE_OPERATOR_NOT_BELOW;
  1212. break;
  1213. case 'NOT_BELOW_STRICT':
  1214. $iOperatorCode = TREE_OPERATOR_NOT_BELOW_STRICT;
  1215. break;
  1216. case 'ABOVE':
  1217. $iOperatorCode = TREE_OPERATOR_ABOVE;
  1218. break;
  1219. case 'ABOVE_STRICT':
  1220. $iOperatorCode = TREE_OPERATOR_ABOVE_STRICT;
  1221. break;
  1222. case 'NOT_ABOVE':
  1223. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE;
  1224. break;
  1225. case 'NOT_ABOVE_STRICT':
  1226. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE_STRICT;
  1227. break;
  1228. }
  1229. if ($sFromClass == $sJoinClassAlias)
  1230. {
  1231. $oReceiver = $aJoinItems[$sToClass];
  1232. $oNewComer = $aJoinItems[$sFromClass];
  1233. $oReceiver->AddCondition_ReferencedBy_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
  1234. }
  1235. else
  1236. {
  1237. $oReceiver = $aJoinItems[$sFromClass];
  1238. $oNewComer = $aJoinItems[$sToClass];
  1239. $oReceiver->AddCondition_PointingTo_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
  1240. }
  1241. }
  1242. $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false /* leave unresolved fields */);
  1243. }
  1244. // Check and prepare the select information
  1245. $this->m_aSelectedClasses = array();
  1246. foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails)
  1247. {
  1248. $sClassToSelect = $oClassDetails->GetValue();
  1249. $this->m_aSelectedClasses[$sClassToSelect] = $aAliases[$sClassToSelect];
  1250. }
  1251. $this->m_aClasses = $aAliases;
  1252. }
  1253. ////////////////////////////////////////////////////////////////////////////
  1254. //
  1255. // Construction of the SQL queries
  1256. //
  1257. ////////////////////////////////////////////////////////////////////////////
  1258. public function MakeDeleteQuery($aArgs = array())
  1259. {
  1260. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  1261. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  1262. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, null, array());
  1263. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  1264. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  1265. $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams());
  1266. return $oSQLQuery->RenderDelete($aScalarArgs);
  1267. }
  1268. public function MakeUpdateQuery($aValues, $aArgs = array())
  1269. {
  1270. // $aValues is an array of $sAttCode => $value
  1271. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  1272. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  1273. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, null, $aValues);
  1274. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  1275. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  1276. $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams());
  1277. return $oSQLQuery->RenderUpdate($aScalarArgs);
  1278. }
  1279. public function GetSQLQueryStructure($aAttToLoad, $bGetCount, $aGroupByExpr = null, $aSelectedClasses = null)
  1280. {
  1281. // Hide objects that are not visible to the current user
  1282. //
  1283. $oSearch = $this;
  1284. if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered())
  1285. {
  1286. $oVisibleObjects = UserRights::GetSelectFilter($this->GetClass(), $this->GetModifierProperties('UserRightsGetSelectFilter'));
  1287. if ($oVisibleObjects === false)
  1288. {
  1289. // Make sure this is a valid search object, saying NO for all
  1290. $oVisibleObjects = DBObjectSearch::FromEmptySet($this->GetClass());
  1291. }
  1292. if (is_object($oVisibleObjects))
  1293. {
  1294. $oVisibleObjects->AllowAllData();
  1295. $oSearch = $this->Intersect($oVisibleObjects);
  1296. $oSearch->SetDataFiltered();
  1297. }
  1298. else
  1299. {
  1300. // should be true at this point, meaning that no additional filtering
  1301. // is required
  1302. }
  1303. }
  1304. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  1305. //
  1306. $aModifierProperties = MetaModel::MakeModifierProperties($oSearch);
  1307. // Create a unique cache id
  1308. //
  1309. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  1310. {
  1311. // Need to identify the query
  1312. $sOqlQuery = $oSearch->ToOql(false, null, true);
  1313. if (count($aModifierProperties))
  1314. {
  1315. array_multisort($aModifierProperties);
  1316. $sModifierProperties = json_encode($aModifierProperties);
  1317. }
  1318. else
  1319. {
  1320. $sModifierProperties = '';
  1321. }
  1322. $sRawId = $sOqlQuery.$sModifierProperties;
  1323. if (!is_null($aAttToLoad))
  1324. {
  1325. $sRawId .= json_encode($aAttToLoad);
  1326. }
  1327. if (!is_null($aGroupByExpr))
  1328. {
  1329. foreach($aGroupByExpr as $sAlias => $oExpr)
  1330. {
  1331. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  1332. }
  1333. }
  1334. $sRawId .= $bGetCount;
  1335. if (is_array($aSelectedClasses))
  1336. {
  1337. $sRawId .= implode(',', $aSelectedClasses); // Unions may alter the list of selected columns
  1338. }
  1339. $sRawId .= $oSearch->GetArchiveMode() ? '--arch' : '';
  1340. $sOqlId = md5($sRawId);
  1341. }
  1342. else
  1343. {
  1344. $sOqlQuery = "SELECTING... ".$oSearch->GetClass();
  1345. $sOqlId = "query id ? n/a";
  1346. }
  1347. // Query caching
  1348. //
  1349. if (self::$m_bQueryCacheEnabled)
  1350. {
  1351. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  1352. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  1353. // to use a hash (like md5) of the string as the key !
  1354. //
  1355. // Example of two queries that were found as similar by the hash array:
  1356. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTO' AND CustomerContract.customer_id = 2
  1357. // and
  1358. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2
  1359. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  1360. //
  1361. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  1362. {
  1363. // hit!
  1364. $oSQLQuery = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  1365. // Note: cloning is not enough because the subtree is made of objects
  1366. }
  1367. elseif (self::$m_bUseAPCCache)
  1368. {
  1369. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  1370. //
  1371. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  1372. $oKPI = new ExecutionKPI();
  1373. $result = apc_fetch($sOqlAPCCacheId);
  1374. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  1375. if (is_object($result))
  1376. {
  1377. $oSQLQuery = $result;
  1378. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery;
  1379. }
  1380. }
  1381. }
  1382. if (!isset($oSQLQuery))
  1383. {
  1384. $oKPI = new ExecutionKPI();
  1385. $oSQLQuery = $oSearch->BuildSQLQueryStruct($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr, $aSelectedClasses);
  1386. $oKPI->ComputeStats('BuildSQLQueryStruct', $sOqlQuery);
  1387. if (self::$m_bQueryCacheEnabled)
  1388. {
  1389. if (self::$m_bUseAPCCache)
  1390. {
  1391. $oKPI = new ExecutionKPI();
  1392. apc_store($sOqlAPCCacheId, $oSQLQuery, self::$m_iQueryCacheTTL);
  1393. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  1394. }
  1395. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery->DeepClone();
  1396. }
  1397. }
  1398. return $oSQLQuery;
  1399. }
  1400. protected function BuildSQLQueryStruct($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr = null, $aSelectedClasses = null)
  1401. {
  1402. $oBuild = new QueryBuilderContext($this, $aModifierProperties, $aGroupByExpr, $aSelectedClasses);
  1403. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, $aAttToLoad, array());
  1404. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  1405. if ($aGroupByExpr)
  1406. {
  1407. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  1408. $oSQLQuery->SetGroupBy($aCols);
  1409. $oSQLQuery->SetSelect($aCols);
  1410. }
  1411. else
  1412. {
  1413. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  1414. }
  1415. $aMandatoryTables = null;
  1416. if (self::$m_bOptimizeQueries)
  1417. {
  1418. if ($bGetCount)
  1419. {
  1420. // Simplify the query if just getting the count
  1421. $oSQLQuery->SetSelect(array());
  1422. }
  1423. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  1424. $oSQLQuery->OptimizeJoins($aMandatoryTables);
  1425. }
  1426. // Filter tables as late as possible: do not interfere with the optimization process
  1427. foreach ($oBuild->GetFilteredTables() as $sTableAlias => $aConditions)
  1428. {
  1429. if ($aMandatoryTables && array_key_exists($sTableAlias, $aMandatoryTables))
  1430. {
  1431. foreach ($aConditions as $oCondition)
  1432. {
  1433. $oSQLQuery->AddCondition($oCondition);
  1434. }
  1435. }
  1436. }
  1437. return $oSQLQuery;
  1438. }
  1439. protected function MakeSQLObjectQuery(&$oBuild, $aAttToLoad = null, $aValues = array())
  1440. {
  1441. // Note: query class might be different than the class of the filter
  1442. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1443. $sClass = $this->GetFirstJoinedClass();
  1444. $sClassAlias = $this->GetFirstJoinedClassAlias();
  1445. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  1446. self::DbgTrace("Entering: ".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1447. $sRootClass = MetaModel::GetRootClass($sClass);
  1448. $sKeyField = MetaModel::DBGetKey($sClass);
  1449. if ($bIsOnQueriedClass)
  1450. {
  1451. // default to the whole list of attributes + the very std id/finalclass
  1452. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  1453. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  1454. {
  1455. $sSelectedClass = $oBuild->GetSelectedClass($sClassAlias);
  1456. $aAttList = MetaModel::ListAttributeDefs($sSelectedClass);
  1457. }
  1458. else
  1459. {
  1460. $aAttList = $aAttToLoad[$sClassAlias];
  1461. }
  1462. foreach ($aAttList as $sAttCode => $oAttDef)
  1463. {
  1464. if (!$oAttDef->IsScalar()) continue;
  1465. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  1466. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1467. {
  1468. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  1469. }
  1470. }
  1471. // Transform the full text condition into additional condition expression
  1472. $aFullText = $this->GetCriteria_FullText();
  1473. if (count($aFullText) > 0)
  1474. {
  1475. $aFullTextFields = array();
  1476. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1477. {
  1478. if (!$oAttDef->IsScalar()) continue;
  1479. if ($oAttDef->IsExternalKey()) continue;
  1480. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  1481. }
  1482. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  1483. foreach($aFullText as $sFTNeedle)
  1484. {
  1485. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  1486. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  1487. }
  1488. }
  1489. }
  1490. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1491. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  1492. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  1493. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  1494. // Compute a clear view of required joins (from the current class)
  1495. // Build the list of external keys:
  1496. // -> ext keys required by an explicit join
  1497. // -> ext keys mentionned in a 'pointing to' condition
  1498. // -> ext keys required for an external field
  1499. // -> ext keys required for a friendly name
  1500. //
  1501. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1502. //
  1503. // Optimization: could be partially computed once for all (cached) ?
  1504. //
  1505. if ($bIsOnQueriedClass)
  1506. {
  1507. // Get all Ext keys for the queried class (??)
  1508. foreach(MetaModel::GetKeysList($sClass) as $sKeyAttCode)
  1509. {
  1510. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1511. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1512. }
  1513. }
  1514. // Get all Ext keys used by the filter
  1515. foreach ($this->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  1516. {
  1517. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1518. {
  1519. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1520. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1521. }
  1522. }
  1523. $aFNJoinAlias = array(); // array of (subclass => alias)
  1524. foreach ($aExpectedAtts as $sExpectedAttCode => $oExpression)
  1525. {
  1526. if (!MetaModel::IsValidAttCode($sClass, $sExpectedAttCode)) continue;
  1527. $oAttDef = MetaModel::GetAttributeDef($sClass, $sExpectedAttCode);
  1528. if ($oAttDef->IsBasedOnOQLExpression())
  1529. {
  1530. // To optimize: detect a restriction on child classes in the condition expression
  1531. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  1532. $oExpression = static::GetPolymorphicExpression($sClass, $sExpectedAttCode);
  1533. $aRequiredFields = array();
  1534. $oExpression->GetUnresolvedFields('', $aRequiredFields);
  1535. $aTranslateFields = array();
  1536. foreach($aRequiredFields as $sSubClass => $aFields)
  1537. {
  1538. foreach($aFields as $sAttCode => $oField)
  1539. {
  1540. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1541. if ($oAttDef->IsExternalKey())
  1542. {
  1543. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1544. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  1545. }
  1546. elseif ($oAttDef->IsExternalField())
  1547. {
  1548. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1549. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sKeyAttCode);
  1550. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  1551. }
  1552. else
  1553. {
  1554. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1555. }
  1556. if (MetaModel::IsParentClass($sClassOfAttribute, $sClass))
  1557. {
  1558. // The attribute is part of the standard query
  1559. //
  1560. $sAliasForAttribute = $sClassAlias;
  1561. }
  1562. else
  1563. {
  1564. // The attribute will be available from an additional outer join
  1565. // For each subclass (table) one single join is enough
  1566. //
  1567. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  1568. {
  1569. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  1570. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  1571. }
  1572. else
  1573. {
  1574. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  1575. }
  1576. }
  1577. $aTranslateFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  1578. }
  1579. }
  1580. $oExpression = $oExpression->Translate($aTranslateFields, false);
  1581. $aTranslateNow = array();
  1582. $aTranslateNow[$sClassAlias][$sExpectedAttCode] = $oExpression;
  1583. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1584. }
  1585. }
  1586. // Add the ext fields used in the select (eventually adds an external key)
  1587. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1588. {
  1589. if ($oAttDef->IsExternalField())
  1590. {
  1591. if (array_key_exists($sAttCode, $aExpectedAtts))
  1592. {
  1593. // Add the external attribute
  1594. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1595. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1596. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1597. }
  1598. }
  1599. }
  1600. // First query built upon on the leaf (ie current) class
  1601. //
  1602. self::DbgTrace("Main (=leaf) class, call MakeSQLObjectQuerySingleTable()");
  1603. if (MetaModel::HasTable($sClass))
  1604. {
  1605. $oSelectBase = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sClass, $aExtKeys, $aValues);
  1606. }
  1607. else
  1608. {
  1609. $oSelectBase = null;
  1610. // As the join will not filter on the expected classes, we have to specify it explicitely
  1611. $sExpectedClasses = implode("', '", MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1612. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1613. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  1614. }
  1615. // Then we join the queries of the eventual parent classes (compound model)
  1616. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1617. {
  1618. if (!MetaModel::HasTable($sParentClass)) continue;
  1619. self::DbgTrace("Parent class: $sParentClass... let's call MakeSQLObjectQuerySingleTable()");
  1620. $oSelectParentTable = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sParentClass, $aExtKeys, $aValues);
  1621. if (is_null($oSelectBase))
  1622. {
  1623. $oSelectBase = $oSelectParentTable;
  1624. }
  1625. else
  1626. {
  1627. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, MetaModel::DBGetKey($sParentClass));
  1628. }
  1629. }
  1630. // Filter on objects referencing me
  1631. //
  1632. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  1633. {
  1634. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  1635. {
  1636. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  1637. {
  1638. foreach ($aFilters as $oForeignFilter)
  1639. {
  1640. $oForeignKeyAttDef = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  1641. self::DbgTrace("Referenced by foreign key: $sForeignExtKeyAttCode... let's call MakeSQLObjectQuery()");
  1642. //self::DbgTrace($oForeignFilter);
  1643. //self::DbgTrace($oForeignFilter->ToOQL());
  1644. //self::DbgTrace($oSelectForeign);
  1645. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1646. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1647. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignExtKeyAttCode, $sForeignClassAlias));
  1648. if ($oForeignKeyAttDef instanceof AttributeObjectKey)
  1649. {
  1650. $sClassAttCode = $oForeignKeyAttDef->Get('class_attcode');
  1651. // Add the condition: `$sForeignClassAlias`.$sClassAttCode IN (subclasses of $sClass')
  1652. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1653. $oClassExpr = new FieldExpression($sClassAttCode, $sForeignClassAlias);
  1654. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1655. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1656. }
  1657. $oSelectForeign = $oForeignFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1658. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1659. $sForeignKeyTable = $oJoinExpr->GetParent();
  1660. $sForeignKeyColumn = $oJoinExpr->GetName();
  1661. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  1662. {
  1663. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1664. }
  1665. else
  1666. {
  1667. // Hierarchical key
  1668. $KeyLeft = $oForeignKeyAttDef->GetSQLLeft();
  1669. $KeyRight = $oForeignKeyAttDef->GetSQLRight();
  1670. $oSelectBase->AddInnerJoinTree($oSelectForeign, $KeyLeft, $KeyRight, $KeyLeft, $KeyRight, $sForeignKeyTable, $iOperatorCode, true);
  1671. }
  1672. }
  1673. }
  1674. }
  1675. }
  1676. // Additional JOINS for Friendly names
  1677. //
  1678. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  1679. {
  1680. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  1681. $oSelectFN = $oSubClassFilter->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sSubClass, $aExtKeys, array());
  1682. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, MetaModel::DBGetKey($sSubClass));
  1683. }
  1684. // That's all... cross fingers and we'll get some working query
  1685. //MyHelpers::var_dump_html($oSelectBase, true);
  1686. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1687. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1688. return $oSelectBase;
  1689. }
  1690. protected function MakeSQLObjectQuerySingleTable(&$oBuild, $aAttToLoad, $sTableClass, $aExtKeys, $aValues)
  1691. {
  1692. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1693. // Prepare the query for a single table (compound objects)
  1694. // Ignores the items (attributes/filters) that are not on the target table
  1695. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1696. //
  1697. // Returns an SQLQuery
  1698. //
  1699. $sTargetClass = $this->GetFirstJoinedClass();
  1700. $sTargetAlias = $this->GetFirstJoinedClassAlias();
  1701. $sTable = MetaModel::DBGetTable($sTableClass);
  1702. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  1703. $aTranslation = array();
  1704. $aExpectedAtts = array();
  1705. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  1706. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  1707. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1708. // 1 - SELECT and UPDATE
  1709. //
  1710. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1711. //
  1712. $aUpdateValues = array();
  1713. // 1/a - Get the key and friendly name
  1714. //
  1715. // We need one pkey to be the key, let's take the first one available
  1716. $oSelectedIdField = null;
  1717. $oIdField = new FieldExpressionResolved(MetaModel::DBGetKey($sTableClass), $sTableAlias);
  1718. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  1719. if ($bIsOnQueriedClass)
  1720. {
  1721. // Add this field to the list of queried fields (required for the COUNT to work fine)
  1722. $oSelectedIdField = $oIdField;
  1723. }
  1724. // 1/b - Get the other attributes
  1725. //
  1726. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1727. {
  1728. // Skip this attribute if not defined in this table
  1729. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1730. // Skip this attribute if not made of SQL columns
  1731. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1732. // Update...
  1733. //
  1734. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1735. {
  1736. assert ($oAttDef->IsBasedOnDBColumns());
  1737. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1738. {
  1739. $aUpdateValues[$sColumn] = $sValue;
  1740. }
  1741. }
  1742. }
  1743. // 2 - The SQL query, for this table only
  1744. //
  1745. $oSelectBase = new SQLObjectQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  1746. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  1747. //
  1748. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1749. {
  1750. // Skip this attribute if not defined in this table
  1751. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1752. // Select...
  1753. //
  1754. if ($oAttDef->IsExternalField())
  1755. {
  1756. // skip, this will be handled in the joined tables (done hereabove)
  1757. }
  1758. else
  1759. {
  1760. // standard field, or external key
  1761. // add it to the output
  1762. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1763. {
  1764. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  1765. {
  1766. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1767. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  1768. {
  1769. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  1770. }
  1771. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  1772. }
  1773. }
  1774. }
  1775. }
  1776. // 4 - The external keys -> joins...
  1777. //
  1778. $aAllPointingTo = $this->GetCriteria_PointingTo();
  1779. if (array_key_exists($sTableClass, $aExtKeys))
  1780. {
  1781. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1782. {
  1783. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1784. $aPointingTo = $this->GetCriteria_PointingTo($sKeyAttCode);
  1785. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1786. {
  1787. // The join was not explicitely defined in the filter,
  1788. // we need to do it now
  1789. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1790. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1791. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1792. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  1793. }
  1794. }
  1795. }
  1796. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  1797. {
  1798. foreach($aPointingTo as $iOperatorCode => $aFilter)
  1799. {
  1800. foreach($aFilter as $oExtFilter)
  1801. {
  1802. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  1803. // The aliases should not conflict because normalization occured while building the filter
  1804. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1805. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1806. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1807. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1808. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  1809. {
  1810. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  1811. {
  1812. // Specify expected attributes for the target class query
  1813. // ... and use the current alias !
  1814. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  1815. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  1816. {
  1817. if ($oAtt->IsFriendlyName())
  1818. {
  1819. // Note: for a given ext key, there is one single attribute "friendly name"
  1820. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  1821. }
  1822. else
  1823. {
  1824. $sExtAttCode = $oAtt->GetExtAttCode();
  1825. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1826. $oRemoteAttDef = MetaModel::GetAttributeDef($sKeyClass, $sExtAttCode);
  1827. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColId => $sRemoteAttExpr)
  1828. {
  1829. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  1830. }
  1831. }
  1832. }
  1833. if ($oKeyAttDef instanceof AttributeObjectKey)
  1834. {
  1835. // Add the condition: `$sTargetAlias`.$sClassAttCode IN (subclasses of $sKeyClass')
  1836. $sClassAttCode = $oKeyAttDef->Get('class_attcode');
  1837. $oClassAttDef = MetaModel::GetAttributeDef($sTargetClass, $sClassAttCode);
  1838. foreach ($oClassAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1839. {
  1840. $aTranslateNow[$sTargetAlias][$sClassAttCode.$sColId] = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1841. }
  1842. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sKeyClass, ENUM_CHILD_CLASSES_ALL));
  1843. $oClassExpr = new FieldExpression($sClassAttCode, $sTargetAlias);
  1844. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1845. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1846. }
  1847. // Translate prior to recursing
  1848. //
  1849. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1850. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeSQLObjectQuery()");
  1851. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  1852. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1853. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1854. $sExternalKeyTable = $oJoinExpr->GetParent();
  1855. $sExternalKeyField = $oJoinExpr->GetName();
  1856. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  1857. $sLocalKeyField = current($aCols); // get the first column for an external key
  1858. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1859. if ($oKeyAttDef->IsNullAllowed())
  1860. {
  1861. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1862. }
  1863. else
  1864. {
  1865. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1866. }
  1867. }
  1868. }
  1869. elseif(MetaModel::GetAttributeOrigin($sKeyClass, $sKeyAttCode) == $sTableClass)
  1870. {
  1871. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  1872. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1873. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1874. $sExternalKeyTable = $oJoinExpr->GetParent();
  1875. $sExternalKeyField = $oJoinExpr->GetName();
  1876. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  1877. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  1878. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  1879. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  1880. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  1881. }
  1882. }
  1883. }
  1884. }
  1885. // Translate the selected columns
  1886. //
  1887. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  1888. // Filter out archived records
  1889. //
  1890. if (MetaModel::IsArchivable($sTableClass))
  1891. {
  1892. if (!$oBuild->GetRootFilter()->GetArchiveMode())
  1893. {
  1894. $bIsOnJoinedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetJoinedClasses());
  1895. if ($bIsOnJoinedClass)
  1896. {
  1897. if (MetaModel::IsParentClass($sTableClass, $sTargetClass))
  1898. {
  1899. $oNotArchived = new BinaryExpression(new FieldExpressionResolved('archive_flag', $sTableAlias), '=', new ScalarExpression(0));
  1900. $oBuild->AddFilteredTable($sTableAlias, $oNotArchived);
  1901. }
  1902. }
  1903. }
  1904. }
  1905. return $oSelectBase;
  1906. }
  1907. /**
  1908. * Get the expression for the class and its subclasses (if finalclass = 'subclass' ...)
  1909. * Simplifies the final expression by grouping classes having the same expression
  1910. */
  1911. static protected function GetPolymorphicExpression($sClass, $sAttCode)
  1912. {
  1913. // 1st step - get all of the required expressions (instantiable classes)
  1914. // and group them using their OQL representation
  1915. //
  1916. $aExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes)
  1917. foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1918. {
  1919. if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) continue;
  1920. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1921. $oSubClassExp = $oAttDef->GetOQLExpression($sSubClass);
  1922. // 3rd step - position the attributes in the hierarchy of classes
  1923. //
  1924. $oSubClassExp->Browse(function($oNode) use ($sSubClass) {
  1925. if ($oNode instanceof FieldExpression)
  1926. {
  1927. $sAttCode = $oNode->GetName();
  1928. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1929. if ($oAttDef->IsExternalField())
  1930. {
  1931. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1932. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sKeyAttCode);
  1933. }
  1934. else
  1935. {
  1936. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1937. }
  1938. $sParent = MetaModel::GetAttributeOrigin($sClassOfAttribute, $oNode->GetName());
  1939. $oNode->SetParent($sParent);
  1940. }
  1941. });
  1942. $sSignature = $oSubClassExp->Render();
  1943. if (!array_key_exists($sSignature, $aExpressions))
  1944. {
  1945. $aExpressions[$sSignature] = array(
  1946. 'expression' => $oSubClassExp,
  1947. 'classes' => array(),
  1948. );
  1949. }
  1950. $aExpressions[$sSignature]['classes'][] = $sSubClass;
  1951. }
  1952. // 2nd step - build the final name expression depending on the finalclass
  1953. //
  1954. if (count($aExpressions) == 1)
  1955. {
  1956. $aExpData = reset($aExpressions);
  1957. $oExpression = $aExpData['expression'];
  1958. }
  1959. else
  1960. {
  1961. $oExpression = null;
  1962. foreach ($aExpressions as $sSignature => $aExpData)
  1963. {
  1964. $oClassListExpr = ListExpression::FromScalars($aExpData['classes']);
  1965. $oClassExpr = new FieldExpression('finalclass', $sClass);
  1966. $oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1967. if (is_null($oExpression))
  1968. {
  1969. $oExpression = $aExpData['expression'];
  1970. }
  1971. else
  1972. {
  1973. $oExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oExpression));
  1974. }
  1975. }
  1976. }
  1977. return $oExpression;
  1978. }
  1979. }