dbobjectsearch.class.php 76 KB

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