dbobjectsearch.class.php 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235
  1. <?php
  2. // Copyright (C) 2010-2017 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-2017 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. // Dev hack for disabling the some query build optimizations (Folding/Merging)
  25. define('ENABLE_OPT', true);
  26. class DBObjectSearch extends DBSearch
  27. {
  28. private $m_aClasses; // queried classes (alias => class name), the first item is the class corresponding to this filter (the rest is coming from subfilters)
  29. private $m_aSelectedClasses; // selected for the output (alias => class name)
  30. private $m_oSearchCondition;
  31. private $m_aParams;
  32. private $m_aFullText;
  33. private $m_aPointingTo;
  34. private $m_aReferencedBy;
  35. // By default, some information may be hidden to the current user
  36. // But it may happen that we need to disable that feature
  37. protected $m_bAllowAllData = false;
  38. protected $m_bDataFiltered = false;
  39. public function __construct($sClass, $sClassAlias = null)
  40. {
  41. parent::__construct();
  42. if (is_null($sClassAlias)) $sClassAlias = $sClass;
  43. if(!is_string($sClass)) throw new Exception('DBObjectSearch::__construct called with a non-string parameter: $sClass = '.print_r($sClass, true));
  44. if(!MetaModel::IsValidClass($sClass)) throw new Exception('DBObjectSearch::__construct called for an invalid class: "'.$sClass.'"');
  45. $this->m_aSelectedClasses = array($sClassAlias => $sClass);
  46. $this->m_aClasses = array($sClassAlias => $sClass);
  47. $this->m_oSearchCondition = new TrueExpression;
  48. $this->m_aParams = array();
  49. $this->m_aFullText = array();
  50. $this->m_aPointingTo = array();
  51. $this->m_aReferencedBy = array();
  52. }
  53. public function AllowAllData($bAllowAllData = true) {$this->m_bAllowAllData = $bAllowAllData;}
  54. public function IsAllDataAllowed() {return $this->m_bAllowAllData;}
  55. protected function IsDataFiltered() {return $this->m_bDataFiltered; }
  56. protected function SetDataFiltered() {$this->m_bDataFiltered = true;}
  57. // Create a search definition that leads to 0 result, still a valid search object
  58. static public function FromEmptySet($sClass)
  59. {
  60. $oResultFilter = new DBObjectSearch($sClass);
  61. $oResultFilter->m_oSearchCondition = new FalseExpression;
  62. return $oResultFilter;
  63. }
  64. public function GetJoinedClasses() {return $this->m_aClasses;}
  65. public function GetClassName($sAlias)
  66. {
  67. if (array_key_exists($sAlias, $this->m_aSelectedClasses))
  68. {
  69. return $this->m_aSelectedClasses[$sAlias];
  70. }
  71. else
  72. {
  73. throw new CoreException("Invalid class alias '$sAlias'");
  74. }
  75. }
  76. public function GetClass()
  77. {
  78. return reset($this->m_aSelectedClasses);
  79. }
  80. public function GetClassAlias()
  81. {
  82. reset($this->m_aSelectedClasses);
  83. return key($this->m_aSelectedClasses);
  84. }
  85. public function GetFirstJoinedClass()
  86. {
  87. return reset($this->m_aClasses);
  88. }
  89. public function GetFirstJoinedClassAlias()
  90. {
  91. reset($this->m_aClasses);
  92. return key($this->m_aClasses);
  93. }
  94. /**
  95. * Change the class (only subclasses are supported as of now, because the conditions must fit the new class)
  96. * Defaults to the first selected class (most of the time it is also the first joined class
  97. */
  98. public function ChangeClass($sNewClass, $sAlias = null)
  99. {
  100. if (is_null($sAlias))
  101. {
  102. $sAlias = $this->GetClassAlias();
  103. }
  104. else
  105. {
  106. if (!array_key_exists($sAlias, $this->m_aSelectedClasses))
  107. {
  108. // discard silently - necessary when recursing on the related nodes (see code below)
  109. return;
  110. }
  111. }
  112. $sCurrClass = $this->GetClassName($sAlias);
  113. if ($sNewClass == $sCurrClass)
  114. {
  115. // Skip silently
  116. return;
  117. }
  118. if (!MetaModel::IsParentClass($sCurrClass, $sNewClass))
  119. {
  120. throw new Exception("Could not change the search class from '$sCurrClass' to '$sNewClass'. Only child classes are permitted.");
  121. }
  122. // Change for this node
  123. //
  124. $this->m_aSelectedClasses[$sAlias] = $sNewClass;
  125. $this->m_aClasses[$sAlias] = $sNewClass;
  126. // Change for all the related node (yes, this was necessary with some queries - strange effects otherwise)
  127. //
  128. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  129. {
  130. foreach($aPointingTo as $iOperatorCode => $aFilter)
  131. {
  132. foreach($aFilter as $oExtFilter)
  133. {
  134. $oExtFilter->ChangeClass($sNewClass, $sAlias);
  135. }
  136. }
  137. }
  138. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  139. {
  140. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  141. {
  142. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  143. {
  144. foreach ($aFilters as $oForeignFilter)
  145. {
  146. $oForeignFilter->ChangeClass($sNewClass, $sAlias);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. public function GetSelectedClasses()
  153. {
  154. return $this->m_aSelectedClasses;
  155. }
  156. /**
  157. * @param array $aSelectedClasses array of aliases
  158. * @throws CoreException
  159. */
  160. public function SetSelectedClasses($aSelectedClasses)
  161. {
  162. $this->m_aSelectedClasses = array();
  163. foreach ($aSelectedClasses as $sAlias)
  164. {
  165. if (!array_key_exists($sAlias, $this->m_aClasses))
  166. {
  167. throw new CoreException("SetSelectedClasses: Invalid class alias $sAlias");
  168. }
  169. $this->m_aSelectedClasses[$sAlias] = $this->m_aClasses[$sAlias];
  170. }
  171. }
  172. /**
  173. * Change any alias of the query tree
  174. *
  175. * @param $sOldName
  176. * @param $sNewName
  177. * @return bool True if the alias has been found and changed
  178. */
  179. public function RenameAlias($sOldName, $sNewName)
  180. {
  181. $bFound = false;
  182. if (array_key_exists($sOldName, $this->m_aClasses))
  183. {
  184. $bFound = true;
  185. }
  186. if (array_key_exists($sNewName, $this->m_aClasses))
  187. {
  188. throw new Exception("RenameAlias: alias '$sNewName' already used");
  189. }
  190. $aClasses = array();
  191. foreach ($this->m_aClasses as $sAlias => $sClass)
  192. {
  193. if ($sAlias === $sOldName)
  194. {
  195. $aClasses[$sNewName] = $sClass;
  196. }
  197. else
  198. {
  199. $aClasses[$sAlias] = $sClass;
  200. }
  201. }
  202. $this->m_aClasses = $aClasses;
  203. $aSelectedClasses = array();
  204. foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
  205. {
  206. if ($sAlias === $sOldName)
  207. {
  208. $aSelectedClasses[$sNewName] = $sClass;
  209. }
  210. else
  211. {
  212. $aSelectedClasses[$sAlias] = $sClass;
  213. }
  214. }
  215. $this->m_aSelectedClasses = $aSelectedClasses;
  216. $this->m_oSearchCondition->RenameAlias($sOldName, $sNewName);
  217. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  218. {
  219. foreach($aPointingTo as $iOperatorCode => $aFilter)
  220. {
  221. foreach($aFilter as $oExtFilter)
  222. {
  223. $bFound = $oExtFilter->RenameAlias($sOldName, $sNewName) || $bFound;
  224. }
  225. }
  226. }
  227. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  228. {
  229. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  230. {
  231. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  232. {
  233. foreach ($aFilters as $oForeignFilter)
  234. {
  235. $bFound = $oForeignFilter->RenameAlias($sOldName, $sNewName) || $bFound;
  236. }
  237. }
  238. }
  239. }
  240. return $bFound;
  241. }
  242. public function SetModifierProperty($sPluginClass, $sProperty, $value)
  243. {
  244. $this->m_aModifierProperties[$sPluginClass][$sProperty] = $value;
  245. }
  246. public function GetModifierProperties($sPluginClass)
  247. {
  248. if (array_key_exists($sPluginClass, $this->m_aModifierProperties))
  249. {
  250. return $this->m_aModifierProperties[$sPluginClass];
  251. }
  252. else
  253. {
  254. return array();
  255. }
  256. }
  257. public function IsAny()
  258. {
  259. if (!$this->m_oSearchCondition->IsTrue()) return false;
  260. if (count($this->m_aFullText) > 0) return false;
  261. if (count($this->m_aPointingTo) > 0) return false;
  262. if (count($this->m_aReferencedBy) > 0) return false;
  263. return true;
  264. }
  265. protected function TransferConditionExpression($oFilter, $aTranslation)
  266. {
  267. // Prevent collisions in the parameter names by renaming them if needed
  268. foreach($this->m_aParams as $sParam => $value)
  269. {
  270. if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam]))
  271. {
  272. // Generate a new and unique name for the collinding parameter
  273. $index = 1;
  274. while(array_key_exists($sParam.$index, $oFilter->m_aParams))
  275. {
  276. $index++;
  277. }
  278. $secondValue = $oFilter->m_aParams[$sParam];
  279. $oFilter->RenameParam($sParam, $sParam.$index);
  280. unset($oFilter->m_aParams[$sParam]);
  281. $oFilter->m_aParams[$sParam.$index] = $secondValue;
  282. }
  283. }
  284. $oTranslated = $oFilter->GetCriteria()->Translate($aTranslation, false, false /* leave unresolved fields */);
  285. $this->AddConditionExpression($oTranslated);
  286. $this->m_aParams = array_merge($this->m_aParams, $oFilter->m_aParams);
  287. }
  288. protected function RenameParam($sOldName, $sNewName)
  289. {
  290. $this->m_oSearchCondition->RenameParam($sOldName, $sNewName);
  291. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  292. {
  293. foreach($aPointingTo as $iOperatorCode => $aFilter)
  294. {
  295. foreach($aFilter as $oExtFilter)
  296. {
  297. $oExtFilter->RenameParam($sOldName, $sNewName);
  298. }
  299. }
  300. }
  301. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  302. {
  303. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  304. {
  305. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  306. {
  307. foreach ($aFilters as $oForeignFilter)
  308. {
  309. $oForeignFilter->RenameParam($sOldName, $sNewName);
  310. }
  311. }
  312. }
  313. }
  314. }
  315. public function ResetCondition()
  316. {
  317. $this->m_oSearchCondition = new TrueExpression();
  318. // ? is that usefull/enough, do I need to rebuild the list after the subqueries ?
  319. }
  320. public function MergeConditionExpression($oExpression)
  321. {
  322. $this->m_oSearchCondition = $this->m_oSearchCondition->LogOr($oExpression);
  323. }
  324. public function AddConditionExpression($oExpression)
  325. {
  326. $this->m_oSearchCondition = $this->m_oSearchCondition->LogAnd($oExpression);
  327. }
  328. public function AddNameCondition($sName)
  329. {
  330. $oValueExpr = new ScalarExpression($sName);
  331. $oNameExpr = new FieldExpression('friendlyname', $this->GetClassAlias());
  332. $oNewCondition = new BinaryExpression($oNameExpr, '=', $oValueExpr);
  333. $this->AddConditionExpression($oNewCondition);
  334. }
  335. public function AddCondition($sFilterCode, $value, $sOpCode = null, $bParseSeachString = false)
  336. {
  337. MyHelpers::CheckKeyInArray('filter code in class: '.$this->GetClass(), $sFilterCode, MetaModel::GetClassFilterDefs($this->GetClass()));
  338. $oFilterDef = MetaModel::GetClassFilterDef($this->GetClass(), $sFilterCode);
  339. $oField = new FieldExpression($sFilterCode, $this->GetClassAlias());
  340. if (empty($sOpCode))
  341. {
  342. if ($sFilterCode == 'id')
  343. {
  344. $sOpCode = '=';
  345. }
  346. else
  347. {
  348. $oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sFilterCode);
  349. $oNewCondition = $oAttDef->GetSmartConditionExpression($value, $oField, $this->m_aParams, $bParseSeachString);
  350. $this->AddConditionExpression($oNewCondition);
  351. return;
  352. }
  353. }
  354. // Parse search strings if needed and if the filter code corresponds to a valid attcode
  355. if($bParseSeachString && MetaModel::IsValidAttCode($this->GetClass(), $sFilterCode))
  356. {
  357. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  358. $value = $oAttDef->ParseSearchString($value);
  359. }
  360. // Preserve backward compatibility - quick n'dirty way to change that API semantic
  361. //
  362. switch($sOpCode)
  363. {
  364. case 'SameDay':
  365. case 'SameMonth':
  366. case 'SameYear':
  367. case 'Today':
  368. case '>|':
  369. case '<|':
  370. case '=|':
  371. throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', array('operator' => $sOpCode));
  372. break;
  373. case "IN":
  374. if (!is_array($value)) $value = array($value);
  375. if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
  376. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  377. $sOQLCondition = $oField->Render()." IN $sListExpr";
  378. break;
  379. case "NOTIN":
  380. if (!is_array($value)) $value = array($value);
  381. if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
  382. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  383. $sOQLCondition = $oField->Render()." NOT IN $sListExpr";
  384. break;
  385. case 'Contains':
  386. $this->m_aParams[$sFilterCode] = "%$value%";
  387. $sOperator = 'LIKE';
  388. break;
  389. case 'Begins with':
  390. $this->m_aParams[$sFilterCode] = "$value%";
  391. $sOperator = 'LIKE';
  392. break;
  393. case 'Finishes with':
  394. $this->m_aParams[$sFilterCode] = "%$value";
  395. $sOperator = 'LIKE';
  396. break;
  397. default:
  398. if ($value === null)
  399. {
  400. switch ($sOpCode)
  401. {
  402. case '=':
  403. $sOpCode = '*Expression*';
  404. $oExpression = new FunctionExpression('ISNULL', array($oField));
  405. break;
  406. case '!=':
  407. $sOpCode = '*Expression*';
  408. $oExpression = new FunctionExpression('ISNULL', array($oField));
  409. $oExpression = new BinaryExpression($oExpression, '=', new ScalarExpression(0));
  410. break;
  411. default:
  412. throw new Exception("AddCondition on null value: unsupported operator '$sOpCode''");
  413. }
  414. }
  415. else
  416. {
  417. $this->m_aParams[$sFilterCode] = $value;
  418. $sOperator = $sOpCode;
  419. }
  420. }
  421. switch($sOpCode)
  422. {
  423. case '*Expression*':
  424. $oNewCondition = $oExpression;
  425. break;
  426. case "IN":
  427. case "NOTIN":
  428. $oNewCondition = Expression::FromOQL($sOQLCondition);
  429. break;
  430. case 'Contains':
  431. case 'Begins with':
  432. case 'Finishes with':
  433. default:
  434. $oRightExpr = new VariableExpression($sFilterCode);
  435. $oNewCondition = new BinaryExpression($oField, $sOperator, $oRightExpr);
  436. }
  437. $this->AddConditionExpression($oNewCondition);
  438. }
  439. /**
  440. * Specify a condition on external keys or link sets
  441. * @param sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
  442. * Example: infra_list->ci_id->location_id->country
  443. * @param value The value to match (can be an array => IN(val1, val2...)
  444. * @return void
  445. */
  446. public function AddConditionAdvanced($sAttSpec, $value)
  447. {
  448. $sClass = $this->GetClass();
  449. $iPos = strpos($sAttSpec, '->');
  450. if ($iPos !== false)
  451. {
  452. $sAttCode = substr($sAttSpec, 0, $iPos);
  453. $sSubSpec = substr($sAttSpec, $iPos + 2);
  454. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  455. {
  456. throw new Exception("Invalid attribute code '$sClass/$sAttCode' in condition specification '$sAttSpec'");
  457. }
  458. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  459. if ($oAttDef->IsLinkSet())
  460. {
  461. $sTargetClass = $oAttDef->GetLinkedClass();
  462. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  463. $oNewFilter = new DBObjectSearch($sTargetClass);
  464. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  465. $this->AddCondition_ReferencedBy($oNewFilter, $sExtKeyToMe);
  466. }
  467. elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  468. {
  469. $sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE);
  470. $oNewFilter = new DBObjectSearch($sTargetClass);
  471. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  472. $this->AddCondition_PointingTo($oNewFilter, $sAttCode);
  473. }
  474. else
  475. {
  476. throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key");
  477. }
  478. }
  479. else
  480. {
  481. // $sAttSpec is an attribute code
  482. //
  483. if (is_array($value))
  484. {
  485. $oField = new FieldExpression($sAttSpec, $this->GetClass());
  486. $oListExpr = ListExpression::FromScalars($value);
  487. $oInValues = new BinaryExpression($oField, 'IN', $oListExpr);
  488. $this->AddConditionExpression($oInValues);
  489. }
  490. else
  491. {
  492. $this->AddCondition($sAttSpec, $value);
  493. }
  494. }
  495. }
  496. public function AddCondition_FullText($sFullText)
  497. {
  498. $this->m_aFullText[] = $sFullText;
  499. }
  500. protected function AddToNameSpace(&$aClassAliases, &$aAliasTranslation, $bTranslateMainAlias = true)
  501. {
  502. if ($bTranslateMainAlias)
  503. {
  504. $sOrigAlias = $this->GetFirstJoinedClassAlias();
  505. if (array_key_exists($sOrigAlias, $aClassAliases))
  506. {
  507. $sNewAlias = MetaModel::GenerateUniqueAlias($aClassAliases, $sOrigAlias, $this->GetFirstJoinedClass());
  508. if (isset($this->m_aSelectedClasses[$sOrigAlias]))
  509. {
  510. $this->m_aSelectedClasses[$sNewAlias] = $this->GetFirstJoinedClass();
  511. unset($this->m_aSelectedClasses[$sOrigAlias]);
  512. }
  513. // TEMPORARY ALGORITHM (m_aClasses is not correctly updated, it is not possible to add a subtree onto a subnode)
  514. // Replace the element at the same position (unset + set is not enough because the hash array is ordered)
  515. $aPrevList = $this->m_aClasses;
  516. $this->m_aClasses = array();
  517. foreach ($aPrevList as $sSomeAlias => $sSomeClass)
  518. {
  519. if ($sSomeAlias == $sOrigAlias)
  520. {
  521. $this->m_aClasses[$sNewAlias] = $sSomeClass; // note: GetFirstJoinedClass now returns '' !!!
  522. }
  523. else
  524. {
  525. $this->m_aClasses[$sSomeAlias] = $sSomeClass;
  526. }
  527. }
  528. // Translate the condition expression with the new alias
  529. $aAliasTranslation[$sOrigAlias]['*'] = $sNewAlias;
  530. }
  531. // add the alias into the filter aliases list
  532. $aClassAliases[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
  533. }
  534. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  535. {
  536. foreach($aPointingTo as $iOperatorCode => $aFilter)
  537. {
  538. foreach($aFilter as $oFilter)
  539. {
  540. $oFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  541. }
  542. }
  543. }
  544. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  545. {
  546. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  547. {
  548. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  549. {
  550. foreach ($aFilters as $oForeignFilter)
  551. {
  552. $oForeignFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  553. }
  554. }
  555. }
  556. }
  557. }
  558. // Browse the tree nodes recursively
  559. //
  560. protected function GetNode($sAlias)
  561. {
  562. if ($this->GetFirstJoinedClassAlias() == $sAlias)
  563. {
  564. return $this;
  565. }
  566. else
  567. {
  568. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  569. {
  570. foreach($aPointingTo as $iOperatorCode => $aFilter)
  571. {
  572. foreach($aFilter as $oFilter)
  573. {
  574. $ret = $oFilter->GetNode($sAlias);
  575. if (is_object($ret))
  576. {
  577. return $ret;
  578. }
  579. }
  580. }
  581. }
  582. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  583. {
  584. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  585. {
  586. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  587. {
  588. foreach ($aFilters as $oForeignFilter)
  589. {
  590. $ret = $oForeignFilter->GetNode($sAlias);
  591. if (is_object($ret))
  592. {
  593. return $ret;
  594. }
  595. }
  596. }
  597. }
  598. }
  599. }
  600. // Not found
  601. return null;
  602. }
  603. /**
  604. * Helper to
  605. * - convert a translation table (format optimized for the translation in an expression tree) into simple hash
  606. * - compile over an eventually existing map
  607. *
  608. * @param $aRealiasingMap Map to update
  609. * @param $aAliasTranslation Translation table resulting from calls to MergeWith_InNamespace
  610. * @return array of <old-alias> => <new-alias>
  611. */
  612. protected function UpdateRealiasingMap(&$aRealiasingMap, $aAliasTranslation)
  613. {
  614. if ($aRealiasingMap !== null)
  615. {
  616. foreach ($aAliasTranslation as $sPrevAlias => $aRules)
  617. {
  618. if (isset($aRules['*']))
  619. {
  620. $sNewAlias = $aRules['*'];
  621. $sOriginalAlias = array_search($sPrevAlias, $aRealiasingMap);
  622. if ($sOriginalAlias !== false)
  623. {
  624. $aRealiasingMap[$sOriginalAlias] = $sNewAlias;
  625. }
  626. else
  627. {
  628. $aRealiasingMap[$sPrevAlias] = $sNewAlias;
  629. }
  630. }
  631. }
  632. }
  633. }
  634. /**
  635. * Completes the list of alias=>class by browsing the whole structure recursively
  636. * This a workaround to handle some cases in which the list of classes is not correctly updated.
  637. * This code should disappear as soon as DBObjectSearch get split between a container search class and a Node class
  638. *
  639. * @param $aClasses List to be completed
  640. */
  641. protected function RecomputeClassList(&$aClasses)
  642. {
  643. $aClasses[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
  644. // Recurse in the query tree
  645. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  646. {
  647. foreach($aPointingTo as $iOperatorCode => $aFilter)
  648. {
  649. foreach($aFilter as $oFilter)
  650. {
  651. $oFilter->RecomputeClassList($aClasses);
  652. }
  653. }
  654. }
  655. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  656. {
  657. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  658. {
  659. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  660. {
  661. foreach ($aFilters as $oForeignFilter)
  662. {
  663. $oForeignFilter->RecomputeClassList($aClasses);
  664. }
  665. }
  666. }
  667. }
  668. }
  669. /**
  670. * @param DBObjectSearch $oFilter
  671. * @param $sExtKeyAttCode
  672. * @param int $iOperatorCode
  673. * @param null $aRealiasingMap array of <old-alias> => <new-alias>, for each alias that has changed
  674. * @throws CoreException
  675. * @throws CoreWarning
  676. */
  677. public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
  678. {
  679. if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode))
  680. {
  681. throw new CoreWarning("The attribute code '$sExtKeyAttCode' is not an external key of the class '{$this->GetClass()}'");
  682. }
  683. $oAttExtKey = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
  684. if(!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass()))
  685. {
  686. 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()}");
  687. }
  688. if(($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey))
  689. {
  690. throw new CoreException("The specified tree operator $iOperatorCode is not applicable to the key '{$this->GetClass()}::$sExtKeyAttCode', which is not a HierarchicalKey");
  691. }
  692. // Note: though it seems to be a good practice to clone the given source filter
  693. // (as it was done and fixed an issue in Intersect())
  694. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  695. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  696. // NO: $oFilter = $oFilter->DeepClone();
  697. // See also: Trac #639, and self::AddCondition_ReferencedBy()
  698. $aAliasTranslation = array();
  699. $res = $this->AddCondition_PointingTo_InNameSpace($oFilter, $sExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
  700. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  701. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  702. if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass()))
  703. {
  704. if (isset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode]))
  705. {
  706. foreach ($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode] as $oRemoteFilter)
  707. {
  708. if ($this->GetClass() == $oRemoteFilter->GetClass())
  709. {
  710. // Optimization - fold sibling query
  711. $aAliasTranslation = array();
  712. $this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation);
  713. unset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode]);
  714. $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false);
  715. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  716. break;
  717. }
  718. }
  719. }
  720. }
  721. $this->RecomputeClassList($this->m_aClasses);
  722. return $res;
  723. }
  724. protected function AddCondition_PointingTo_InNameSpace(DBObjectSearch $oFilter, $sExtKeyAttCode, &$aClassAliases, &$aAliasTranslation, $iOperatorCode)
  725. {
  726. // Find the node on which the new tree must be attached (most of the time it is "this")
  727. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  728. $bMerged = false;
  729. if (ENABLE_OPT && isset($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode]))
  730. {
  731. foreach ($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode] as $oExisting)
  732. {
  733. if ($oExisting->GetClass() == $oFilter->GetClass())
  734. {
  735. $oExisting->MergeWith_InNamespace($oFilter, $oExisting->m_aClasses, $aAliasTranslation);
  736. $bMerged = true;
  737. break;
  738. }
  739. }
  740. }
  741. if (!$bMerged)
  742. {
  743. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  744. $oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode][] = $oFilter;
  745. }
  746. }
  747. /**
  748. * @param DBObjectSearch $oFilter
  749. * @param $sForeignExtKeyAttCode
  750. * @param int $iOperatorCode
  751. * @param null $aRealiasingMap array of <old-alias> => <new-alias>, for each alias that has changed
  752. */
  753. public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
  754. {
  755. $sForeignClass = $oFilter->GetClass();
  756. if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode))
  757. {
  758. throw new CoreException("The attribute code '$sForeignExtKeyAttCode' is not an external key of the class '{$sForeignClass}'");
  759. }
  760. $oAttExtKey = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  761. if(!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass()))
  762. {
  763. // à refaire en spécifique dans FromOQL
  764. 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()}");
  765. }
  766. // Note: though it seems to be a good practice to clone the given source filter
  767. // (as it was done and fixed an issue in Intersect())
  768. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  769. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  770. // NO: $oFilter = $oFilter->DeepClone();
  771. // See also: Trac #639, and self::AddCondition_PointingTo()
  772. $aAliasTranslation = array();
  773. $res = $this->AddCondition_ReferencedBy_InNameSpace($oFilter, $sForeignExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
  774. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  775. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  776. if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass()))
  777. {
  778. if (isset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode]))
  779. {
  780. foreach ($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode] as $oRemoteFilter)
  781. {
  782. if ($this->GetClass() == $oRemoteFilter->GetClass())
  783. {
  784. // Optimization - fold sibling query
  785. $aAliasTranslation = array();
  786. $this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation);
  787. unset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode]);
  788. $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false);
  789. $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
  790. break;
  791. }
  792. }
  793. }
  794. }
  795. $this->RecomputeClassList($this->m_aClasses);
  796. return $res;
  797. }
  798. protected function AddCondition_ReferencedBy_InNameSpace(DBSearch $oFilter, $sForeignExtKeyAttCode, &$aClassAliases, &$aAliasTranslation, $iOperatorCode)
  799. {
  800. $sForeignClass = $oFilter->GetClass();
  801. // Find the node on which the new tree must be attached (most of the time it is "this")
  802. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  803. $bMerged = false;
  804. if (ENABLE_OPT && isset($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode]))
  805. {
  806. foreach ($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode] as $oExisting)
  807. {
  808. if ($oExisting->GetClass() == $oFilter->GetClass())
  809. {
  810. $oExisting->MergeWith_InNamespace($oFilter, $oExisting->m_aClasses, $aAliasTranslation);
  811. $bMerged = true;
  812. break;
  813. }
  814. }
  815. }
  816. if (!$bMerged)
  817. {
  818. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  819. $oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode][] = $oFilter;
  820. }
  821. }
  822. public function Intersect(DBSearch $oFilter)
  823. {
  824. if ($oFilter instanceof DBUnionSearch)
  825. {
  826. // Develop!
  827. $aFilters = $oFilter->GetSearches();
  828. }
  829. else
  830. {
  831. $aFilters = array($oFilter);
  832. }
  833. $aSearches = array();
  834. foreach ($aFilters as $oRightFilter)
  835. {
  836. // Limitation: the queried class must be the first declared class
  837. if ($this->GetFirstJoinedClassAlias() != $this->GetClassAlias())
  838. {
  839. 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()})");
  840. }
  841. if ($oRightFilter->GetFirstJoinedClassAlias() != $oRightFilter->GetClassAlias())
  842. {
  843. 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()})");
  844. }
  845. $oLeftFilter = $this->DeepClone();
  846. $oRightFilter = $oRightFilter->DeepClone();
  847. $bAllowAllData = ($oLeftFilter->IsAllDataAllowed() && $oRightFilter->IsAllDataAllowed());
  848. $oLeftFilter->AllowAllData($bAllowAllData);
  849. if ($oLeftFilter->GetClass() != $oRightFilter->GetClass())
  850. {
  851. if (MetaModel::IsParentClass($oLeftFilter->GetClass(), $oRightFilter->GetClass()))
  852. {
  853. // Specialize $oLeftFilter
  854. $oLeftFilter->ChangeClass($oRightFilter->GetClass());
  855. }
  856. elseif (MetaModel::IsParentClass($oRightFilter->GetClass(), $oLeftFilter->GetClass()))
  857. {
  858. // Specialize $oRightFilter
  859. $oRightFilter->ChangeClass($oLeftFilter->GetClass());
  860. }
  861. else
  862. {
  863. throw new CoreException("Attempting to merge a filter of class '{$oLeftFilter->GetClass()}' with a filter of class '{$oRightFilter->GetClass()}'");
  864. }
  865. }
  866. $aAliasTranslation = array();
  867. $oLeftFilter->MergeWith_InNamespace($oRightFilter, $oLeftFilter->m_aClasses, $aAliasTranslation);
  868. $oLeftFilter->TransferConditionExpression($oRightFilter, $aAliasTranslation);
  869. $aSearches[] = $oLeftFilter;
  870. }
  871. if (count($aSearches) == 1)
  872. {
  873. // return a DBObjectSearch
  874. return $aSearches[0];
  875. }
  876. else
  877. {
  878. return new DBUnionSearch($aSearches);
  879. }
  880. }
  881. protected function MergeWith_InNamespace($oFilter, &$aClassAliases, &$aAliasTranslation)
  882. {
  883. if ($this->GetClass() != $oFilter->GetClass())
  884. {
  885. throw new CoreException("Attempting to merge a filter of class '{$this->GetClass()}' with a filter of class '{$oFilter->GetClass()}'");
  886. }
  887. // Translate search condition into our aliasing scheme
  888. $aAliasTranslation[$oFilter->GetClassAlias()]['*'] = $this->GetClassAlias();
  889. $this->m_aFullText = array_merge($this->m_aFullText, $oFilter->m_aFullText);
  890. foreach($oFilter->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  891. {
  892. foreach($aPointingTo as $iOperatorCode => $aFilter)
  893. {
  894. foreach($aFilter as $oExtFilter)
  895. {
  896. $this->AddCondition_PointingTo_InNamespace($oExtFilter, $sExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
  897. }
  898. }
  899. }
  900. foreach($oFilter->m_aReferencedBy as $sForeignClass => $aReferences)
  901. {
  902. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  903. {
  904. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  905. {
  906. foreach ($aFilters as $oForeignFilter)
  907. {
  908. $this->AddCondition_ReferencedBy_InNamespace($oForeignFilter, $sForeignExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
  909. }
  910. }
  911. }
  912. }
  913. }
  914. public function GetCriteria() {return $this->m_oSearchCondition;}
  915. public function GetCriteria_FullText() {return $this->m_aFullText;}
  916. protected function GetCriteria_PointingTo($sKeyAttCode = "")
  917. {
  918. if (empty($sKeyAttCode))
  919. {
  920. return $this->m_aPointingTo;
  921. }
  922. if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) return array();
  923. return $this->m_aPointingTo[$sKeyAttCode];
  924. }
  925. protected function GetCriteria_ReferencedBy()
  926. {
  927. return $this->m_aReferencedBy;
  928. }
  929. public function SetInternalParams($aParams)
  930. {
  931. return $this->m_aParams = $aParams;
  932. }
  933. public function GetInternalParams()
  934. {
  935. return $this->m_aParams;
  936. }
  937. public function GetQueryParams($bExcludeMagicParams = true)
  938. {
  939. $aParams = array();
  940. $this->m_oSearchCondition->Render($aParams, true);
  941. if ($bExcludeMagicParams)
  942. {
  943. $aRet = array();
  944. // Make the list of acceptable arguments... could be factorized with run_query, into oSearch->GetQueryParams($bExclude magic params)
  945. $aNakedMagicArguments = array();
  946. foreach (MetaModel::PrepareQueryArguments(array()) as $sArgName => $value)
  947. {
  948. $iPos = strpos($sArgName, '->object()');
  949. if ($iPos === false)
  950. {
  951. $aNakedMagicArguments[$sArgName] = $value;
  952. }
  953. else
  954. {
  955. $aNakedMagicArguments[substr($sArgName, 0, $iPos)] = true;
  956. }
  957. }
  958. foreach ($aParams as $sParam => $foo)
  959. {
  960. $iPos = strpos($sParam, '->');
  961. if ($iPos === false)
  962. {
  963. $sRefName = $sParam;
  964. }
  965. else
  966. {
  967. $sRefName = substr($sParam, 0, $iPos);
  968. }
  969. if (!array_key_exists($sRefName, $aNakedMagicArguments))
  970. {
  971. $aRet[$sParam] = $foo;
  972. }
  973. }
  974. }
  975. return $aRet;
  976. }
  977. public function ListConstantFields()
  978. {
  979. return $this->m_oSearchCondition->ListConstantFields();
  980. }
  981. /**
  982. * Turn the parameters (:xxx) into scalar values in order to easily
  983. * serialize a search
  984. */
  985. public function ApplyParameters($aArgs)
  986. {
  987. return $this->m_oSearchCondition->ApplyParameters(array_merge($this->m_aParams, $aArgs));
  988. }
  989. public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false)
  990. {
  991. // Currently unused, but could be useful later
  992. $bRetrofitParams = false;
  993. if ($bDevelopParams)
  994. {
  995. if (is_null($aContextParams))
  996. {
  997. $aParams = array_merge($this->m_aParams);
  998. }
  999. else
  1000. {
  1001. $aParams = array_merge($aContextParams, $this->m_aParams);
  1002. }
  1003. $aParams = MetaModel::PrepareQueryArguments($aParams);
  1004. }
  1005. else
  1006. {
  1007. // Leave it as is, the rendering will be made with parameters in clear
  1008. $aParams = null;
  1009. }
  1010. $aSelectedAliases = array();
  1011. foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
  1012. {
  1013. $aSelectedAliases[] = '`' . $sAlias . '`';
  1014. }
  1015. $sSelectedClasses = implode(', ', $aSelectedAliases);
  1016. $sRes = 'SELECT '.$sSelectedClasses.' FROM';
  1017. $sRes .= ' ' . $this->GetFirstJoinedClass() . ' AS `' . $this->GetFirstJoinedClassAlias() . '`';
  1018. $sRes .= $this->ToOQL_Joins();
  1019. $sRes .= " WHERE ".$this->m_oSearchCondition->Render($aParams, $bRetrofitParams);
  1020. // Temporary: add more info about other conditions, necessary to avoid strange behaviors with the cache
  1021. foreach($this->m_aFullText as $sFullText)
  1022. {
  1023. $sRes .= " AND MATCHES '$sFullText'";
  1024. }
  1025. if ($bWithAllowAllFlag && $this->m_bAllowAllData)
  1026. {
  1027. $sRes .= " ALLOW ALL DATA";
  1028. }
  1029. return $sRes;
  1030. }
  1031. protected function OperatorCodeToOQL($iOperatorCode)
  1032. {
  1033. switch($iOperatorCode)
  1034. {
  1035. case TREE_OPERATOR_EQUALS:
  1036. $sOperator = ' = ';
  1037. break;
  1038. case TREE_OPERATOR_BELOW:
  1039. $sOperator = ' BELOW ';
  1040. break;
  1041. case TREE_OPERATOR_BELOW_STRICT:
  1042. $sOperator = ' BELOW STRICT ';
  1043. break;
  1044. case TREE_OPERATOR_NOT_BELOW:
  1045. $sOperator = ' NOT BELOW ';
  1046. break;
  1047. case TREE_OPERATOR_NOT_BELOW_STRICT:
  1048. $sOperator = ' NOT BELOW STRICT ';
  1049. break;
  1050. case TREE_OPERATOR_ABOVE:
  1051. $sOperator = ' ABOVE ';
  1052. break;
  1053. case TREE_OPERATOR_ABOVE_STRICT:
  1054. $sOperator = ' ABOVE STRICT ';
  1055. break;
  1056. case TREE_OPERATOR_NOT_ABOVE:
  1057. $sOperator = ' NOT ABOVE ';
  1058. break;
  1059. case TREE_OPERATOR_NOT_ABOVE_STRICT:
  1060. $sOperator = ' NOT ABOVE STRICT ';
  1061. break;
  1062. }
  1063. return $sOperator;
  1064. }
  1065. protected function ToOQL_Joins()
  1066. {
  1067. $sRes = '';
  1068. foreach($this->m_aPointingTo as $sExtKey => $aPointingTo)
  1069. {
  1070. foreach($aPointingTo as $iOperatorCode => $aFilter)
  1071. {
  1072. $sOperator = $this->OperatorCodeToOQL($iOperatorCode);
  1073. foreach($aFilter as $oFilter)
  1074. {
  1075. $sRes .= ' JOIN ' . $oFilter->GetFirstJoinedClass() . ' AS `' . $oFilter->GetFirstJoinedClassAlias() . '` ON `' . $this->GetFirstJoinedClassAlias() . '`.' . $sExtKey . $sOperator . '`' . $oFilter->GetFirstJoinedClassAlias() . '`.id';
  1076. $sRes .= $oFilter->ToOQL_Joins();
  1077. }
  1078. }
  1079. }
  1080. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  1081. {
  1082. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  1083. {
  1084. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  1085. {
  1086. $sOperator = $this->OperatorCodeToOQL($iOperatorCode);
  1087. foreach ($aFilters as $oForeignFilter)
  1088. {
  1089. $sRes .= ' JOIN ' . $oForeignFilter->GetFirstJoinedClass() . ' AS `' . $oForeignFilter->GetFirstJoinedClassAlias() . '` ON `' . $oForeignFilter->GetFirstJoinedClassAlias() . '`.' . $sForeignExtKeyAttCode . $sOperator . '`' . $this->GetFirstJoinedClassAlias() . '`.id';
  1090. $sRes .= $oForeignFilter->ToOQL_Joins();
  1091. }
  1092. }
  1093. }
  1094. }
  1095. return $sRes;
  1096. }
  1097. protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases)
  1098. {
  1099. if ($oExpression instanceof BinaryOqlExpression)
  1100. {
  1101. $sOperator = $oExpression->GetOperator();
  1102. $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
  1103. $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
  1104. return new BinaryExpression($oLeft, $sOperator, $oRight);
  1105. }
  1106. elseif ($oExpression instanceof FieldOqlExpression)
  1107. {
  1108. $sClassAlias = $oExpression->GetParent();
  1109. $sFltCode = $oExpression->GetName();
  1110. if (empty($sClassAlias))
  1111. {
  1112. // Need to find the right alias
  1113. // Build an array of field => array of aliases
  1114. $aFieldClasses = array();
  1115. foreach($aClassAliases as $sAlias => $sReal)
  1116. {
  1117. foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode)
  1118. {
  1119. $aFieldClasses[$sAnFltCode][] = $sAlias;
  1120. }
  1121. }
  1122. $sClassAlias = $aFieldClasses[$sFltCode][0];
  1123. }
  1124. return new FieldExpression($sFltCode, $sClassAlias);
  1125. }
  1126. elseif ($oExpression instanceof VariableOqlExpression)
  1127. {
  1128. return new VariableExpression($oExpression->GetName());
  1129. }
  1130. elseif ($oExpression instanceof TrueOqlExpression)
  1131. {
  1132. return new TrueExpression;
  1133. }
  1134. elseif ($oExpression instanceof ScalarOqlExpression)
  1135. {
  1136. return new ScalarExpression($oExpression->GetValue());
  1137. }
  1138. elseif ($oExpression instanceof ListOqlExpression)
  1139. {
  1140. $aItems = array();
  1141. foreach ($oExpression->GetItems() as $oItemExpression)
  1142. {
  1143. $aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases);
  1144. }
  1145. return new ListExpression($aItems);
  1146. }
  1147. elseif ($oExpression instanceof FunctionOqlExpression)
  1148. {
  1149. $aArgs = array();
  1150. foreach ($oExpression->GetArgs() as $oArgExpression)
  1151. {
  1152. $aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases);
  1153. }
  1154. return new FunctionExpression($oExpression->GetVerb(), $aArgs);
  1155. }
  1156. elseif ($oExpression instanceof IntervalOqlExpression)
  1157. {
  1158. return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit());
  1159. }
  1160. else
  1161. {
  1162. throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery));
  1163. }
  1164. }
  1165. public function InitFromOqlQuery(OqlQuery $oOqlQuery, $sQuery)
  1166. {
  1167. $oModelReflection = new ModelReflectionRuntime();
  1168. $sClass = $oOqlQuery->GetClass($oModelReflection);
  1169. $sClassAlias = $oOqlQuery->GetClassAlias();
  1170. $aAliases = array($sClassAlias => $sClass);
  1171. // Note: the condition must be built here, it may be altered later on when optimizing some joins
  1172. $oConditionTree = $oOqlQuery->GetCondition();
  1173. if ($oConditionTree instanceof Expression)
  1174. {
  1175. $aRawAliases = array($sClassAlias => $sClass);
  1176. $aJoinSpecs = $oOqlQuery->GetJoins();
  1177. if (is_array($aJoinSpecs))
  1178. {
  1179. foreach ($aJoinSpecs as $oJoinSpec)
  1180. {
  1181. $aRawAliases[$oJoinSpec->GetClassAlias()] = $oJoinSpec->GetClass();
  1182. }
  1183. }
  1184. $this->m_oSearchCondition = $this->OQLExpressionToCondition($sQuery, $oConditionTree, $aRawAliases);
  1185. }
  1186. // Maintain an array of filters, because the flat list is in fact referring to a tree
  1187. // And this will be an easy way to dispatch the conditions
  1188. // $this will be referenced by the other filters, or the other way around...
  1189. $aJoinItems = array($sClassAlias => $this);
  1190. $aJoinSpecs = $oOqlQuery->GetJoins();
  1191. if (is_array($aJoinSpecs))
  1192. {
  1193. $aAliasTranslation = array();
  1194. foreach ($aJoinSpecs as $oJoinSpec)
  1195. {
  1196. $sJoinClass = $oJoinSpec->GetClass();
  1197. $sJoinClassAlias = $oJoinSpec->GetClassAlias();
  1198. if (isset($aAliasTranslation[$sJoinClassAlias]['*']))
  1199. {
  1200. $sJoinClassAlias = $aAliasTranslation[$sJoinClassAlias]['*'];
  1201. }
  1202. // Assumption: ext key on the left only !!!
  1203. // normalization should take care of this
  1204. $oLeftField = $oJoinSpec->GetLeftField();
  1205. $sFromClass = $oLeftField->GetParent();
  1206. if (isset($aAliasTranslation[$sFromClass]['*']))
  1207. {
  1208. $sFromClass = $aAliasTranslation[$sFromClass]['*'];
  1209. }
  1210. $sExtKeyAttCode = $oLeftField->GetName();
  1211. $oRightField = $oJoinSpec->GetRightField();
  1212. $sToClass = $oRightField->GetParent();
  1213. if (isset($aAliasTranslation[$sToClass]['*']))
  1214. {
  1215. $sToClass = $aAliasTranslation[$sToClass]['*'];
  1216. }
  1217. $aAliases[$sJoinClassAlias] = $sJoinClass;
  1218. $aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias);
  1219. $sOperator = $oJoinSpec->GetOperator();
  1220. switch($sOperator)
  1221. {
  1222. case '=':
  1223. default:
  1224. $iOperatorCode = TREE_OPERATOR_EQUALS;
  1225. break;
  1226. case 'BELOW':
  1227. $iOperatorCode = TREE_OPERATOR_BELOW;
  1228. break;
  1229. case 'BELOW_STRICT':
  1230. $iOperatorCode = TREE_OPERATOR_BELOW_STRICT;
  1231. break;
  1232. case 'NOT_BELOW':
  1233. $iOperatorCode = TREE_OPERATOR_NOT_BELOW;
  1234. break;
  1235. case 'NOT_BELOW_STRICT':
  1236. $iOperatorCode = TREE_OPERATOR_NOT_BELOW_STRICT;
  1237. break;
  1238. case 'ABOVE':
  1239. $iOperatorCode = TREE_OPERATOR_ABOVE;
  1240. break;
  1241. case 'ABOVE_STRICT':
  1242. $iOperatorCode = TREE_OPERATOR_ABOVE_STRICT;
  1243. break;
  1244. case 'NOT_ABOVE':
  1245. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE;
  1246. break;
  1247. case 'NOT_ABOVE_STRICT':
  1248. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE_STRICT;
  1249. break;
  1250. }
  1251. if ($sFromClass == $sJoinClassAlias)
  1252. {
  1253. $oReceiver = $aJoinItems[$sToClass];
  1254. $oNewComer = $aJoinItems[$sFromClass];
  1255. $oReceiver->AddCondition_ReferencedBy_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
  1256. }
  1257. else
  1258. {
  1259. $oReceiver = $aJoinItems[$sFromClass];
  1260. $oNewComer = $aJoinItems[$sToClass];
  1261. $oReceiver->AddCondition_PointingTo_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
  1262. }
  1263. }
  1264. $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false /* leave unresolved fields */);
  1265. }
  1266. // Check and prepare the select information
  1267. $this->m_aSelectedClasses = array();
  1268. foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails)
  1269. {
  1270. $sClassToSelect = $oClassDetails->GetValue();
  1271. $this->m_aSelectedClasses[$sClassToSelect] = $aAliases[$sClassToSelect];
  1272. }
  1273. $this->m_aClasses = $aAliases;
  1274. }
  1275. ////////////////////////////////////////////////////////////////////////////
  1276. //
  1277. // Construction of the SQL queries
  1278. //
  1279. ////////////////////////////////////////////////////////////////////////////
  1280. public function MakeDeleteQuery($aArgs = array())
  1281. {
  1282. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  1283. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  1284. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, array($this->GetClassAlias() => array()), array());
  1285. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  1286. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  1287. $oSQLQuery->OptimizeJoins(array());
  1288. $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams());
  1289. $sRet = $oSQLQuery->RenderDelete($aScalarArgs);
  1290. return $sRet;
  1291. }
  1292. public function MakeUpdateQuery($aValues, $aArgs = array())
  1293. {
  1294. // $aValues is an array of $sAttCode => $value
  1295. $aModifierProperties = MetaModel::MakeModifierProperties($this);
  1296. $oBuild = new QueryBuilderContext($this, $aModifierProperties);
  1297. $aRequested = array(); // Requested attributes are the updated attributes
  1298. foreach ($aValues as $sAttCode => $value)
  1299. {
  1300. $aRequested[$sAttCode] = MetaModel::GetAttributeDef($this->GetClass(), $sAttCode);
  1301. }
  1302. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, array($this->GetClassAlias() => $aRequested), $aValues);
  1303. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  1304. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  1305. $oSQLQuery->OptimizeJoins(array());
  1306. $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams());
  1307. $sRet = $oSQLQuery->RenderUpdate($aScalarArgs);
  1308. return $sRet;
  1309. }
  1310. public function GetSQLQueryStructure($aAttToLoad, $bGetCount, $aGroupByExpr = null, $aSelectedClasses = null)
  1311. {
  1312. // Hide objects that are not visible to the current user
  1313. //
  1314. $oSearch = $this;
  1315. if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered())
  1316. {
  1317. $oVisibleObjects = UserRights::GetSelectFilter($this->GetClass(), $this->GetModifierProperties('UserRightsGetSelectFilter'));
  1318. if ($oVisibleObjects === false)
  1319. {
  1320. // Make sure this is a valid search object, saying NO for all
  1321. $oVisibleObjects = DBObjectSearch::FromEmptySet($this->GetClass());
  1322. }
  1323. if (is_object($oVisibleObjects))
  1324. {
  1325. $oVisibleObjects->AllowAllData();
  1326. $oSearch = $this->Intersect($oVisibleObjects);
  1327. $oSearch->SetDataFiltered();
  1328. }
  1329. else
  1330. {
  1331. // should be true at this point, meaning that no additional filtering
  1332. // is required
  1333. }
  1334. }
  1335. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  1336. //
  1337. $aModifierProperties = MetaModel::MakeModifierProperties($oSearch);
  1338. // Create a unique cache id
  1339. //
  1340. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  1341. {
  1342. // Need to identify the query
  1343. $sOqlQuery = $oSearch->ToOql(false, null, true);
  1344. if (count($aModifierProperties))
  1345. {
  1346. array_multisort($aModifierProperties);
  1347. $sModifierProperties = json_encode($aModifierProperties);
  1348. }
  1349. else
  1350. {
  1351. $sModifierProperties = '';
  1352. }
  1353. $sRawId = $sOqlQuery.$sModifierProperties;
  1354. if (!is_null($aAttToLoad))
  1355. {
  1356. $sRawId .= json_encode($aAttToLoad);
  1357. }
  1358. if (!is_null($aGroupByExpr))
  1359. {
  1360. foreach($aGroupByExpr as $sAlias => $oExpr)
  1361. {
  1362. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  1363. }
  1364. }
  1365. $sRawId .= $bGetCount;
  1366. if (is_array($aSelectedClasses))
  1367. {
  1368. $sRawId .= implode(',', $aSelectedClasses); // Unions may alter the list of selected columns
  1369. }
  1370. $sRawId .= $oSearch->GetArchiveMode() ? '--arch' : '';
  1371. $sRawId .= $oSearch->GetShowObsoleteData() ? '--obso' : '';
  1372. $sOqlId = md5($sRawId);
  1373. }
  1374. else
  1375. {
  1376. $sOqlQuery = "SELECTING... ".$oSearch->GetClass();
  1377. $sOqlId = "query id ? n/a";
  1378. }
  1379. // Query caching
  1380. //
  1381. if (self::$m_bQueryCacheEnabled)
  1382. {
  1383. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  1384. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  1385. // to use a hash (like md5) of the string as the key !
  1386. //
  1387. // Example of two queries that were found as similar by the hash array:
  1388. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTO' AND CustomerContract.customer_id = 2
  1389. // and
  1390. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2
  1391. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  1392. //
  1393. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  1394. {
  1395. // hit!
  1396. $oSQLQuery = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  1397. // Note: cloning is not enough because the subtree is made of objects
  1398. }
  1399. elseif (self::$m_bUseAPCCache)
  1400. {
  1401. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  1402. //
  1403. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  1404. $oKPI = new ExecutionKPI();
  1405. $result = apc_fetch($sOqlAPCCacheId);
  1406. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  1407. if (is_object($result))
  1408. {
  1409. $oSQLQuery = $result;
  1410. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery;
  1411. }
  1412. }
  1413. }
  1414. if (!isset($oSQLQuery))
  1415. {
  1416. $oKPI = new ExecutionKPI();
  1417. $oSQLQuery = $oSearch->BuildSQLQueryStruct($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr, $aSelectedClasses);
  1418. $oKPI->ComputeStats('BuildSQLQueryStruct', $sOqlQuery);
  1419. if (self::$m_bQueryCacheEnabled)
  1420. {
  1421. if (self::$m_bUseAPCCache)
  1422. {
  1423. $oKPI = new ExecutionKPI();
  1424. apc_store($sOqlAPCCacheId, $oSQLQuery, self::$m_iQueryCacheTTL);
  1425. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  1426. }
  1427. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery->DeepClone();
  1428. }
  1429. }
  1430. return $oSQLQuery;
  1431. }
  1432. protected function BuildSQLQueryStruct($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr = null, $aSelectedClasses = null)
  1433. {
  1434. $oBuild = new QueryBuilderContext($this, $aModifierProperties, $aGroupByExpr, $aSelectedClasses);
  1435. $oSQLQuery = $this->MakeSQLObjectQuery($oBuild, $aAttToLoad, array());
  1436. $oSQLQuery->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  1437. if ($aGroupByExpr)
  1438. {
  1439. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  1440. $oSQLQuery->SetGroupBy($aCols);
  1441. $oSQLQuery->SetSelect($aCols);
  1442. }
  1443. else
  1444. {
  1445. $oSQLQuery->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  1446. }
  1447. $aMandatoryTables = null;
  1448. if (self::$m_bOptimizeQueries)
  1449. {
  1450. if ($bGetCount)
  1451. {
  1452. // Simplify the query if just getting the count
  1453. $oSQLQuery->SetSelect(array());
  1454. }
  1455. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  1456. $oSQLQuery->OptimizeJoins($aMandatoryTables);
  1457. }
  1458. // Filter tables as late as possible: do not interfere with the optimization process
  1459. foreach ($oBuild->GetFilteredTables() as $sTableAlias => $aConditions)
  1460. {
  1461. if ($aMandatoryTables && array_key_exists($sTableAlias, $aMandatoryTables))
  1462. {
  1463. foreach ($aConditions as $oCondition)
  1464. {
  1465. $oSQLQuery->AddCondition($oCondition);
  1466. }
  1467. }
  1468. }
  1469. return $oSQLQuery;
  1470. }
  1471. protected function MakeSQLObjectQuery(&$oBuild, $aAttToLoad = null, $aValues = array())
  1472. {
  1473. // Note: query class might be different than the class of the filter
  1474. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1475. $sClass = $this->GetFirstJoinedClass();
  1476. $sClassAlias = $this->GetFirstJoinedClassAlias();
  1477. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  1478. self::DbgTrace("Entering: ".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1479. $sRootClass = MetaModel::GetRootClass($sClass);
  1480. $sKeyField = MetaModel::DBGetKey($sClass);
  1481. if ($bIsOnQueriedClass)
  1482. {
  1483. // default to the whole list of attributes + the very std id/finalclass
  1484. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  1485. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  1486. {
  1487. $sSelectedClass = $oBuild->GetSelectedClass($sClassAlias);
  1488. $aAttList = MetaModel::ListAttributeDefs($sSelectedClass);
  1489. }
  1490. else
  1491. {
  1492. $aAttList = $aAttToLoad[$sClassAlias];
  1493. }
  1494. foreach ($aAttList as $sAttCode => $oAttDef)
  1495. {
  1496. if (!$oAttDef->IsScalar()) continue;
  1497. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  1498. if ($oAttDef->IsBasedOnOQLExpression())
  1499. {
  1500. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode, new FieldExpression($sAttCode, $sClassAlias));
  1501. }
  1502. else
  1503. {
  1504. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1505. {
  1506. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  1507. }
  1508. }
  1509. }
  1510. // Transform the full text condition into additional condition expression
  1511. $aFullText = $this->GetCriteria_FullText();
  1512. if (count($aFullText) > 0)
  1513. {
  1514. $aFullTextFields = array();
  1515. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1516. {
  1517. if (!$oAttDef->IsScalar()) continue;
  1518. if ($oAttDef->IsExternalKey()) continue;
  1519. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  1520. }
  1521. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  1522. foreach($aFullText as $sFTNeedle)
  1523. {
  1524. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  1525. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  1526. }
  1527. }
  1528. }
  1529. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  1530. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  1531. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  1532. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  1533. // Compute a clear view of required joins (from the current class)
  1534. // Build the list of external keys:
  1535. // -> ext keys required by an explicit join
  1536. // -> ext keys mentionned in a 'pointing to' condition
  1537. // -> ext keys required for an external field
  1538. // -> ext keys required for a friendly name
  1539. //
  1540. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1541. //
  1542. // Optimization: could be partially computed once for all (cached) ?
  1543. //
  1544. if ($bIsOnQueriedClass)
  1545. {
  1546. // Get all Ext keys for the queried class (??)
  1547. foreach(MetaModel::GetKeysList($sClass) as $sKeyAttCode)
  1548. {
  1549. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1550. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1551. }
  1552. }
  1553. // Get all Ext keys used by the filter
  1554. foreach ($this->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  1555. {
  1556. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1557. {
  1558. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1559. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1560. }
  1561. }
  1562. $aFNJoinAlias = array(); // array of (subclass => alias)
  1563. foreach ($aExpectedAtts as $sExpectedAttCode => $oExpression)
  1564. {
  1565. if (!MetaModel::IsValidAttCode($sClass, $sExpectedAttCode)) continue;
  1566. $oAttDef = MetaModel::GetAttributeDef($sClass, $sExpectedAttCode);
  1567. if ($oAttDef->IsBasedOnOQLExpression())
  1568. {
  1569. // To optimize: detect a restriction on child classes in the condition expression
  1570. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  1571. $oExpression = static::GetPolymorphicExpression($sClass, $sExpectedAttCode);
  1572. $aRequiredFields = array();
  1573. $oExpression->GetUnresolvedFields('', $aRequiredFields);
  1574. $aTranslateFields = array();
  1575. foreach($aRequiredFields as $sSubClass => $aFields)
  1576. {
  1577. foreach($aFields as $sAttCode => $oField)
  1578. {
  1579. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1580. if ($oAttDef->IsExternalKey())
  1581. {
  1582. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1583. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  1584. }
  1585. elseif ($oAttDef->IsExternalField())
  1586. {
  1587. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1588. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sKeyAttCode);
  1589. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  1590. }
  1591. else
  1592. {
  1593. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1594. }
  1595. if (MetaModel::IsParentClass($sClassOfAttribute, $sClass))
  1596. {
  1597. // The attribute is part of the standard query
  1598. //
  1599. $sAliasForAttribute = $sClassAlias;
  1600. }
  1601. else
  1602. {
  1603. // The attribute will be available from an additional outer join
  1604. // For each subclass (table) one single join is enough
  1605. //
  1606. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  1607. {
  1608. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  1609. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  1610. }
  1611. else
  1612. {
  1613. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  1614. }
  1615. }
  1616. $aTranslateFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  1617. }
  1618. }
  1619. $oExpression = $oExpression->Translate($aTranslateFields, false);
  1620. $aTranslateNow = array();
  1621. $aTranslateNow[$sClassAlias][$sExpectedAttCode] = $oExpression;
  1622. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1623. }
  1624. }
  1625. // Add the ext fields used in the select (eventually adds an external key)
  1626. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1627. {
  1628. if ($oAttDef->IsExternalField())
  1629. {
  1630. if (array_key_exists($sAttCode, $aExpectedAtts))
  1631. {
  1632. // Add the external attribute
  1633. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1634. $sKeyTableClass = MetaModel::GetAttributeOrigin($sClass, $sKeyAttCode);
  1635. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1636. }
  1637. }
  1638. }
  1639. // First query built upon on the leaf (ie current) class
  1640. //
  1641. self::DbgTrace("Main (=leaf) class, call MakeSQLObjectQuerySingleTable()");
  1642. if (MetaModel::HasTable($sClass))
  1643. {
  1644. $oSelectBase = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sClass, $aExtKeys, $aValues);
  1645. }
  1646. else
  1647. {
  1648. $oSelectBase = null;
  1649. // As the join will not filter on the expected classes, we have to specify it explicitely
  1650. $sExpectedClasses = implode("', '", MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1651. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1652. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  1653. }
  1654. // Then we join the queries of the eventual parent classes (compound model)
  1655. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1656. {
  1657. if (!MetaModel::HasTable($sParentClass)) continue;
  1658. self::DbgTrace("Parent class: $sParentClass... let's call MakeSQLObjectQuerySingleTable()");
  1659. $oSelectParentTable = $this->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sParentClass, $aExtKeys, $aValues);
  1660. if (is_null($oSelectBase))
  1661. {
  1662. $oSelectBase = $oSelectParentTable;
  1663. }
  1664. else
  1665. {
  1666. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, MetaModel::DBGetKey($sParentClass));
  1667. }
  1668. }
  1669. // Filter on objects referencing me
  1670. //
  1671. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  1672. {
  1673. foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
  1674. {
  1675. foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
  1676. {
  1677. foreach ($aFilters as $oForeignFilter)
  1678. {
  1679. $oForeignKeyAttDef = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  1680. self::DbgTrace("Referenced by foreign key: $sForeignExtKeyAttCode... let's call MakeSQLObjectQuery()");
  1681. //self::DbgTrace($oForeignFilter);
  1682. //self::DbgTrace($oForeignFilter->ToOQL());
  1683. //self::DbgTrace($oSelectForeign);
  1684. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1685. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1686. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignExtKeyAttCode, $sForeignClassAlias));
  1687. if ($oForeignKeyAttDef instanceof AttributeObjectKey)
  1688. {
  1689. $sClassAttCode = $oForeignKeyAttDef->Get('class_attcode');
  1690. // Add the condition: `$sForeignClassAlias`.$sClassAttCode IN (subclasses of $sClass')
  1691. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1692. $oClassExpr = new FieldExpression($sClassAttCode, $sForeignClassAlias);
  1693. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1694. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1695. }
  1696. $oSelectForeign = $oForeignFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1697. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1698. $sForeignKeyTable = $oJoinExpr->GetParent();
  1699. $sForeignKeyColumn = $oJoinExpr->GetName();
  1700. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  1701. {
  1702. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1703. }
  1704. else
  1705. {
  1706. // Hierarchical key
  1707. $KeyLeft = $oForeignKeyAttDef->GetSQLLeft();
  1708. $KeyRight = $oForeignKeyAttDef->GetSQLRight();
  1709. $oSelectBase->AddInnerJoinTree($oSelectForeign, $KeyLeft, $KeyRight, $KeyLeft, $KeyRight, $sForeignKeyTable, $iOperatorCode, true);
  1710. }
  1711. }
  1712. }
  1713. }
  1714. }
  1715. // Additional JOINS for Friendly names
  1716. //
  1717. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  1718. {
  1719. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  1720. $oSelectFN = $oSubClassFilter->MakeSQLObjectQuerySingleTable($oBuild, $aAttToLoad, $sSubClass, $aExtKeys, array());
  1721. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, MetaModel::DBGetKey($sSubClass));
  1722. }
  1723. // That's all... cross fingers and we'll get some working query
  1724. //MyHelpers::var_dump_html($oSelectBase, true);
  1725. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1726. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1727. return $oSelectBase;
  1728. }
  1729. protected function MakeSQLObjectQuerySingleTable(&$oBuild, $aAttToLoad, $sTableClass, $aExtKeys, $aValues)
  1730. {
  1731. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1732. // Prepare the query for a single table (compound objects)
  1733. // Ignores the items (attributes/filters) that are not on the target table
  1734. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1735. //
  1736. // Returns an SQLQuery
  1737. //
  1738. $sTargetClass = $this->GetFirstJoinedClass();
  1739. $sTargetAlias = $this->GetFirstJoinedClassAlias();
  1740. $sTable = MetaModel::DBGetTable($sTableClass);
  1741. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  1742. $aTranslation = array();
  1743. $aExpectedAtts = array();
  1744. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  1745. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  1746. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$this->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1747. // 1 - SELECT and UPDATE
  1748. //
  1749. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1750. //
  1751. $aUpdateValues = array();
  1752. // 1/a - Get the key and friendly name
  1753. //
  1754. // We need one pkey to be the key, let's take the first one available
  1755. $oSelectedIdField = null;
  1756. $oIdField = new FieldExpressionResolved(MetaModel::DBGetKey($sTableClass), $sTableAlias);
  1757. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  1758. if ($bIsOnQueriedClass)
  1759. {
  1760. // Add this field to the list of queried fields (required for the COUNT to work fine)
  1761. $oSelectedIdField = $oIdField;
  1762. }
  1763. // 1/b - Get the other attributes
  1764. //
  1765. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1766. {
  1767. // Skip this attribute if not defined in this table
  1768. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1769. // Skip this attribute if not made of SQL columns
  1770. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1771. // Update...
  1772. //
  1773. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1774. {
  1775. assert ($oAttDef->IsBasedOnDBColumns());
  1776. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1777. {
  1778. $aUpdateValues[$sColumn] = $sValue;
  1779. }
  1780. }
  1781. }
  1782. // 2 - The SQL query, for this table only
  1783. //
  1784. $oSelectBase = new SQLObjectQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  1785. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  1786. //
  1787. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1788. {
  1789. // Skip this attribute if not defined in this table
  1790. if (MetaModel::GetAttributeOrigin($sTargetClass, $sAttCode) != $sTableClass) continue;
  1791. // Select...
  1792. //
  1793. if ($oAttDef->IsExternalField())
  1794. {
  1795. // skip, this will be handled in the joined tables (done hereabove)
  1796. }
  1797. else
  1798. {
  1799. // standard field, or external key
  1800. // add it to the output
  1801. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1802. {
  1803. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  1804. {
  1805. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1806. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  1807. {
  1808. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  1809. }
  1810. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  1811. }
  1812. }
  1813. }
  1814. }
  1815. // 4 - The external keys -> joins...
  1816. //
  1817. $aAllPointingTo = $this->GetCriteria_PointingTo();
  1818. if (array_key_exists($sTableClass, $aExtKeys))
  1819. {
  1820. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1821. {
  1822. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1823. $aPointingTo = $this->GetCriteria_PointingTo($sKeyAttCode);
  1824. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  1825. {
  1826. // The join was not explicitely defined in the filter,
  1827. // we need to do it now
  1828. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1829. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1830. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1831. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  1832. }
  1833. }
  1834. }
  1835. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  1836. {
  1837. foreach($aPointingTo as $iOperatorCode => $aFilter)
  1838. {
  1839. foreach($aFilter as $oExtFilter)
  1840. {
  1841. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  1842. // The aliases should not conflict because normalization occured while building the filter
  1843. $oKeyAttDef = MetaModel::GetAttributeDef($sTableClass, $sKeyAttCode);
  1844. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1845. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1846. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1847. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  1848. {
  1849. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  1850. {
  1851. // Specify expected attributes for the target class query
  1852. // ... and use the current alias !
  1853. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  1854. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  1855. {
  1856. $oExtAttDef = $oAtt->GetExtAttDef();
  1857. if ($oExtAttDef->IsBasedOnOQLExpression())
  1858. {
  1859. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression($oExtAttDef->GetCode(), $sKeyClassAlias);
  1860. }
  1861. else
  1862. {
  1863. $sExtAttCode = $oAtt->GetExtAttCode();
  1864. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1865. $oRemoteAttDef = MetaModel::GetAttributeDef($sKeyClass, $sExtAttCode);
  1866. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColId => $sRemoteAttExpr)
  1867. {
  1868. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  1869. }
  1870. }
  1871. }
  1872. if ($oKeyAttDef instanceof AttributeObjectKey)
  1873. {
  1874. // Add the condition: `$sTargetAlias`.$sClassAttCode IN (subclasses of $sKeyClass')
  1875. $sClassAttCode = $oKeyAttDef->Get('class_attcode');
  1876. $oClassAttDef = MetaModel::GetAttributeDef($sTargetClass, $sClassAttCode);
  1877. foreach ($oClassAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1878. {
  1879. $aTranslateNow[$sTargetAlias][$sClassAttCode.$sColId] = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  1880. }
  1881. $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sKeyClass, ENUM_CHILD_CLASSES_ALL));
  1882. $oClassExpr = new FieldExpression($sClassAttCode, $sTargetAlias);
  1883. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  1884. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  1885. }
  1886. // Translate prior to recursing
  1887. //
  1888. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  1889. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeSQLObjectQuery()");
  1890. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  1891. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1892. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1893. $sExternalKeyTable = $oJoinExpr->GetParent();
  1894. $sExternalKeyField = $oJoinExpr->GetName();
  1895. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  1896. $sLocalKeyField = current($aCols); // get the first column for an external key
  1897. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1898. if ($oKeyAttDef->IsNullAllowed())
  1899. {
  1900. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1901. }
  1902. else
  1903. {
  1904. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  1905. }
  1906. }
  1907. }
  1908. elseif(MetaModel::GetAttributeOrigin($sKeyClass, $sKeyAttCode) == $sTableClass)
  1909. {
  1910. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  1911. $oSelectExtKey = $oExtFilter->MakeSQLObjectQuery($oBuild, $aAttToLoad);
  1912. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  1913. $sExternalKeyTable = $oJoinExpr->GetParent();
  1914. $sExternalKeyField = $oJoinExpr->GetName();
  1915. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  1916. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  1917. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  1918. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  1919. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  1920. }
  1921. }
  1922. }
  1923. }
  1924. // Translate the selected columns
  1925. //
  1926. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  1927. // Filter out archived records
  1928. //
  1929. if (MetaModel::IsArchivable($sTableClass))
  1930. {
  1931. if (!$oBuild->GetRootFilter()->GetArchiveMode())
  1932. {
  1933. $bIsOnJoinedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetJoinedClasses());
  1934. if ($bIsOnJoinedClass)
  1935. {
  1936. if (MetaModel::IsParentClass($sTableClass, $sTargetClass))
  1937. {
  1938. $oNotArchived = new BinaryExpression(new FieldExpressionResolved('archive_flag', $sTableAlias), '=', new ScalarExpression(0));
  1939. $oBuild->AddFilteredTable($sTableAlias, $oNotArchived);
  1940. }
  1941. }
  1942. }
  1943. }
  1944. return $oSelectBase;
  1945. }
  1946. /**
  1947. * Get the expression for the class and its subclasses (if finalclass = 'subclass' ...)
  1948. * Simplifies the final expression by grouping classes having the same expression
  1949. */
  1950. static protected function GetPolymorphicExpression($sClass, $sAttCode)
  1951. {
  1952. // 1st step - get all of the required expressions (instantiable classes)
  1953. // and group them using their OQL representation
  1954. //
  1955. $aExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes)
  1956. foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1957. {
  1958. if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) continue;
  1959. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1960. $oSubClassExp = $oAttDef->GetOQLExpression($sSubClass);
  1961. // 3rd step - position the attributes in the hierarchy of classes
  1962. //
  1963. $oSubClassExp->Browse(function($oNode) use ($sSubClass) {
  1964. if ($oNode instanceof FieldExpression)
  1965. {
  1966. $sAttCode = $oNode->GetName();
  1967. $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
  1968. if ($oAttDef->IsExternalField())
  1969. {
  1970. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1971. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sKeyAttCode);
  1972. }
  1973. else
  1974. {
  1975. $sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
  1976. }
  1977. $sParent = MetaModel::GetAttributeOrigin($sClassOfAttribute, $oNode->GetName());
  1978. $oNode->SetParent($sParent);
  1979. }
  1980. });
  1981. $sSignature = $oSubClassExp->Render();
  1982. if (!array_key_exists($sSignature, $aExpressions))
  1983. {
  1984. $aExpressions[$sSignature] = array(
  1985. 'expression' => $oSubClassExp,
  1986. 'classes' => array(),
  1987. );
  1988. }
  1989. $aExpressions[$sSignature]['classes'][] = $sSubClass;
  1990. }
  1991. // 2nd step - build the final name expression depending on the finalclass
  1992. //
  1993. if (count($aExpressions) == 1)
  1994. {
  1995. $aExpData = reset($aExpressions);
  1996. $oExpression = $aExpData['expression'];
  1997. }
  1998. else
  1999. {
  2000. $oExpression = null;
  2001. foreach ($aExpressions as $sSignature => $aExpData)
  2002. {
  2003. $oClassListExpr = ListExpression::FromScalars($aExpData['classes']);
  2004. $oClassExpr = new FieldExpression('finalclass', $sClass);
  2005. $oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  2006. if (is_null($oExpression))
  2007. {
  2008. $oExpression = $aExpData['expression'];
  2009. }
  2010. else
  2011. {
  2012. $oExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oExpression));
  2013. }
  2014. }
  2015. }
  2016. return $oExpression;
  2017. }
  2018. }