dbobjectsearch.class.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  1. <?php
  2. // Copyright (C) 2010-2015 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-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class DBObjectSearch extends DBSearch
  25. {
  26. private $m_aClasses; // queried classes (alias => class name), the first item is the class corresponding to this filter (the rest is coming from subfilters)
  27. private $m_aSelectedClasses; // selected for the output (alias => class name)
  28. private $m_oSearchCondition;
  29. private $m_aParams;
  30. private $m_aFullText;
  31. private $m_aPointingTo;
  32. private $m_aReferencedBy;
  33. public function __construct($sClass, $sClassAlias = null)
  34. {
  35. parent::__construct();
  36. if (is_null($sClassAlias)) $sClassAlias = $sClass;
  37. if(!is_string($sClass)) throw new Exception('DBObjectSearch::__construct called with a non-string parameter: $sClass = '.print_r($sClass, true));
  38. if(!MetaModel::IsValidClass($sClass)) throw new Exception('DBObjectSearch::__construct called for an invalid class: "'.$sClass.'"');
  39. $this->m_aSelectedClasses = array($sClassAlias => $sClass);
  40. $this->m_aClasses = array($sClassAlias => $sClass);
  41. $this->m_oSearchCondition = new TrueExpression;
  42. $this->m_aParams = array();
  43. $this->m_aFullText = array();
  44. $this->m_aPointingTo = array();
  45. $this->m_aReferencedBy = array();
  46. }
  47. // Create a search definition that leads to 0 result, still a valid search object
  48. static public function FromEmptySet($sClass)
  49. {
  50. $oResultFilter = new DBObjectSearch($sClass);
  51. $oResultFilter->m_oSearchCondition = new FalseExpression;
  52. return $oResultFilter;
  53. }
  54. public function GetJoinedClasses() {return $this->m_aClasses;}
  55. public function GetClassName($sAlias)
  56. {
  57. if (array_key_exists($sAlias, $this->m_aSelectedClasses))
  58. {
  59. return $this->m_aSelectedClasses[$sAlias];
  60. }
  61. else
  62. {
  63. throw new CoreException("Invalid class alias '$sAlias'");
  64. }
  65. }
  66. public function GetClass()
  67. {
  68. return reset($this->m_aSelectedClasses);
  69. }
  70. public function GetClassAlias()
  71. {
  72. reset($this->m_aSelectedClasses);
  73. return key($this->m_aSelectedClasses);
  74. }
  75. public function GetFirstJoinedClass()
  76. {
  77. return reset($this->m_aClasses);
  78. }
  79. public function GetFirstJoinedClassAlias()
  80. {
  81. reset($this->m_aClasses);
  82. return key($this->m_aClasses);
  83. }
  84. /**
  85. * Change the class (only subclasses are supported as of now, because the conditions must fit the new class)
  86. * Defaults to the first selected class (most of the time it is also the first joined class
  87. */
  88. public function ChangeClass($sNewClass, $sAlias = null)
  89. {
  90. if (is_null($sAlias))
  91. {
  92. $sAlias = $this->GetClassAlias();
  93. }
  94. else
  95. {
  96. if (!array_key_exists($sAlias, $this->m_aSelectedClasses))
  97. {
  98. // discard silently - necessary when recursing on the related nodes (see code below)
  99. return;
  100. }
  101. }
  102. $sCurrClass = $this->GetClassName($sAlias);
  103. if ($sNewClass == $sCurrClass)
  104. {
  105. // Skip silently
  106. return;
  107. }
  108. if (!MetaModel::IsParentClass($sCurrClass, $sNewClass))
  109. {
  110. throw new Exception("Could not change the search class from '$sCurrClass' to '$sNewClass'. Only child classes are permitted.");
  111. }
  112. // Change for this node
  113. //
  114. $this->m_aSelectedClasses[$sAlias] = $sNewClass;
  115. $this->m_aClasses[$sAlias] = $sNewClass;
  116. // Change for all the related node (yes, this was necessary with some queries - strange effects otherwise)
  117. //
  118. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  119. {
  120. foreach($aPointingTo as $iOperatorCode => $aFilter)
  121. {
  122. foreach($aFilter as $oExtFilter)
  123. {
  124. $oExtFilter->ChangeClass($sNewClass, $sAlias);
  125. }
  126. }
  127. }
  128. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  129. {
  130. foreach($aReferences as $sForeignExtKeyAttCode => $oForeignFilter)
  131. {
  132. $oForeignFilter->ChangeClass($sNewClass, $sAlias);
  133. }
  134. }
  135. }
  136. public function GetSelectedClasses()
  137. {
  138. return $this->m_aSelectedClasses;
  139. }
  140. /**
  141. * @param array $aSelectedClasses array of aliases
  142. * @throws CoreException
  143. */
  144. public function SetSelectedClasses($aSelectedClasses)
  145. {
  146. $this->m_aSelectedClasses = array();
  147. foreach ($aSelectedClasses as $sAlias)
  148. {
  149. if (!array_key_exists($sAlias, $this->m_aClasses))
  150. {
  151. throw new CoreException("Invalid class alias $sAlias");
  152. }
  153. $this->m_aSelectedClasses[$sAlias] = $this->m_aClasses[$sAlias];
  154. }
  155. }
  156. public function SetModifierProperty($sPluginClass, $sProperty, $value)
  157. {
  158. $this->m_aModifierProperties[$sPluginClass][$sProperty] = $value;
  159. }
  160. public function GetModifierProperties($sPluginClass)
  161. {
  162. if (array_key_exists($sPluginClass, $this->m_aModifierProperties))
  163. {
  164. return $this->m_aModifierProperties[$sPluginClass];
  165. }
  166. else
  167. {
  168. return array();
  169. }
  170. }
  171. public function IsAny()
  172. {
  173. // #@# todo - if (!$this->m_oSearchCondition->IsTrue()) return false;
  174. if (count($this->m_aFullText) > 0) return false;
  175. if (count($this->m_aPointingTo) > 0) return false;
  176. if (count($this->m_aReferencedBy) > 0) return false;
  177. return true;
  178. }
  179. protected function TransferConditionExpression($oFilter, $aTranslation)
  180. {
  181. // Prevent collisions in the parameter names by renaming them if needed
  182. foreach($this->m_aParams as $sParam => $value)
  183. {
  184. if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam]))
  185. {
  186. // Generate a new and unique name for the collinding parameter
  187. $index = 1;
  188. while(array_key_exists($sParam.$index, $oFilter->m_aParams))
  189. {
  190. $index++;
  191. }
  192. $secondValue = $oFilter->m_aParams[$sParam];
  193. $oFilter->RenameParam($sParam, $sParam.$index);
  194. unset($oFilter->m_aParams[$sParam]);
  195. $oFilter->m_aParams[$sParam.$index] = $secondValue;
  196. }
  197. }
  198. $oTranslated = $oFilter->GetCriteria()->Translate($aTranslation, false, false /* leave unresolved fields */);
  199. $this->AddConditionExpression($oTranslated);
  200. $this->m_aParams = array_merge($this->m_aParams, $oFilter->m_aParams);
  201. }
  202. protected function RenameParam($sOldName, $sNewName)
  203. {
  204. $this->m_oSearchCondition->RenameParam($sOldName, $sNewName);
  205. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  206. {
  207. foreach($aPointingTo as $iOperatorCode => $aFilter)
  208. {
  209. foreach($aFilter as $oExtFilter)
  210. {
  211. $oExtFilter->RenameParam($sOldName, $sNewName);
  212. }
  213. }
  214. }
  215. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  216. {
  217. foreach($aReferences as $sForeignExtKeyAttCode => $oForeignFilter)
  218. {
  219. $oForeignFilter->RenameParam($sOldName, $sNewName);
  220. }
  221. }
  222. }
  223. public function ResetCondition()
  224. {
  225. $this->m_oSearchCondition = new TrueExpression();
  226. // ? is that usefull/enough, do I need to rebuild the list after the subqueries ?
  227. }
  228. public function MergeConditionExpression($oExpression)
  229. {
  230. $this->m_oSearchCondition = $this->m_oSearchCondition->LogOr($oExpression);
  231. }
  232. public function AddConditionExpression($oExpression)
  233. {
  234. $this->m_oSearchCondition = $this->m_oSearchCondition->LogAnd($oExpression);
  235. }
  236. public function AddNameCondition($sName)
  237. {
  238. $oValueExpr = new ScalarExpression($sName);
  239. $oNameExpr = new FieldExpression('friendlyname', $this->GetClassAlias());
  240. $oNewCondition = new BinaryExpression($oNameExpr, '=', $oValueExpr);
  241. $this->AddConditionExpression($oNewCondition);
  242. }
  243. public function AddCondition($sFilterCode, $value, $sOpCode = null)
  244. {
  245. MyHelpers::CheckKeyInArray('filter code in class: '.$this->GetClass(), $sFilterCode, MetaModel::GetClassFilterDefs($this->GetClass()));
  246. $oFilterDef = MetaModel::GetClassFilterDef($this->GetClass(), $sFilterCode);
  247. $oField = new FieldExpression($sFilterCode, $this->GetClassAlias());
  248. if (empty($sOpCode))
  249. {
  250. if ($sFilterCode == 'id')
  251. {
  252. $sOpCode = '=';
  253. }
  254. else
  255. {
  256. $oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sFilterCode);
  257. $oNewCondition = $oAttDef->GetSmartConditionExpression($value, $oField, $this->m_aParams);
  258. $this->AddConditionExpression($oNewCondition);
  259. return;
  260. }
  261. }
  262. MyHelpers::CheckKeyInArray('operator', $sOpCode, $oFilterDef->GetOperators());
  263. // Preserve backward compatibility - quick n'dirty way to change that API semantic
  264. //
  265. switch($sOpCode)
  266. {
  267. case 'SameDay':
  268. case 'SameMonth':
  269. case 'SameYear':
  270. case 'Today':
  271. case '>|':
  272. case '<|':
  273. case '=|':
  274. throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', array('operator' => $sOpCode));
  275. break;
  276. case "IN":
  277. if (!is_array($value)) $value = array($value);
  278. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  279. $sOQLCondition = $oField->Render()." IN $sListExpr";
  280. break;
  281. case "NOTIN":
  282. if (!is_array($value)) $value = array($value);
  283. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  284. $sOQLCondition = $oField->Render()." NOT IN $sListExpr";
  285. break;
  286. case 'Contains':
  287. $this->m_aParams[$sFilterCode] = "%$value%";
  288. $sOperator = 'LIKE';
  289. break;
  290. case 'Begins with':
  291. $this->m_aParams[$sFilterCode] = "$value%";
  292. $sOperator = 'LIKE';
  293. break;
  294. case 'Finishes with':
  295. $this->m_aParams[$sFilterCode] = "%$value";
  296. $sOperator = 'LIKE';
  297. break;
  298. default:
  299. $this->m_aParams[$sFilterCode] = $value;
  300. $sOperator = $sOpCode;
  301. }
  302. switch($sOpCode)
  303. {
  304. case "IN":
  305. case "NOTIN":
  306. $oNewCondition = Expression::FromOQL($sOQLCondition);
  307. break;
  308. case 'Contains':
  309. case 'Begins with':
  310. case 'Finishes with':
  311. default:
  312. $oRightExpr = new VariableExpression($sFilterCode);
  313. $oNewCondition = new BinaryExpression($oField, $sOperator, $oRightExpr);
  314. }
  315. $this->AddConditionExpression($oNewCondition);
  316. }
  317. /**
  318. * Specify a condition on external keys or link sets
  319. * @param sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
  320. * Example: infra_list->ci_id->location_id->country
  321. * @param value The value to match (can be an array => IN(val1, val2...)
  322. * @return void
  323. */
  324. public function AddConditionAdvanced($sAttSpec, $value)
  325. {
  326. $sClass = $this->GetClass();
  327. $iPos = strpos($sAttSpec, '->');
  328. if ($iPos !== false)
  329. {
  330. $sAttCode = substr($sAttSpec, 0, $iPos);
  331. $sSubSpec = substr($sAttSpec, $iPos + 2);
  332. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  333. {
  334. throw new Exception("Invalid attribute code '$sClass/$sAttCode' in condition specification '$sAttSpec'");
  335. }
  336. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  337. if ($oAttDef->IsLinkSet())
  338. {
  339. $sTargetClass = $oAttDef->GetLinkedClass();
  340. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  341. $oNewFilter = new DBObjectSearch($sTargetClass);
  342. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  343. $this->AddCondition_ReferencedBy($oNewFilter, $sExtKeyToMe);
  344. }
  345. elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  346. {
  347. $sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE);
  348. $oNewFilter = new DBObjectSearch($sTargetClass);
  349. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  350. $this->AddCondition_PointingTo($oNewFilter, $sAttCode);
  351. }
  352. else
  353. {
  354. throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key");
  355. }
  356. }
  357. else
  358. {
  359. // $sAttSpec is an attribute code
  360. //
  361. if (is_array($value))
  362. {
  363. $oField = new FieldExpression($sAttSpec, $this->GetClass());
  364. $oListExpr = ListExpression::FromScalars($value);
  365. $oInValues = new BinaryExpression($oField, 'IN', $oListExpr);
  366. $this->AddConditionExpression($oInValues);
  367. }
  368. else
  369. {
  370. $this->AddCondition($sAttSpec, $value);
  371. }
  372. }
  373. }
  374. public function AddCondition_FullText($sFullText)
  375. {
  376. $this->m_aFullText[] = $sFullText;
  377. }
  378. protected function AddToNameSpace(&$aClassAliases, &$aAliasTranslation, $bTranslateMainAlias = true)
  379. {
  380. if ($bTranslateMainAlias)
  381. {
  382. $sOrigAlias = $this->GetFirstJoinedClassAlias();
  383. if (array_key_exists($sOrigAlias, $aClassAliases))
  384. {
  385. $sNewAlias = MetaModel::GenerateUniqueAlias($aClassAliases, $sOrigAlias, $this->GetFirstJoinedClass());
  386. if (isset($this->m_aSelectedClasses[$sOrigAlias]))
  387. {
  388. $this->m_aSelectedClasses[$sNewAlias] = $this->GetFirstJoinedClass();
  389. unset($this->m_aSelectedClasses[$sOrigAlias]);
  390. }
  391. // TEMPORARY ALGORITHM (m_aClasses is not correctly updated, it is not possible to add a subtree onto a subnode)
  392. // Replace the element at the same position (unset + set is not enough because the hash array is ordered)
  393. $aPrevList = $this->m_aClasses;
  394. $this->m_aClasses = array();
  395. foreach ($aPrevList as $sSomeAlias => $sSomeClass)
  396. {
  397. if ($sSomeAlias == $sOrigAlias)
  398. {
  399. $this->m_aClasses[$sNewAlias] = $sSomeClass; // note: GetFirstJoinedClass now returns '' !!!
  400. }
  401. else
  402. {
  403. $this->m_aClasses[$sSomeAlias] = $sSomeClass;
  404. }
  405. }
  406. // Translate the condition expression with the new alias
  407. $aAliasTranslation[$sOrigAlias]['*'] = $sNewAlias;
  408. }
  409. // add the alias into the filter aliases list
  410. $aClassAliases[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
  411. }
  412. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  413. {
  414. foreach($aPointingTo as $iOperatorCode => $aFilter)
  415. {
  416. foreach($aFilter as $oFilter)
  417. {
  418. $oFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  419. }
  420. }
  421. }
  422. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  423. {
  424. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  425. {
  426. $oForeignFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  427. }
  428. }
  429. }
  430. // Browse the tree nodes recursively
  431. //
  432. protected function GetNode($sAlias)
  433. {
  434. if ($this->GetFirstJoinedClassAlias() == $sAlias)
  435. {
  436. return $this;
  437. }
  438. else
  439. {
  440. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  441. {
  442. foreach($aPointingTo as $iOperatorCode => $aFilter)
  443. {
  444. foreach($aFilter as $oFilter)
  445. {
  446. $ret = $oFilter->GetNode($sAlias);
  447. if (is_object($ret))
  448. {
  449. return $ret;
  450. }
  451. }
  452. }
  453. }
  454. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  455. {
  456. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  457. {
  458. $ret = $oForeignFilter->GetNode($sAlias);
  459. if (is_object($ret))
  460. {
  461. return $ret;
  462. }
  463. }
  464. }
  465. }
  466. // Not found
  467. return null;
  468. }
  469. public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS)
  470. {
  471. if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode))
  472. {
  473. throw new CoreWarning("The attribute code '$sExtKeyAttCode' is not an external key of the class '{$this->GetClass()}'");
  474. }
  475. $oAttExtKey = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
  476. if(!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass()))
  477. {
  478. 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()}");
  479. }
  480. if(($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey))
  481. {
  482. throw new CoreException("The specified tree operator $iOperatorCode is not applicable to the key '{$this->GetClass()}::$sExtKeyAttCode', which is not a HierarchicalKey");
  483. }
  484. // Note: though it seems to be a good practice to clone the given source filter
  485. // (as it was done and fixed an issue in Intersect())
  486. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  487. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  488. // NO: $oFilter = $oFilter->DeepClone();
  489. // See also: Trac #639, and self::AddCondition_ReferencedBy()
  490. $aAliasTranslation = array();
  491. $res = $this->AddCondition_PointingTo_InNameSpace($oFilter, $sExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
  492. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  493. return $res;
  494. }
  495. protected function AddCondition_PointingTo_InNameSpace(DBObjectSearch $oFilter, $sExtKeyAttCode, &$aClassAliases, &$aAliasTranslation, $iOperatorCode)
  496. {
  497. // Find the node on which the new tree must be attached (most of the time it is "this")
  498. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  499. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  500. $oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode][] = $oFilter;
  501. }
  502. public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode)
  503. {
  504. $sForeignClass = $oFilter->GetClass();
  505. if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode))
  506. {
  507. throw new CoreException("The attribute code '$sForeignExtKeyAttCode' is not an external key of the class '{$sForeignClass}'");
  508. }
  509. $oAttExtKey = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  510. if(!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass()))
  511. {
  512. // à refaire en spécifique dans FromOQL
  513. 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()}");
  514. }
  515. // Note: though it seems to be a good practice to clone the given source filter
  516. // (as it was done and fixed an issue in Intersect())
  517. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  518. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  519. // NO: $oFilter = $oFilter->DeepClone();
  520. // See also: Trac #639, and self::AddCondition_PointingTo()
  521. $aAliasTranslation = array();
  522. $res = $this->AddCondition_ReferencedBy_InNameSpace($oFilter, $sForeignExtKeyAttCode, $this->m_aClasses, $aAliasTranslation);
  523. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  524. return $res;
  525. }
  526. protected function AddCondition_ReferencedBy_InNameSpace(DBSearch $oFilter, $sForeignExtKeyAttCode, &$aClassAliases, &$aAliasTranslation)
  527. {
  528. $sForeignClass = $oFilter->GetClass();
  529. // Find the node on which the new tree must be attached (most of the time it is "this")
  530. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  531. if (array_key_exists($sForeignClass, $this->m_aReferencedBy) && array_key_exists($sForeignExtKeyAttCode, $this->m_aReferencedBy[$sForeignClass]))
  532. {
  533. $oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode]->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation);
  534. }
  535. else
  536. {
  537. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  538. // #@# The condition expression found in that filter should not be used - could be another kind of structure like a join spec tree !!!!
  539. //$oNewFilter = $oFilter->DeepClone();
  540. //$oNewFilter->ResetCondition();
  541. $oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode]= $oFilter;
  542. }
  543. }
  544. public function Intersect(DBSearch $oFilter)
  545. {
  546. if ($oFilter instanceof DBUnionSearch)
  547. {
  548. // Develop!
  549. $aFilters = $oFilter->GetSearches();
  550. }
  551. else
  552. {
  553. $aFilters = array($oFilter);
  554. }
  555. $aSearches = array();
  556. foreach ($aFilters as $oRightFilter)
  557. {
  558. $oLeftFilter = $this->DeepClone();
  559. $oRightFilter = $oRightFilter->DeepClone();
  560. if ($oLeftFilter->GetClass() != $oRightFilter->GetClass())
  561. {
  562. if (MetaModel::IsParentClass($oLeftFilter->GetClass(), $oRightFilter->GetClass()))
  563. {
  564. // Specialize $oLeftFilter
  565. $oLeftFilter->ChangeClass($oRightFilter->GetClass());
  566. }
  567. elseif (MetaModel::IsParentClass($oRightFilter->GetClass(), $oLeftFilter->GetClass()))
  568. {
  569. // Specialize $oRightFilter
  570. $oRightFilter->ChangeClass($oLeftFilter->GetClass());
  571. }
  572. else
  573. {
  574. throw new CoreException("Attempting to merge a filter of class '{$oLeftFilter->GetClass()}' with a filter of class '{$oRightFilter->GetClass()}'");
  575. }
  576. }
  577. $aAliasTranslation = array();
  578. $oLeftFilter->MergeWith_InNamespace($oRightFilter, $oLeftFilter->m_aClasses, $aAliasTranslation);
  579. $oLeftFilter->TransferConditionExpression($oRightFilter, $aAliasTranslation);
  580. $aSearches[] = $oLeftFilter;
  581. }
  582. if (count($aSearches) == 1)
  583. {
  584. // return a DBObjectSearch
  585. return $aSearches[0];
  586. }
  587. else
  588. {
  589. return new DBUnionSearch($aSearches);
  590. }
  591. }
  592. protected function MergeWith_InNamespace($oFilter, &$aClassAliases, &$aAliasTranslation)
  593. {
  594. if ($this->GetClass() != $oFilter->GetClass())
  595. {
  596. throw new CoreException("Attempting to merge a filter of class '{$this->GetClass()}' with a filter of class '{$oFilter->GetClass()}'");
  597. }
  598. // Translate search condition into our aliasing scheme
  599. $aAliasTranslation[$oFilter->GetClassAlias()]['*'] = $this->GetClassAlias();
  600. $this->m_aFullText = array_merge($this->m_aFullText, $oFilter->m_aFullText);
  601. foreach($oFilter->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  602. {
  603. foreach($aPointingTo as $iOperatorCode => $aFilter)
  604. {
  605. foreach($aFilter as $oExtFilter)
  606. {
  607. $this->AddCondition_PointingTo_InNamespace($oExtFilter, $sExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
  608. }
  609. }
  610. }
  611. foreach($oFilter->m_aReferencedBy as $sForeignClass => $aReferences)
  612. {
  613. foreach($aReferences as $sForeignExtKeyAttCode => $oForeignFilter)
  614. {
  615. $this->AddCondition_ReferencedBy_InNamespace($oForeignFilter, $sForeignExtKeyAttCode, $aClassAliases, $aAliasTranslation);
  616. }
  617. }
  618. }
  619. public function GetCriteria() {return $this->m_oSearchCondition;}
  620. public function GetCriteria_FullText() {return $this->m_aFullText;}
  621. public function GetCriteria_PointingTo($sKeyAttCode = "")
  622. {
  623. if (empty($sKeyAttCode))
  624. {
  625. return $this->m_aPointingTo;
  626. }
  627. if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) return array();
  628. return $this->m_aPointingTo[$sKeyAttCode];
  629. }
  630. public function GetCriteria_ReferencedBy($sRemoteClass = "", $sForeignExtKeyAttCode = "")
  631. {
  632. if (empty($sRemoteClass))
  633. {
  634. return $this->m_aReferencedBy;
  635. }
  636. if (!array_key_exists($sRemoteClass, $this->m_aReferencedBy)) return null;
  637. if (empty($sForeignExtKeyAttCode))
  638. {
  639. return $this->m_aReferencedBy[$sRemoteClass];
  640. }
  641. if (!array_key_exists($sForeignExtKeyAttCode, $this->m_aReferencedBy[$sRemoteClass])) return null;
  642. return $this->m_aReferencedBy[$sRemoteClass][$sForeignExtKeyAttCode];
  643. }
  644. public function SetInternalParams($aParams)
  645. {
  646. return $this->m_aParams = $aParams;
  647. }
  648. public function GetInternalParams()
  649. {
  650. return $this->m_aParams;
  651. }
  652. public function GetQueryParams()
  653. {
  654. $aParams = array();
  655. $this->m_oSearchCondition->Render($aParams, true);
  656. return $aParams;
  657. }
  658. public function ListConstantFields()
  659. {
  660. return $this->m_oSearchCondition->ListConstantFields();
  661. }
  662. /**
  663. * Turn the parameters (:xxx) into scalar values in order to easily
  664. * serialize a search
  665. */
  666. public function ApplyParameters($aArgs)
  667. {
  668. return $this->m_oSearchCondition->ApplyParameters(array_merge($this->m_aParams, $aArgs));
  669. }
  670. public function ToOQL($bDevelopParams = false, $aContextParams = null)
  671. {
  672. // Currently unused, but could be useful later
  673. $bRetrofitParams = false;
  674. if ($bDevelopParams)
  675. {
  676. if (is_null($aContextParams))
  677. {
  678. $aParams = array_merge($this->m_aParams);
  679. }
  680. else
  681. {
  682. $aParams = array_merge($aContextParams, $this->m_aParams);
  683. }
  684. $aParams = MetaModel::PrepareQueryArguments($aParams);
  685. }
  686. else
  687. {
  688. // Leave it as is, the rendering will be made with parameters in clear
  689. $aParams = null;
  690. }
  691. $sSelectedClasses = implode(', ', array_keys($this->m_aSelectedClasses));
  692. $sRes = 'SELECT '.$sSelectedClasses.' FROM';
  693. $sRes .= ' '.$this->GetFirstJoinedClass().' AS '.$this->GetFirstJoinedClassAlias();
  694. $sRes .= $this->ToOQL_Joins();
  695. $sRes .= " WHERE ".$this->m_oSearchCondition->Render($aParams, $bRetrofitParams);
  696. // Temporary: add more info about other conditions, necessary to avoid strange behaviors with the cache
  697. foreach($this->m_aFullText as $sFullText)
  698. {
  699. $sRes .= " AND MATCHES '$sFullText'";
  700. }
  701. return $sRes;
  702. }
  703. protected function ToOQL_Joins()
  704. {
  705. $sRes = '';
  706. foreach($this->m_aPointingTo as $sExtKey => $aPointingTo)
  707. {
  708. foreach($aPointingTo as $iOperatorCode => $aFilter)
  709. {
  710. foreach($aFilter as $oFilter)
  711. {
  712. switch($iOperatorCode)
  713. {
  714. case TREE_OPERATOR_EQUALS:
  715. $sOperator = ' = ';
  716. break;
  717. case TREE_OPERATOR_BELOW:
  718. $sOperator = ' BELOW ';
  719. break;
  720. case TREE_OPERATOR_BELOW_STRICT:
  721. $sOperator = ' BELOW STRICT ';
  722. break;
  723. case TREE_OPERATOR_NOT_BELOW:
  724. $sOperator = ' NOT BELOW ';
  725. break;
  726. case TREE_OPERATOR_NOT_BELOW_STRICT:
  727. $sOperator = ' NOT BELOW STRICT ';
  728. break;
  729. case TREE_OPERATOR_ABOVE:
  730. $sOperator = ' ABOVE ';
  731. break;
  732. case TREE_OPERATOR_ABOVE_STRICT:
  733. $sOperator = ' ABOVE STRICT ';
  734. break;
  735. case TREE_OPERATOR_NOT_ABOVE:
  736. $sOperator = ' NOT ABOVE ';
  737. break;
  738. case TREE_OPERATOR_NOT_ABOVE_STRICT:
  739. $sOperator = ' NOT ABOVE STRICT ';
  740. break;
  741. }
  742. $sRes .= ' JOIN '.$oFilter->GetFirstJoinedClass().' AS '.$oFilter->GetFirstJoinedClassAlias().' ON '.$this->GetFirstJoinedClassAlias().'.'.$sExtKey.$sOperator.$oFilter->GetFirstJoinedClassAlias().'.id';
  743. $sRes .= $oFilter->ToOQL_Joins();
  744. }
  745. }
  746. }
  747. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  748. {
  749. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  750. {
  751. $sRes .= ' JOIN '.$oForeignFilter->GetFirstJoinedClass().' AS '.$oForeignFilter->GetFirstJoinedClassAlias().' ON '.$oForeignFilter->GetFirstJoinedClassAlias().'.'.$sForeignExtKeyAttCode.' = '.$this->GetFirstJoinedClassAlias().'.id';
  752. $sRes .= $oForeignFilter->ToOQL_Joins();
  753. }
  754. }
  755. return $sRes;
  756. }
  757. protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases)
  758. {
  759. if ($oExpression instanceof BinaryOqlExpression)
  760. {
  761. $sOperator = $oExpression->GetOperator();
  762. $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
  763. $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
  764. return new BinaryExpression($oLeft, $sOperator, $oRight);
  765. }
  766. elseif ($oExpression instanceof FieldOqlExpression)
  767. {
  768. $sClassAlias = $oExpression->GetParent();
  769. $sFltCode = $oExpression->GetName();
  770. if (empty($sClassAlias))
  771. {
  772. // Need to find the right alias
  773. // Build an array of field => array of aliases
  774. $aFieldClasses = array();
  775. foreach($aClassAliases as $sAlias => $sReal)
  776. {
  777. foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode)
  778. {
  779. $aFieldClasses[$sAnFltCode][] = $sAlias;
  780. }
  781. }
  782. $sClassAlias = $aFieldClasses[$sFltCode][0];
  783. }
  784. return new FieldExpression($sFltCode, $sClassAlias);
  785. }
  786. elseif ($oExpression instanceof VariableOqlExpression)
  787. {
  788. return new VariableExpression($oExpression->GetName());
  789. }
  790. elseif ($oExpression instanceof TrueOqlExpression)
  791. {
  792. return new TrueExpression;
  793. }
  794. elseif ($oExpression instanceof ScalarOqlExpression)
  795. {
  796. return new ScalarExpression($oExpression->GetValue());
  797. }
  798. elseif ($oExpression instanceof ListOqlExpression)
  799. {
  800. $aItems = array();
  801. foreach ($oExpression->GetItems() as $oItemExpression)
  802. {
  803. $aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases);
  804. }
  805. return new ListExpression($aItems);
  806. }
  807. elseif ($oExpression instanceof FunctionOqlExpression)
  808. {
  809. $aArgs = array();
  810. foreach ($oExpression->GetArgs() as $oArgExpression)
  811. {
  812. $aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases);
  813. }
  814. return new FunctionExpression($oExpression->GetVerb(), $aArgs);
  815. }
  816. elseif ($oExpression instanceof IntervalOqlExpression)
  817. {
  818. return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit());
  819. }
  820. else
  821. {
  822. throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery));
  823. }
  824. }
  825. public function InitFromOqlQuery(OqlQuery $oOqlQuery, $sQuery)
  826. {
  827. $oModelReflection = new ModelReflectionRuntime();
  828. $sClass = $oOqlQuery->GetClass($oModelReflection);
  829. $sClassAlias = $oOqlQuery->GetClassAlias();
  830. $aAliases = array($sClassAlias => $sClass);
  831. // Maintain an array of filters, because the flat list is in fact referring to a tree
  832. // And this will be an easy way to dispatch the conditions
  833. // $this will be referenced by the other filters, or the other way around...
  834. $aJoinItems = array($sClassAlias => $this);
  835. $aJoinSpecs = $oOqlQuery->GetJoins();
  836. if (is_array($aJoinSpecs))
  837. {
  838. foreach ($aJoinSpecs as $oJoinSpec)
  839. {
  840. $sJoinClass = $oJoinSpec->GetClass();
  841. $sJoinClassAlias = $oJoinSpec->GetClassAlias();
  842. // Assumption: ext key on the left only !!!
  843. // normalization should take care of this
  844. $oLeftField = $oJoinSpec->GetLeftField();
  845. $sFromClass = $oLeftField->GetParent();
  846. $sExtKeyAttCode = $oLeftField->GetName();
  847. $oRightField = $oJoinSpec->GetRightField();
  848. $sToClass = $oRightField->GetParent();
  849. $aAliases[$sJoinClassAlias] = $sJoinClass;
  850. $aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias);
  851. if ($sFromClass == $sJoinClassAlias)
  852. {
  853. $oReceiver = $aJoinItems[$sToClass];
  854. $oNewComer = $aJoinItems[$sFromClass];
  855. $aAliasTranslation = array();
  856. $oReceiver->AddCondition_ReferencedBy_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation);
  857. }
  858. else
  859. {
  860. $sOperator = $oJoinSpec->GetOperator();
  861. switch($sOperator)
  862. {
  863. case '=':
  864. $iOperatorCode = TREE_OPERATOR_EQUALS;
  865. break;
  866. case 'BELOW':
  867. $iOperatorCode = TREE_OPERATOR_BELOW;
  868. break;
  869. case 'BELOW_STRICT':
  870. $iOperatorCode = TREE_OPERATOR_BELOW_STRICT;
  871. break;
  872. case 'NOT_BELOW':
  873. $iOperatorCode = TREE_OPERATOR_NOT_BELOW;
  874. break;
  875. case 'NOT_BELOW_STRICT':
  876. $iOperatorCode = TREE_OPERATOR_NOT_BELOW_STRICT;
  877. break;
  878. case 'ABOVE':
  879. $iOperatorCode = TREE_OPERATOR_ABOVE;
  880. break;
  881. case 'ABOVE_STRICT':
  882. $iOperatorCode = TREE_OPERATOR_ABOVE_STRICT;
  883. break;
  884. case 'NOT_ABOVE':
  885. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE;
  886. break;
  887. case 'NOT_ABOVE_STRICT':
  888. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE_STRICT;
  889. break;
  890. }
  891. $oReceiver = $aJoinItems[$sFromClass];
  892. $oNewComer = $aJoinItems[$sToClass];
  893. $aAliasTranslation = array();
  894. $oReceiver->AddCondition_PointingTo_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
  895. }
  896. }
  897. }
  898. // Check and prepare the select information
  899. $this->m_aSelectedClasses = array();
  900. foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails)
  901. {
  902. $sClassToSelect = $oClassDetails->GetValue();
  903. $this->m_aSelectedClasses[$sClassToSelect] = $aAliases[$sClassToSelect];
  904. }
  905. $this->m_aClasses = $aAliases;
  906. $oConditionTree = $oOqlQuery->GetCondition();
  907. if ($oConditionTree instanceof Expression)
  908. {
  909. $this->m_oSearchCondition = $this->OQLExpressionToCondition($sQuery, $oConditionTree, $aAliases);
  910. }
  911. }
  912. ////////////////////////////////////////////////////////////////////////////
  913. //
  914. // Construction of the SQL queries
  915. //
  916. ////////////////////////////////////////////////////////////////////////////
  917. public function MakeDeleteQuery($aArgs = array())
  918. {
  919. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  920. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  921. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, null, array());
  922. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  923. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  924. $aScalarArgs = array_merge(MetaModel::PrepareQueryArguments($aArgs), $this->GetInternalParams());
  925. return $oSQLQuery->RenderDelete($aScalarArgs);
  926. }
  927. public function MakeUpdateQuery($aValues, $aArgs = array())
  928. {
  929. // $aValues is an array of $sAttCode => $value
  930. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  931. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  932. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, null, $aValues);
  933. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  934. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  935. $aScalarArgs = array_merge(MetaModel::PrepareQueryArguments($aArgs), $this->GetInternalParams());
  936. return $oSQLQuery->RenderUpdate($aScalarArgs);
  937. }
  938. public function MakeSQLQuery($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr = null, $aSelectedClasses = null)
  939. {
  940. $oBuild = new QueryBuilderContext($this, $aModifierProperties, $aGroupByExpr, $aSelectedClasses);
  941. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, $aAttToLoad, array());
  942. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  943. if ($aGroupByExpr)
  944. {
  945. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  946. $oSQLQuery->SetGroupBy($aCols);
  947. $oSQLQuery->SetSelect($aCols);
  948. }
  949. else
  950. {
  951. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  952. }
  953. if (self::$m_bOptimizeQueries)
  954. {
  955. if ($bGetCount)
  956. {
  957. // Simplify the query if just getting the count
  958. $oSQLQuery->SetSelect(array());
  959. }
  960. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  961. $oSQLQuery->OptimizeJoins($aMandatoryTables);
  962. }
  963. return $oSQLQuery;
  964. }
  965. protected function MakeSQLObjectQuery(&$oBuild, $aAttToLoad = null, $aValues = array())
  966. {
  967. // Note: query class might be different than the class of the filter
  968. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  969. $sClass = $this->GetFirstJoinedClass();
  970. $sClassAlias = $this->GetFirstJoinedClassAlias();
  971. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  972. self::DbgTrace("Entering: ".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  973. $sRootClass = MetaModel::GetRootClass($sClass);
  974. $sKeyField = MetaModel::DBGetKey($sClass);
  975. if ($bIsOnQueriedClass)
  976. {
  977. // default to the whole list of attributes + the very std id/finalclass
  978. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  979. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  980. {
  981. $sSelectedClass = $oBuild->GetSelectedClass($sClassAlias);
  982. $aAttList = MetaModel::ListAttributeDefs($sSelectedClass);
  983. }
  984. else
  985. {
  986. $aAttList = $aAttToLoad[$sClassAlias];
  987. }
  988. foreach ($aAttList as $sAttCode => $oAttDef)
  989. {
  990. if (!$oAttDef->IsScalar()) continue;
  991. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  992. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  993. {
  994. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  995. }
  996. }
  997. // Transform the full text condition into additional condition expression
  998. $aFullText = $this->GetCriteria_FullText();
  999. if (count($aFullText) > 0)
  1000. {
  1001. $aFullTextFields = array();
  1002. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1003. {
  1004. if (!$oAttDef->IsScalar()) continue;
  1005. if ($oAttDef->IsExternalKey()) continue;
  1006. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  1007. }
  1008. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  1009. foreach($aFullText as $sFTNeedle)
  1010. {
  1011. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  1012. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  1013. }
  1014. }
  1015. }
  1016. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1017. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  1018. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  1019. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  1020. // Compute a clear view of required joins (from the current class)
  1021. // Build the list of external keys:
  1022. // -> ext keys required by an explicit join
  1023. // -> ext keys mentionned in a 'pointing to' condition
  1024. // -> ext keys required for an external field
  1025. // -> ext keys required for a friendly name
  1026. //
  1027. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1028. //
  1029. // Optimization: could be partially computed once for all (cached) ?
  1030. //
  1031. if ($bIsOnQueriedClass)
  1032. {
  1033. // Get all Ext keys for the queried class (??)
  1034. foreach(MetaModel::GetKeysList($sClass) as $sKeyAttCode)
  1035. {
  1036. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1037. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1038. }
  1039. }
  1040. // Get all Ext keys used by the filter
  1041. foreach ($this->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  1042. {
  1043. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1044. {
  1045. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1046. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1047. }
  1048. }
  1049. $aFNJoinAlias = array(); // array of (subclass => alias)
  1050. if (array_key_exists('friendlyname', $aExpectedAtts))
  1051. {
  1052. // To optimize: detect a restriction on child classes in the condition expression
  1053. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  1054. $oNameExpression = self::GetExtendedNameExpression($sClass);
  1055. $aNameFields = array();
  1056. $oNameExpression->GetUnresolvedFields('', $aNameFields);
  1057. $aTranslateNameFields = array();
  1058. foreach($aNameFields as $sSubClass => $aFields)
  1059. {
  1060. foreach($aFields as $sAttCode => $oField)
  1061. {
  1062. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1063. if ($oAttDef->IsExternalKey())
  1064. {
  1065. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1066. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  1067. }
  1068. elseif ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  1069. {
  1070. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1071. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sKeyAttCode);
  1072. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  1073. }
  1074. else
  1075. {
  1076. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1077. }
  1078. if (MetaModel::IsParentClass($sClassOfAttribute, $sClass))
  1079. {
  1080. // The attribute is part of the standard query
  1081. //
  1082. $sAliasForAttribute = $sClassAlias;
  1083. }
  1084. else
  1085. {
  1086. // The attribute will be available from an additional outer join
  1087. // For each subclass (table) one single join is enough
  1088. //
  1089. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  1090. {
  1091. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  1092. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  1093. }
  1094. else
  1095. {
  1096. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  1097. }
  1098. }
  1099. $aTranslateNameFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  1100. }
  1101. }
  1102. $oNameExpression = $oNameExpression->Translate($aTranslateNameFields, false);
  1103. $aTranslateNow = array();
  1104. $aTranslateNow[$sClassAlias]['friendlyname'] = $oNameExpression;
  1105. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1106. }
  1107. // Add the ext fields used in the select (eventually adds an external key)
  1108. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1109. {
  1110. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  1111. {
  1112. if (array_key_exists($sAttCode, $aExpectedAtts))
  1113. {
  1114. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1115. if ($sKeyAttCode != 'id')
  1116. {
  1117. // Add the external attribute
  1118. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1119. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1120. }
  1121. }
  1122. }
  1123. }
  1124. // First query built upon on the leaf (ie current) class
  1125. //
  1126. self::DbgTrace("Main (=leaf) class, call MakeSQLObjectQuerySingleTable()");
  1127. if (MetaModel::HasTable($sClass))
  1128. {
  1129. $oSelectBase = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sClass, $aExtKeys, $aValues);
  1130. }
  1131. else
  1132. {
  1133. $oSelectBase = null;
  1134. // As the join will not filter on the expected classes, we have to specify it explicitely
  1135. $sExpectedClasses = implode("', '", MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1136. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1137. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  1138. }
  1139. // Then we join the queries of the eventual parent classes (compound model)
  1140. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1141. {
  1142. if (!MetaModel::HasTable($sParentClass)) continue;
  1143. self::DbgTrace("Parent class: $sParentClass... let's call MakeSQLObjectQuerySingleTable()");
  1144. $oSelectParentTable = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sParentClass, $aExtKeys, $aValues);
  1145. if (is_null($oSelectBase))
  1146. {
  1147. $oSelectBase = $oSelectParentTable;
  1148. }
  1149. else
  1150. {
  1151. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, MetaModel::DBGetKey($sParentClass));
  1152. }
  1153. }
  1154. // Filter on objects referencing me
  1155. foreach ($this->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1156. {
  1157. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1158. {
  1159. $oForeignKeyAttDef = MetaModel::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1160. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeSQLObjectQuery()");
  1161. //self::DbgTrace($oForeignFilter);
  1162. //self::DbgTrace($oForeignFilter->ToOQL());
  1163. //self::DbgTrace($oSelectForeign);
  1164. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1165. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1166. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignKeyAttCode, $sForeignClassAlias));
  1167. if ($oForeignKeyAttDef instanceof AttributeObjectKey)
  1168. {
  1169. $sClassAttCode = $oForeignKeyAttDef->Get('class_attcode');
  1170. // Add the condition: `$sForeignClassAlias`.$sClassAttCode IN (subclasses of $sClass')
  1171. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1172. $oClassExpr = new FieldExpression($sClassAttCode, $sForeignClassAlias);
  1173. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1174. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1175. }
  1176. $oSelectForeign = $oForeignFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1177. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1178. $sForeignKeyTable = $oJoinExpr->GetParent();
  1179. $sForeignKeyColumn = $oJoinExpr->GetName();
  1180. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1181. }
  1182. }
  1183. // Additional JOINS for Friendly names
  1184. //
  1185. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  1186. {
  1187. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  1188. $oSelectFN = $oSubClassFilter->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sSubClass, $aExtKeys, array());
  1189. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, MetaModel::DBGetKey($sSubClass));
  1190. }
  1191. // That's all... cross fingers and we'll get some working query
  1192. //MyHelpers::var_dump_html($oSelectBase, true);
  1193. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1194. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1195. return $oSelectBase;
  1196. }
  1197. protected function MakeSQLObjectQuerySingleTable(&$oBuild, $aAttToLoad, $sTableClass, $aExtKeys, $aValues)
  1198. {
  1199. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1200. //echo "MakeSQLObjectQuery($sTableClass)-liste des clefs externes($sTableClass): <pre>".print_r($aExtKeys, true)."</pre><br/>\n";
  1201. // Prepare the query for a single table (compound objects)
  1202. // Ignores the items (attributes/filters) that are not on the target table
  1203. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1204. //
  1205. // Returns an SQLQuery
  1206. //
  1207. $sTargetClass = $this->GetFirstJoinedClass();
  1208. $sTargetAlias = $this->GetFirstJoinedClassAlias();
  1209. $sTable = MetaModel::DBGetTable($sTableClass);
  1210. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  1211. $aTranslation = array();
  1212. $aExpectedAtts = array();
  1213. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  1214. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  1215. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1216. // 1 - SELECT and UPDATE
  1217. //
  1218. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1219. //
  1220. $aUpdateValues = array();
  1221. // 1/a - Get the key and friendly name
  1222. //
  1223. // We need one pkey to be the key, let's take the first one available
  1224. $oSelectedIdField = null;
  1225. $oIdField = new FieldExpressionResolved(MetaModel::DBGetKey($sTableClass), $sTableAlias);
  1226. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  1227. if ($bIsOnQueriedClass)
  1228. {
  1229. // Add this field to the list of queried fields (required for the COUNT to work fine)
  1230. $oSelectedIdField = $oIdField;
  1231. }
  1232. // 1/b - Get the other attributes
  1233. //
  1234. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1235. {
  1236. // Skip this attribute if not defined in this table
  1237. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1238. // Skip this attribute if not made of SQL columns
  1239. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1240. // Update...
  1241. //
  1242. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1243. {
  1244. assert ($oAttDef->IsDirectField());
  1245. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1246. {
  1247. $aUpdateValues[$sColumn] = $sValue;
  1248. }
  1249. }
  1250. }
  1251. // 2 - The SQL query, for this table only
  1252. //
  1253. $oSelectBase = new SQLObjectQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  1254. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  1255. //
  1256. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1257. {
  1258. // Skip this attribute if not defined in this table
  1259. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1260. // Select...
  1261. //
  1262. if ($oAttDef->IsExternalField())
  1263. {
  1264. // skip, this will be handled in the joined tables (done hereabove)
  1265. }
  1266. else
  1267. {
  1268. //echo "<p>MakeSQLObjectQuerySingleTable: Field $sAttCode is part of the table $sTable (named: $sTableAlias)</p>";
  1269. // standard field, or external key
  1270. // add it to the output
  1271. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1272. {
  1273. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  1274. {
  1275. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1276. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  1277. {
  1278. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  1279. }
  1280. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  1281. }
  1282. }
  1283. }
  1284. }
  1285. //echo "MakeSQLObjectQuery- Classe $sTableClass<br/>\n";
  1286. // 4 - The external keys -> joins...
  1287. //
  1288. $aAllPointingTo = $this->GetCriteria_PointingTo();
  1289. if (array_key_exists($sTableClass, $aExtKeys))
  1290. {
  1291. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1292. {
  1293. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1294. $aPointingTo = $this->GetCriteria_PointingTo($sKeyAttCode);
  1295. //echo "MakeSQLObjectQuery-Cle '$sKeyAttCode'<br/>\n";
  1296. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1297. {
  1298. //echo "MakeSQLObjectQuery-Ajoutons l'operateur TREE_OPERATOR_EQUALS pour $sKeyAttCode<br/>\n";
  1299. // The join was not explicitely defined in the filter,
  1300. // we need to do it now
  1301. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1302. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1303. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1304. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  1305. }
  1306. }
  1307. }
  1308. //echo "MakeSQLObjectQuery-liste des clefs de jointure: <pre>".print_r(array_keys($aAllPointingTo), true)."</pre><br/>\n";
  1309. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  1310. {
  1311. foreach($aPointingTo as $iOperatorCode => $aFilter)
  1312. {
  1313. foreach($aFilter as $oExtFilter)
  1314. {
  1315. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  1316. // The aliases should not conflict because normalization occured while building the filter
  1317. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1318. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1319. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1320. //echo "MakeSQLObjectQuery-$sTableClass::$sKeyAttCode Foreach PointingTo($iOperatorCode) <span style=\"color:red\">$sKeyClass (alias:$sKeyClassAlias)</span><br/>\n";
  1321. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1322. //echo "MakeSQLObjectQuery-array_key_exists($sTableClass, \$aExtKeys)<br/>\n";
  1323. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  1324. {
  1325. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  1326. {
  1327. // Specify expected attributes for the target class query
  1328. // ... and use the current alias !
  1329. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  1330. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  1331. {
  1332. //echo "MakeSQLObjectQuery aExtKeys[$sTableClass][$sKeyAttCode] => $sAttCode-oAtt: <pre>".print_r($oAtt, true)."</pre><br/>\n";
  1333. if ($oAtt instanceof AttributeFriendlyName)
  1334. {
  1335. // Note: for a given ext key, there is one single attribute "friendly name"
  1336. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  1337. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);</b></p>\n";
  1338. }
  1339. else
  1340. {
  1341. $sExtAttCode = $oAtt->GetExtAttCode();
  1342. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1343. $oRemoteAttDef = MetaModel::GetAttributeDef($sKeyClass, $sExtAttCode);
  1344. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColId => $sRemoteAttExpr)
  1345. {
  1346. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  1347. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);</b></p>\n";
  1348. }
  1349. //echo "<p><b>ExtAttr2: $sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</b></p>\n";
  1350. }
  1351. }
  1352. if ($oKeyAttDef instanceof AttributeObjectKey)
  1353. {
  1354. // Add the condition: `$sTargetAlias`.$sClassAttCode IN (subclasses of $sKeyClass')
  1355. $sClassAttCode = $oKeyAttDef->Get('class_attcode');
  1356. $oClassAttDef = MetaModel::GetAttributeDef($sTargetClass, $sClassAttCode);
  1357. foreach ($oClassAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1358. {
  1359. $aTranslateNow[$sTargetAlias][$sClassAttCode.$sColId] = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1360. }
  1361. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sKeyClass, ENUM_CHILD_CLASSES_ALL));
  1362. $oClassExpr = new FieldExpression($sClassAttCode, $sTargetAlias);
  1363. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1364. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1365. }
  1366. // Translate prior to recursing
  1367. //
  1368. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."\n".print_r($aTranslateNow, true)."</pre></p>\n";
  1369. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1370. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1371. //echo "<p>External key $sKeyAttCode (class: $sKeyClass), call MakeSQLObjectQuery()/p>\n";
  1372. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeSQLObjectQuery()");
  1373. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  1374. //echo "<p>Recursive MakeSQLObjectQuery ".__LINE__.": <pre>\n".print_r($oBuild->GetRootFilter()->GetSelectedClasses(), true)."</pre></p>\n";
  1375. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1376. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1377. $sExternalKeyTable = $oJoinExpr->GetParent();
  1378. $sExternalKeyField = $oJoinExpr->GetName();
  1379. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  1380. $sLocalKeyField = current($aCols); // get the first column for an external key
  1381. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1382. if ($oKeyAttDef->IsNullAllowed())
  1383. {
  1384. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1385. }
  1386. else
  1387. {
  1388. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1389. }
  1390. }
  1391. }
  1392. elseif(MetaModel::GetAttributeOrigin($sKeyClass, $sKeyAttCode) == $sTableClass)
  1393. {
  1394. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  1395. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1396. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1397. $sExternalKeyTable = $oJoinExpr->GetParent();
  1398. $sExternalKeyField = $oJoinExpr->GetName();
  1399. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  1400. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  1401. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  1402. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  1403. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  1404. }
  1405. }
  1406. }
  1407. }
  1408. // Translate the selected columns
  1409. //
  1410. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1411. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  1412. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1413. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1414. return $oSelectBase;
  1415. }
  1416. /**
  1417. * Get the friendly name for the class and its subclasses (if finalclass = 'subclass' ...)
  1418. * Simplifies the final expression by grouping classes having the same name expression
  1419. * Used when querying a parent class
  1420. */
  1421. static protected function GetExtendedNameExpression($sClass)
  1422. {
  1423. // 1st step - get all of the required expressions (instantiable classes)
  1424. // and group them using their OQL representation
  1425. //
  1426. $aFNExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes)
  1427. foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1428. {
  1429. if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) continue;
  1430. $oSubClassName = MetaModel::GetNameExpression($sSubClass);
  1431. $sSignature = $oSubClassName->Render();
  1432. if (!array_key_exists($sSignature, $aFNExpressions))
  1433. {
  1434. $aFNExpressions[$sSignature] = array(
  1435. 'expression' => $oSubClassName,
  1436. 'classes' => array(),
  1437. );
  1438. }
  1439. $aFNExpressions[$sSignature]['classes'][] = $sSubClass;
  1440. }
  1441. // 2nd step - build the final name expression depending on the finalclass
  1442. //
  1443. if (count($aFNExpressions) == 1)
  1444. {
  1445. $aExpData = reset($aFNExpressions);
  1446. $oNameExpression = $aExpData['expression'];
  1447. }
  1448. else
  1449. {
  1450. $oNameExpression = null;
  1451. foreach ($aFNExpressions as $sSignature => $aExpData)
  1452. {
  1453. $oClassListExpr = ListExpression::FromScalars($aExpData['classes']);
  1454. $oClassExpr = new FieldExpression('finalclass', $sClass);
  1455. $oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1456. if (is_null($oNameExpression))
  1457. {
  1458. $oNameExpression = $aExpData['expression'];
  1459. }
  1460. else
  1461. {
  1462. $oNameExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oNameExpression));
  1463. }
  1464. }
  1465. }
  1466. return $oNameExpression;
  1467. }
  1468. }