dbobjectsearch.class.php 61 KB

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