dbobjectsearch.class.php 58 KB

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