dbobjectsearch.class.php 76 KB

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