dbobjectsearch.class.php 58 KB

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