dbobjectsearch.class.php 76 KB

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