dbobjectsearch.class.php 59 KB

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