dbobjectsearch.class.php 75 KB

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