dbobjectsearch.class.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  1. <?php
  2. // Copyright (C) 2010-2016 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-2016 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. 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($bExcludeMagicParams = true)
  653. {
  654. $aParams = array();
  655. $this->m_oSearchCondition->Render($aParams, true);
  656. if ($bExcludeMagicParams)
  657. {
  658. $aRet = array();
  659. // Make the list of acceptable arguments... could be factorized with run_query, into oSearch->GetQueryParams($bExclude magic params)
  660. $aNakedMagicArguments = array();
  661. foreach (MetaModel::PrepareQueryArguments(array()) as $sArgName => $value)
  662. {
  663. $iPos = strpos($sArgName, '->object()');
  664. if ($iPos === false)
  665. {
  666. $aNakedMagicArguments[$sArgName] = $value;
  667. }
  668. else
  669. {
  670. $aNakedMagicArguments[substr($sArgName, 0, $iPos)] = true;
  671. }
  672. }
  673. foreach ($aParams as $sParam => $foo)
  674. {
  675. $iPos = strpos($sParam, '->');
  676. if ($iPos === false)
  677. {
  678. $sRefName = $sParam;
  679. }
  680. else
  681. {
  682. $sRefName = substr($sParam, 0, $iPos);
  683. }
  684. if (!array_key_exists($sRefName, $aNakedMagicArguments))
  685. {
  686. $aRet[$sParam] = $foo;
  687. }
  688. }
  689. }
  690. return $aRet;
  691. }
  692. public function ListConstantFields()
  693. {
  694. return $this->m_oSearchCondition->ListConstantFields();
  695. }
  696. /**
  697. * Turn the parameters (:xxx) into scalar values in order to easily
  698. * serialize a search
  699. */
  700. public function ApplyParameters($aArgs)
  701. {
  702. return $this->m_oSearchCondition->ApplyParameters(array_merge($this->m_aParams, $aArgs));
  703. }
  704. public function ToOQL($bDevelopParams = false, $aContextParams = null)
  705. {
  706. // Currently unused, but could be useful later
  707. $bRetrofitParams = false;
  708. if ($bDevelopParams)
  709. {
  710. if (is_null($aContextParams))
  711. {
  712. $aParams = array_merge($this->m_aParams);
  713. }
  714. else
  715. {
  716. $aParams = array_merge($aContextParams, $this->m_aParams);
  717. }
  718. $aParams = MetaModel::PrepareQueryArguments($aParams);
  719. }
  720. else
  721. {
  722. // Leave it as is, the rendering will be made with parameters in clear
  723. $aParams = null;
  724. }
  725. $aSelectedAliases = array();
  726. foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
  727. {
  728. $aSelectedAliases[] = '`' . $sAlias . '`';
  729. }
  730. $sSelectedClasses = implode(', ', $aSelectedAliases);
  731. $sRes = 'SELECT '.$sSelectedClasses.' FROM';
  732. $sRes .= ' ' . $this->GetFirstJoinedClass() . ' AS `' . $this->GetFirstJoinedClassAlias() . '`';
  733. $sRes .= $this->ToOQL_Joins();
  734. $sRes .= " WHERE ".$this->m_oSearchCondition->Render($aParams, $bRetrofitParams);
  735. // Temporary: add more info about other conditions, necessary to avoid strange behaviors with the cache
  736. foreach($this->m_aFullText as $sFullText)
  737. {
  738. $sRes .= " AND MATCHES '$sFullText'";
  739. }
  740. return $sRes;
  741. }
  742. protected function ToOQL_Joins()
  743. {
  744. $sRes = '';
  745. foreach($this->m_aPointingTo as $sExtKey => $aPointingTo)
  746. {
  747. foreach($aPointingTo as $iOperatorCode => $aFilter)
  748. {
  749. foreach($aFilter as $oFilter)
  750. {
  751. switch($iOperatorCode)
  752. {
  753. case TREE_OPERATOR_EQUALS:
  754. $sOperator = ' = ';
  755. break;
  756. case TREE_OPERATOR_BELOW:
  757. $sOperator = ' BELOW ';
  758. break;
  759. case TREE_OPERATOR_BELOW_STRICT:
  760. $sOperator = ' BELOW STRICT ';
  761. break;
  762. case TREE_OPERATOR_NOT_BELOW:
  763. $sOperator = ' NOT BELOW ';
  764. break;
  765. case TREE_OPERATOR_NOT_BELOW_STRICT:
  766. $sOperator = ' NOT BELOW STRICT ';
  767. break;
  768. case TREE_OPERATOR_ABOVE:
  769. $sOperator = ' ABOVE ';
  770. break;
  771. case TREE_OPERATOR_ABOVE_STRICT:
  772. $sOperator = ' ABOVE STRICT ';
  773. break;
  774. case TREE_OPERATOR_NOT_ABOVE:
  775. $sOperator = ' NOT ABOVE ';
  776. break;
  777. case TREE_OPERATOR_NOT_ABOVE_STRICT:
  778. $sOperator = ' NOT ABOVE STRICT ';
  779. break;
  780. }
  781. $sRes .= ' JOIN ' . $oFilter->GetFirstJoinedClass() . ' AS `' . $oFilter->GetFirstJoinedClassAlias() . '` ON `' . $this->GetFirstJoinedClassAlias() . '`.' . $sExtKey . $sOperator . '`' . $oFilter->GetFirstJoinedClassAlias() . '`.id';
  782. $sRes .= $oFilter->ToOQL_Joins();
  783. }
  784. }
  785. }
  786. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  787. {
  788. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  789. {
  790. $sRes .= ' JOIN ' . $oForeignFilter->GetFirstJoinedClass() . ' AS `' . $oForeignFilter->GetFirstJoinedClassAlias() . '` ON `' . $oForeignFilter->GetFirstJoinedClassAlias() . '`.' . $sForeignExtKeyAttCode . ' = `' . $this->GetFirstJoinedClassAlias() . '`.id';
  791. $sRes .= $oForeignFilter->ToOQL_Joins();
  792. }
  793. }
  794. return $sRes;
  795. }
  796. protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases)
  797. {
  798. if ($oExpression instanceof BinaryOqlExpression)
  799. {
  800. $sOperator = $oExpression->GetOperator();
  801. $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
  802. $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
  803. return new BinaryExpression($oLeft, $sOperator, $oRight);
  804. }
  805. elseif ($oExpression instanceof FieldOqlExpression)
  806. {
  807. $sClassAlias = $oExpression->GetParent();
  808. $sFltCode = $oExpression->GetName();
  809. if (empty($sClassAlias))
  810. {
  811. // Need to find the right alias
  812. // Build an array of field => array of aliases
  813. $aFieldClasses = array();
  814. foreach($aClassAliases as $sAlias => $sReal)
  815. {
  816. foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode)
  817. {
  818. $aFieldClasses[$sAnFltCode][] = $sAlias;
  819. }
  820. }
  821. $sClassAlias = $aFieldClasses[$sFltCode][0];
  822. }
  823. return new FieldExpression($sFltCode, $sClassAlias);
  824. }
  825. elseif ($oExpression instanceof VariableOqlExpression)
  826. {
  827. return new VariableExpression($oExpression->GetName());
  828. }
  829. elseif ($oExpression instanceof TrueOqlExpression)
  830. {
  831. return new TrueExpression;
  832. }
  833. elseif ($oExpression instanceof ScalarOqlExpression)
  834. {
  835. return new ScalarExpression($oExpression->GetValue());
  836. }
  837. elseif ($oExpression instanceof ListOqlExpression)
  838. {
  839. $aItems = array();
  840. foreach ($oExpression->GetItems() as $oItemExpression)
  841. {
  842. $aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases);
  843. }
  844. return new ListExpression($aItems);
  845. }
  846. elseif ($oExpression instanceof FunctionOqlExpression)
  847. {
  848. $aArgs = array();
  849. foreach ($oExpression->GetArgs() as $oArgExpression)
  850. {
  851. $aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases);
  852. }
  853. return new FunctionExpression($oExpression->GetVerb(), $aArgs);
  854. }
  855. elseif ($oExpression instanceof IntervalOqlExpression)
  856. {
  857. return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit());
  858. }
  859. else
  860. {
  861. throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery));
  862. }
  863. }
  864. public function InitFromOqlQuery(OqlQuery $oOqlQuery, $sQuery)
  865. {
  866. $oModelReflection = new ModelReflectionRuntime();
  867. $sClass = $oOqlQuery->GetClass($oModelReflection);
  868. $sClassAlias = $oOqlQuery->GetClassAlias();
  869. $aAliases = array($sClassAlias => $sClass);
  870. // Maintain an array of filters, because the flat list is in fact referring to a tree
  871. // And this will be an easy way to dispatch the conditions
  872. // $this will be referenced by the other filters, or the other way around...
  873. $aJoinItems = array($sClassAlias => $this);
  874. $aJoinSpecs = $oOqlQuery->GetJoins();
  875. if (is_array($aJoinSpecs))
  876. {
  877. foreach ($aJoinSpecs as $oJoinSpec)
  878. {
  879. $sJoinClass = $oJoinSpec->GetClass();
  880. $sJoinClassAlias = $oJoinSpec->GetClassAlias();
  881. // Assumption: ext key on the left only !!!
  882. // normalization should take care of this
  883. $oLeftField = $oJoinSpec->GetLeftField();
  884. $sFromClass = $oLeftField->GetParent();
  885. $sExtKeyAttCode = $oLeftField->GetName();
  886. $oRightField = $oJoinSpec->GetRightField();
  887. $sToClass = $oRightField->GetParent();
  888. $aAliases[$sJoinClassAlias] = $sJoinClass;
  889. $aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias);
  890. if ($sFromClass == $sJoinClassAlias)
  891. {
  892. $oReceiver = $aJoinItems[$sToClass];
  893. $oNewComer = $aJoinItems[$sFromClass];
  894. $aAliasTranslation = array();
  895. $oReceiver->AddCondition_ReferencedBy_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation);
  896. }
  897. else
  898. {
  899. $sOperator = $oJoinSpec->GetOperator();
  900. switch($sOperator)
  901. {
  902. case '=':
  903. $iOperatorCode = TREE_OPERATOR_EQUALS;
  904. break;
  905. case 'BELOW':
  906. $iOperatorCode = TREE_OPERATOR_BELOW;
  907. break;
  908. case 'BELOW_STRICT':
  909. $iOperatorCode = TREE_OPERATOR_BELOW_STRICT;
  910. break;
  911. case 'NOT_BELOW':
  912. $iOperatorCode = TREE_OPERATOR_NOT_BELOW;
  913. break;
  914. case 'NOT_BELOW_STRICT':
  915. $iOperatorCode = TREE_OPERATOR_NOT_BELOW_STRICT;
  916. break;
  917. case 'ABOVE':
  918. $iOperatorCode = TREE_OPERATOR_ABOVE;
  919. break;
  920. case 'ABOVE_STRICT':
  921. $iOperatorCode = TREE_OPERATOR_ABOVE_STRICT;
  922. break;
  923. case 'NOT_ABOVE':
  924. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE;
  925. break;
  926. case 'NOT_ABOVE_STRICT':
  927. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE_STRICT;
  928. break;
  929. }
  930. $oReceiver = $aJoinItems[$sFromClass];
  931. $oNewComer = $aJoinItems[$sToClass];
  932. $aAliasTranslation = array();
  933. $oReceiver->AddCondition_PointingTo_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
  934. }
  935. }
  936. }
  937. // Check and prepare the select information
  938. $this->m_aSelectedClasses = array();
  939. foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails)
  940. {
  941. $sClassToSelect = $oClassDetails->GetValue();
  942. $this->m_aSelectedClasses[$sClassToSelect] = $aAliases[$sClassToSelect];
  943. }
  944. $this->m_aClasses = $aAliases;
  945. $oConditionTree = $oOqlQuery->GetCondition();
  946. if ($oConditionTree instanceof Expression)
  947. {
  948. $this->m_oSearchCondition = $this->OQLExpressionToCondition($sQuery, $oConditionTree, $aAliases);
  949. }
  950. }
  951. ////////////////////////////////////////////////////////////////////////////
  952. //
  953. // Construction of the SQL queries
  954. //
  955. ////////////////////////////////////////////////////////////////////////////
  956. public function MakeDeleteQuery($aArgs = array())
  957. {
  958. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  959. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  960. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, null, array());
  961. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  962. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  963. $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams());
  964. return $oSQLQuery->RenderDelete($aScalarArgs);
  965. }
  966. public function MakeUpdateQuery($aValues, $aArgs = array())
  967. {
  968. // $aValues is an array of $sAttCode => $value
  969. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  970. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  971. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, null, $aValues);
  972. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  973. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  974. $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams());
  975. return $oSQLQuery->RenderUpdate($aScalarArgs);
  976. }
  977. public function MakeSQLQuery($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr = null, $aSelectedClasses = null)
  978. {
  979. $oBuild = new QueryBuilderContext($this, $aModifierProperties, $aGroupByExpr, $aSelectedClasses);
  980. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, $aAttToLoad, array());
  981. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  982. if ($aGroupByExpr)
  983. {
  984. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  985. $oSQLQuery->SetGroupBy($aCols);
  986. $oSQLQuery->SetSelect($aCols);
  987. }
  988. else
  989. {
  990. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  991. }
  992. if (self::$m_bOptimizeQueries)
  993. {
  994. if ($bGetCount)
  995. {
  996. // Simplify the query if just getting the count
  997. $oSQLQuery->SetSelect(array());
  998. }
  999. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  1000. $oSQLQuery->OptimizeJoins($aMandatoryTables);
  1001. }
  1002. return $oSQLQuery;
  1003. }
  1004. protected function MakeSQLObjectQuery(&$oBuild, $aAttToLoad = null, $aValues = array())
  1005. {
  1006. // Note: query class might be different than the class of the filter
  1007. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1008. $sClass = $this->GetFirstJoinedClass();
  1009. $sClassAlias = $this->GetFirstJoinedClassAlias();
  1010. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  1011. self::DbgTrace("Entering: ".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1012. $sRootClass = MetaModel::GetRootClass($sClass);
  1013. $sKeyField = MetaModel::DBGetKey($sClass);
  1014. if ($bIsOnQueriedClass)
  1015. {
  1016. // default to the whole list of attributes + the very std id/finalclass
  1017. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  1018. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  1019. {
  1020. $sSelectedClass = $oBuild->GetSelectedClass($sClassAlias);
  1021. $aAttList = MetaModel::ListAttributeDefs($sSelectedClass);
  1022. }
  1023. else
  1024. {
  1025. $aAttList = $aAttToLoad[$sClassAlias];
  1026. }
  1027. foreach ($aAttList as $sAttCode => $oAttDef)
  1028. {
  1029. if (!$oAttDef->IsScalar()) continue;
  1030. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  1031. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1032. {
  1033. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  1034. }
  1035. }
  1036. // Transform the full text condition into additional condition expression
  1037. $aFullText = $this->GetCriteria_FullText();
  1038. if (count($aFullText) > 0)
  1039. {
  1040. $aFullTextFields = array();
  1041. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1042. {
  1043. if (!$oAttDef->IsScalar()) continue;
  1044. if ($oAttDef->IsExternalKey()) continue;
  1045. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  1046. }
  1047. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  1048. foreach($aFullText as $sFTNeedle)
  1049. {
  1050. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  1051. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  1052. }
  1053. }
  1054. }
  1055. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1056. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  1057. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  1058. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  1059. // Compute a clear view of required joins (from the current class)
  1060. // Build the list of external keys:
  1061. // -> ext keys required by an explicit join
  1062. // -> ext keys mentionned in a 'pointing to' condition
  1063. // -> ext keys required for an external field
  1064. // -> ext keys required for a friendly name
  1065. //
  1066. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1067. //
  1068. // Optimization: could be partially computed once for all (cached) ?
  1069. //
  1070. if ($bIsOnQueriedClass)
  1071. {
  1072. // Get all Ext keys for the queried class (??)
  1073. foreach(MetaModel::GetKeysList($sClass) as $sKeyAttCode)
  1074. {
  1075. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1076. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1077. }
  1078. }
  1079. // Get all Ext keys used by the filter
  1080. foreach ($this->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  1081. {
  1082. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1083. {
  1084. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1085. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1086. }
  1087. }
  1088. $aFNJoinAlias = array(); // array of (subclass => alias)
  1089. if (array_key_exists('friendlyname', $aExpectedAtts))
  1090. {
  1091. // To optimize: detect a restriction on child classes in the condition expression
  1092. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  1093. $oNameExpression = self::GetExtendedNameExpression($sClass);
  1094. $aNameFields = array();
  1095. $oNameExpression->GetUnresolvedFields('', $aNameFields);
  1096. $aTranslateNameFields = array();
  1097. foreach($aNameFields as $sSubClass => $aFields)
  1098. {
  1099. foreach($aFields as $sAttCode => $oField)
  1100. {
  1101. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1102. if ($oAttDef->IsExternalKey())
  1103. {
  1104. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1105. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  1106. }
  1107. elseif ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  1108. {
  1109. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1110. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sKeyAttCode);
  1111. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  1112. }
  1113. else
  1114. {
  1115. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1116. }
  1117. if (MetaModel::IsParentClass($sClassOfAttribute, $sClass))
  1118. {
  1119. // The attribute is part of the standard query
  1120. //
  1121. $sAliasForAttribute = $sClassAlias;
  1122. }
  1123. else
  1124. {
  1125. // The attribute will be available from an additional outer join
  1126. // For each subclass (table) one single join is enough
  1127. //
  1128. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  1129. {
  1130. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  1131. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  1132. }
  1133. else
  1134. {
  1135. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  1136. }
  1137. }
  1138. $aTranslateNameFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  1139. }
  1140. }
  1141. $oNameExpression = $oNameExpression->Translate($aTranslateNameFields, false);
  1142. $aTranslateNow = array();
  1143. $aTranslateNow[$sClassAlias]['friendlyname'] = $oNameExpression;
  1144. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1145. }
  1146. // Add the ext fields used in the select (eventually adds an external key)
  1147. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1148. {
  1149. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  1150. {
  1151. if (array_key_exists($sAttCode, $aExpectedAtts))
  1152. {
  1153. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1154. if ($sKeyAttCode != 'id')
  1155. {
  1156. // Add the external attribute
  1157. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1158. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1159. }
  1160. }
  1161. }
  1162. }
  1163. // First query built upon on the leaf (ie current) class
  1164. //
  1165. self::DbgTrace("Main (=leaf) class, call MakeSQLObjectQuerySingleTable()");
  1166. if (MetaModel::HasTable($sClass))
  1167. {
  1168. $oSelectBase = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sClass, $aExtKeys, $aValues);
  1169. }
  1170. else
  1171. {
  1172. $oSelectBase = null;
  1173. // As the join will not filter on the expected classes, we have to specify it explicitely
  1174. $sExpectedClasses = implode("', '", MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1175. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1176. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  1177. }
  1178. // Then we join the queries of the eventual parent classes (compound model)
  1179. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1180. {
  1181. if (!MetaModel::HasTable($sParentClass)) continue;
  1182. self::DbgTrace("Parent class: $sParentClass... let's call MakeSQLObjectQuerySingleTable()");
  1183. $oSelectParentTable = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sParentClass, $aExtKeys, $aValues);
  1184. if (is_null($oSelectBase))
  1185. {
  1186. $oSelectBase = $oSelectParentTable;
  1187. }
  1188. else
  1189. {
  1190. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, MetaModel::DBGetKey($sParentClass));
  1191. }
  1192. }
  1193. // Filter on objects referencing me
  1194. foreach ($this->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1195. {
  1196. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1197. {
  1198. $oForeignKeyAttDef = MetaModel::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1199. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeSQLObjectQuery()");
  1200. //self::DbgTrace($oForeignFilter);
  1201. //self::DbgTrace($oForeignFilter->ToOQL());
  1202. //self::DbgTrace($oSelectForeign);
  1203. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1204. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1205. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignKeyAttCode, $sForeignClassAlias));
  1206. if ($oForeignKeyAttDef instanceof AttributeObjectKey)
  1207. {
  1208. $sClassAttCode = $oForeignKeyAttDef->Get('class_attcode');
  1209. // Add the condition: `$sForeignClassAlias`.$sClassAttCode IN (subclasses of $sClass')
  1210. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1211. $oClassExpr = new FieldExpression($sClassAttCode, $sForeignClassAlias);
  1212. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1213. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1214. }
  1215. $oSelectForeign = $oForeignFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1216. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1217. $sForeignKeyTable = $oJoinExpr->GetParent();
  1218. $sForeignKeyColumn = $oJoinExpr->GetName();
  1219. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1220. }
  1221. }
  1222. // Additional JOINS for Friendly names
  1223. //
  1224. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  1225. {
  1226. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  1227. $oSelectFN = $oSubClassFilter->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sSubClass, $aExtKeys, array());
  1228. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, MetaModel::DBGetKey($sSubClass));
  1229. }
  1230. // That's all... cross fingers and we'll get some working query
  1231. //MyHelpers::var_dump_html($oSelectBase, true);
  1232. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1233. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1234. return $oSelectBase;
  1235. }
  1236. protected function MakeSQLObjectQuerySingleTable(&$oBuild, $aAttToLoad, $sTableClass, $aExtKeys, $aValues)
  1237. {
  1238. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1239. //echo "MakeSQLObjectQuery($sTableClass)-liste des clefs externes($sTableClass): <pre>".print_r($aExtKeys, true)."</pre><br/>\n";
  1240. // Prepare the query for a single table (compound objects)
  1241. // Ignores the items (attributes/filters) that are not on the target table
  1242. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1243. //
  1244. // Returns an SQLQuery
  1245. //
  1246. $sTargetClass = $this->GetFirstJoinedClass();
  1247. $sTargetAlias = $this->GetFirstJoinedClassAlias();
  1248. $sTable = MetaModel::DBGetTable($sTableClass);
  1249. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  1250. $aTranslation = array();
  1251. $aExpectedAtts = array();
  1252. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  1253. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  1254. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1255. // 1 - SELECT and UPDATE
  1256. //
  1257. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1258. //
  1259. $aUpdateValues = array();
  1260. // 1/a - Get the key and friendly name
  1261. //
  1262. // We need one pkey to be the key, let's take the first one available
  1263. $oSelectedIdField = null;
  1264. $oIdField = new FieldExpressionResolved(MetaModel::DBGetKey($sTableClass), $sTableAlias);
  1265. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  1266. if ($bIsOnQueriedClass)
  1267. {
  1268. // Add this field to the list of queried fields (required for the COUNT to work fine)
  1269. $oSelectedIdField = $oIdField;
  1270. }
  1271. // 1/b - Get the other attributes
  1272. //
  1273. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1274. {
  1275. // Skip this attribute if not defined in this table
  1276. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1277. // Skip this attribute if not made of SQL columns
  1278. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1279. // Update...
  1280. //
  1281. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1282. {
  1283. assert ($oAttDef->IsDirectField());
  1284. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1285. {
  1286. $aUpdateValues[$sColumn] = $sValue;
  1287. }
  1288. }
  1289. }
  1290. // 2 - The SQL query, for this table only
  1291. //
  1292. $oSelectBase = new SQLObjectQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  1293. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  1294. //
  1295. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1296. {
  1297. // Skip this attribute if not defined in this table
  1298. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1299. // Select...
  1300. //
  1301. if ($oAttDef->IsExternalField())
  1302. {
  1303. // skip, this will be handled in the joined tables (done hereabove)
  1304. }
  1305. else
  1306. {
  1307. //echo "<p>MakeSQLObjectQuerySingleTable: Field $sAttCode is part of the table $sTable (named: $sTableAlias)</p>";
  1308. // standard field, or external key
  1309. // add it to the output
  1310. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1311. {
  1312. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  1313. {
  1314. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1315. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  1316. {
  1317. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  1318. }
  1319. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  1320. }
  1321. }
  1322. }
  1323. }
  1324. //echo "MakeSQLObjectQuery- Classe $sTableClass<br/>\n";
  1325. // 4 - The external keys -> joins...
  1326. //
  1327. $aAllPointingTo = $this->GetCriteria_PointingTo();
  1328. if (array_key_exists($sTableClass, $aExtKeys))
  1329. {
  1330. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1331. {
  1332. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1333. $aPointingTo = $this->GetCriteria_PointingTo($sKeyAttCode);
  1334. //echo "MakeSQLObjectQuery-Cle '$sKeyAttCode'<br/>\n";
  1335. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1336. {
  1337. //echo "MakeSQLObjectQuery-Ajoutons l'operateur TREE_OPERATOR_EQUALS pour $sKeyAttCode<br/>\n";
  1338. // The join was not explicitely defined in the filter,
  1339. // we need to do it now
  1340. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1341. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1342. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1343. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  1344. }
  1345. }
  1346. }
  1347. //echo "MakeSQLObjectQuery-liste des clefs de jointure: <pre>".print_r(array_keys($aAllPointingTo), true)."</pre><br/>\n";
  1348. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  1349. {
  1350. foreach($aPointingTo as $iOperatorCode => $aFilter)
  1351. {
  1352. foreach($aFilter as $oExtFilter)
  1353. {
  1354. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  1355. // The aliases should not conflict because normalization occured while building the filter
  1356. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1357. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1358. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1359. //echo "MakeSQLObjectQuery-$sTableClass::$sKeyAttCode Foreach PointingTo($iOperatorCode) <span style=\"color:red\">$sKeyClass (alias:$sKeyClassAlias)</span><br/>\n";
  1360. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1361. //echo "MakeSQLObjectQuery-array_key_exists($sTableClass, \$aExtKeys)<br/>\n";
  1362. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  1363. {
  1364. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  1365. {
  1366. // Specify expected attributes for the target class query
  1367. // ... and use the current alias !
  1368. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  1369. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  1370. {
  1371. //echo "MakeSQLObjectQuery aExtKeys[$sTableClass][$sKeyAttCode] => $sAttCode-oAtt: <pre>".print_r($oAtt, true)."</pre><br/>\n";
  1372. if ($oAtt instanceof AttributeFriendlyName)
  1373. {
  1374. // Note: for a given ext key, there is one single attribute "friendly name"
  1375. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  1376. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);</b></p>\n";
  1377. }
  1378. else
  1379. {
  1380. $sExtAttCode = $oAtt->GetExtAttCode();
  1381. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1382. $oRemoteAttDef = MetaModel::GetAttributeDef($sKeyClass, $sExtAttCode);
  1383. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColId => $sRemoteAttExpr)
  1384. {
  1385. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  1386. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);</b></p>\n";
  1387. }
  1388. //echo "<p><b>ExtAttr2: $sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</b></p>\n";
  1389. }
  1390. }
  1391. if ($oKeyAttDef instanceof AttributeObjectKey)
  1392. {
  1393. // Add the condition: `$sTargetAlias`.$sClassAttCode IN (subclasses of $sKeyClass')
  1394. $sClassAttCode = $oKeyAttDef->Get('class_attcode');
  1395. $oClassAttDef = MetaModel::GetAttributeDef($sTargetClass, $sClassAttCode);
  1396. foreach ($oClassAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1397. {
  1398. $aTranslateNow[$sTargetAlias][$sClassAttCode.$sColId] = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1399. }
  1400. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sKeyClass, ENUM_CHILD_CLASSES_ALL));
  1401. $oClassExpr = new FieldExpression($sClassAttCode, $sTargetAlias);
  1402. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1403. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1404. }
  1405. // Translate prior to recursing
  1406. //
  1407. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."\n".print_r($aTranslateNow, true)."</pre></p>\n";
  1408. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1409. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1410. //echo "<p>External key $sKeyAttCode (class: $sKeyClass), call MakeSQLObjectQuery()/p>\n";
  1411. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeSQLObjectQuery()");
  1412. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  1413. //echo "<p>Recursive MakeSQLObjectQuery ".__LINE__.": <pre>\n".print_r($oBuild->GetRootFilter()->GetSelectedClasses(), true)."</pre></p>\n";
  1414. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1415. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1416. $sExternalKeyTable = $oJoinExpr->GetParent();
  1417. $sExternalKeyField = $oJoinExpr->GetName();
  1418. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  1419. $sLocalKeyField = current($aCols); // get the first column for an external key
  1420. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1421. if ($oKeyAttDef->IsNullAllowed())
  1422. {
  1423. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1424. }
  1425. else
  1426. {
  1427. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1428. }
  1429. }
  1430. }
  1431. elseif(MetaModel::GetAttributeOrigin($sKeyClass, $sKeyAttCode) == $sTableClass)
  1432. {
  1433. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  1434. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1435. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1436. $sExternalKeyTable = $oJoinExpr->GetParent();
  1437. $sExternalKeyField = $oJoinExpr->GetName();
  1438. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  1439. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  1440. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  1441. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  1442. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  1443. }
  1444. }
  1445. }
  1446. }
  1447. // Translate the selected columns
  1448. //
  1449. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1450. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  1451. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1452. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1453. return $oSelectBase;
  1454. }
  1455. /**
  1456. * Get the friendly name for the class and its subclasses (if finalclass = 'subclass' ...)
  1457. * Simplifies the final expression by grouping classes having the same name expression
  1458. * Used when querying a parent class
  1459. */
  1460. static protected function GetExtendedNameExpression($sClass)
  1461. {
  1462. // 1st step - get all of the required expressions (instantiable classes)
  1463. // and group them using their OQL representation
  1464. //
  1465. $aFNExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes)
  1466. foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1467. {
  1468. if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) continue;
  1469. $oSubClassName = MetaModel::GetNameExpression($sSubClass);
  1470. $sSignature = $oSubClassName->Render();
  1471. if (!array_key_exists($sSignature, $aFNExpressions))
  1472. {
  1473. $aFNExpressions[$sSignature] = array(
  1474. 'expression' => $oSubClassName,
  1475. 'classes' => array(),
  1476. );
  1477. }
  1478. $aFNExpressions[$sSignature]['classes'][] = $sSubClass;
  1479. }
  1480. // 2nd step - build the final name expression depending on the finalclass
  1481. //
  1482. if (count($aFNExpressions) == 1)
  1483. {
  1484. $aExpData = reset($aFNExpressions);
  1485. $oNameExpression = $aExpData['expression'];
  1486. }
  1487. else
  1488. {
  1489. $oNameExpression = null;
  1490. foreach ($aFNExpressions as $sSignature => $aExpData)
  1491. {
  1492. $oClassListExpr = ListExpression::FromScalars($aExpData['classes']);
  1493. $oClassExpr = new FieldExpression('finalclass', $sClass);
  1494. $oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1495. if (is_null($oNameExpression))
  1496. {
  1497. $oNameExpression = $aExpData['expression'];
  1498. }
  1499. else
  1500. {
  1501. $oNameExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oNameExpression));
  1502. }
  1503. }
  1504. }
  1505. return $oNameExpression;
  1506. }
  1507. }