dbobjectsearch.class.php 60 KB

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