dbobjectsearch.class.php 77 KB

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