dbobjectsearch.class.php 61 KB

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