dbobjectsearch.class.php 63 KB

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