dbobjectsearch.class.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. <?php
  2. // Copyright (C) 2010-2012 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-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. define('TREE_OPERATOR_EQUALS', 0);
  25. define('TREE_OPERATOR_BELOW', 1);
  26. define('TREE_OPERATOR_BELOW_STRICT', 2);
  27. define('TREE_OPERATOR_NOT_BELOW', 3);
  28. define('TREE_OPERATOR_NOT_BELOW_STRICT', 4);
  29. define('TREE_OPERATOR_ABOVE', 5);
  30. define('TREE_OPERATOR_ABOVE_STRICT', 6);
  31. define('TREE_OPERATOR_NOT_ABOVE', 7);
  32. define('TREE_OPERATOR_NOT_ABOVE_STRICT', 8);
  33. class DBObjectSearch
  34. {
  35. private $m_aClasses; // queried classes (alias => class name), the first item is the class corresponding to this filter (the rest is coming from subfilters)
  36. private $m_aSelectedClasses; // selected for the output (alias => class name)
  37. private $m_oSearchCondition;
  38. private $m_aParams;
  39. private $m_aFullText;
  40. private $m_aPointingTo;
  41. private $m_aReferencedBy;
  42. private $m_aRelatedTo;
  43. private $m_bDataFiltered;
  44. // By default, some information may be hidden to the current user
  45. // But it may happen that we need to disable that feature
  46. private $m_bAllowAllData = false;
  47. public function __construct($sClass, $sClassAlias = null)
  48. {
  49. if (is_null($sClassAlias)) $sClassAlias = $sClass;
  50. assert('is_string($sClass)');
  51. assert('MetaModel::IsValidClass($sClass)'); // #@# could do better than an assert, or at least give the caller's reference
  52. // => idee d'un assert avec call stack (autre utilisation = echec sur query SQL)
  53. $this->m_aSelectedClasses = array($sClassAlias => $sClass);
  54. $this->m_aClasses = array($sClassAlias => $sClass);
  55. $this->m_oSearchCondition = new TrueExpression;
  56. $this->m_aParams = array();
  57. $this->m_aFullText = array();
  58. $this->m_aPointingTo = array();
  59. $this->m_aReferencedBy = array();
  60. $this->m_aRelatedTo = array();
  61. $this->m_bDataFiltered = false;
  62. $this->m_aParentConditions = array();
  63. $this->m_aModifierProperties = array();
  64. }
  65. /**
  66. * Perform a deep clone (as opposed to "clone" which does copy a reference to the underlying objects)
  67. **/
  68. public function DeepClone()
  69. {
  70. return unserialize(serialize($this)); // Beware this serializes/unserializes the search and its parameters as well
  71. }
  72. public function AllowAllData() {$this->m_bAllowAllData = true;}
  73. public function IsAllDataAllowed() {return $this->m_bAllowAllData;}
  74. public function IsDataFiltered() {return $this->m_bDataFiltered; }
  75. public function SetDataFiltered() {$this->m_bDataFiltered = true;}
  76. public function GetClassName($sAlias)
  77. {
  78. if (array_key_exists($sAlias, $this->m_aClasses))
  79. {
  80. return $this->m_aClasses[$sAlias];
  81. }
  82. else
  83. {
  84. throw new CoreException("Invalid class alias '$sAlias'");
  85. }
  86. }
  87. public function GetJoinedClasses() {return $this->m_aClasses;}
  88. public function GetClass()
  89. {
  90. return reset($this->m_aSelectedClasses);
  91. }
  92. public function GetClassAlias()
  93. {
  94. reset($this->m_aSelectedClasses);
  95. return key($this->m_aSelectedClasses);
  96. }
  97. public function GetFirstJoinedClass()
  98. {
  99. return reset($this->m_aClasses);
  100. }
  101. public function GetFirstJoinedClassAlias()
  102. {
  103. reset($this->m_aClasses);
  104. return key($this->m_aClasses);
  105. }
  106. /**
  107. * Change the class (only subclasses are supported as of now, because the conditions must fit the new class)
  108. * Defaults to the first selected class (most of the time it is also the first joined class
  109. */
  110. public function ChangeClass($sNewClass, $sAlias = null)
  111. {
  112. if (is_null($sAlias))
  113. {
  114. $sAlias = $this->GetClassAlias();
  115. }
  116. else
  117. {
  118. if (!array_key_exists($sAlias, $this->m_aClasses))
  119. {
  120. // discard silently - necessary when recursing on the related nodes (see code below)
  121. return;
  122. }
  123. }
  124. $sCurrClass = $this->GetClassName($sAlias);
  125. if (!MetaModel::IsParentClass($sCurrClass, $sNewClass))
  126. {
  127. throw new Exception("Could not change the search class from '$sCurrClass' to '$sNewClass'. Only child classes are permitted.");
  128. }
  129. // Change for this node
  130. //
  131. $this->m_aSelectedClasses[$sAlias] = $sNewClass;
  132. $this->m_aClasses[$sAlias] = $sNewClass;
  133. // Change for all the related node (yes, this was necessary with some queries - strange effects otherwise)
  134. //
  135. foreach($this->m_aRelatedTo as $aRelatedTo)
  136. {
  137. $aRelatedTo['flt']->ChangeClass($sNewClass, $sAlias);
  138. }
  139. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  140. {
  141. foreach($aPointingTo as $iOperatorCode => $aFilter)
  142. {
  143. foreach($aFilter as $oExtFilter)
  144. {
  145. $oExtFilter->ChangeClass($sNewClass, $sAlias);
  146. }
  147. }
  148. }
  149. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  150. {
  151. foreach($aReferences as $sForeignExtKeyAttCode => $oForeignFilter)
  152. {
  153. $oForeignFilter->ChangeClass($sNewClass, $sAlias);
  154. }
  155. }
  156. }
  157. public function SetSelectedClasses($aNewSet)
  158. {
  159. $this->m_aSelectedClasses = array();
  160. foreach ($aNewSet as $sAlias => $sClass)
  161. {
  162. if (!array_key_exists($sAlias, $this->m_aClasses))
  163. {
  164. throw new CoreException('Unexpected class alias', array('alias'=>$sAlias, 'expected'=>$this->m_aClasses));
  165. }
  166. $this->m_aSelectedClasses[$sAlias] = $sClass;
  167. }
  168. }
  169. public function GetSelectedClasses()
  170. {
  171. return $this->m_aSelectedClasses;
  172. }
  173. public function SetModifierProperty($sPluginClass, $sProperty, $value)
  174. {
  175. $this->m_aModifierProperties[$sPluginClass][$sProperty] = $value;
  176. }
  177. public function GetModifierProperties($sPluginClass)
  178. {
  179. if (array_key_exists($sPluginClass, $this->m_aModifierProperties))
  180. {
  181. return $this->m_aModifierProperties[$sPluginClass];
  182. }
  183. else
  184. {
  185. return array();
  186. }
  187. }
  188. public function IsAny()
  189. {
  190. // #@# todo - if (!$this->m_oSearchCondition->IsTrue()) return false;
  191. if (count($this->m_aFullText) > 0) return false;
  192. if (count($this->m_aPointingTo) > 0) return false;
  193. if (count($this->m_aReferencedBy) > 0) return false;
  194. if (count($this->m_aRelatedTo) > 0) return false;
  195. if (count($this->m_aParentConditions) > 0) return false;
  196. return true;
  197. }
  198. public function Describe()
  199. {
  200. // To replace __Describe
  201. }
  202. public function DescribeConditionPointTo($sExtKeyAttCode, $aPointingTo)
  203. {
  204. if (empty($aPointingTo)) return "";
  205. foreach($aPointingTo as $iOperatorCode => $oFilter)
  206. {
  207. if ($oFilter->IsAny()) break;
  208. $oAtt = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
  209. $sOperator = '';
  210. switch($iOperatorCode)
  211. {
  212. case TREE_OPERATOR_EQUALS:
  213. $sOperator = 'having';
  214. break;
  215. case TREE_OPERATOR_BELOW:
  216. $sOperator = 'below';
  217. break;
  218. case TREE_OPERATOR_BELOW_STRICT:
  219. $sOperator = 'strictly below';
  220. break;
  221. case TREE_OPERATOR_NOT_BELOW:
  222. $sOperator = 'not below';
  223. break;
  224. case TREE_OPERATOR_NOT_BELOW_STRICT:
  225. $sOperator = 'strictly not below';
  226. break;
  227. case TREE_OPERATOR_ABOVE:
  228. $sOperator = 'above';
  229. break;
  230. case TREE_OPERATOR_ABOVE_STRICT:
  231. $sOperator = 'strictly above';
  232. break;
  233. case TREE_OPERATOR_NOT_ABOVE:
  234. $sOperator = 'not above';
  235. break;
  236. case TREE_OPERATOR_NOT_ABOVE_STRICT:
  237. $sOperator = 'strictly not above';
  238. break;
  239. }
  240. $aDescription[] = $oAtt->GetLabel()."$sOperator ({$oFilter->DescribeConditions()})";
  241. }
  242. return implode(' and ', $aDescription);
  243. }
  244. public function DescribeConditionRefBy($sForeignClass, $sForeignExtKeyAttCode)
  245. {
  246. if (!isset($this->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode])) return "";
  247. $oFilter = $this->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode];
  248. if ($oFilter->IsAny()) return "";
  249. $oAtt = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  250. return "being ".$oAtt->GetLabel()." for ".$sForeignClass."s in ({$oFilter->DescribeConditions()})";
  251. }
  252. public function DescribeConditionRelTo($aRelInfo)
  253. {
  254. $oFilter = $aRelInfo['flt'];
  255. $sRelCode = $aRelInfo['relcode'];
  256. $iMaxDepth = $aRelInfo['maxdepth'];
  257. return "related ($sRelCode... peut mieux faire !, $iMaxDepth dig depth) to a {$oFilter->GetClass()} ({$oFilter->DescribeConditions()})";
  258. }
  259. public function DescribeConditions()
  260. {
  261. $aConditions = array();
  262. $aCondFT = array();
  263. foreach($this->m_aFullText as $sFullText)
  264. {
  265. $aCondFT[] = " contain word(s) '$sFullText'";
  266. }
  267. if (count($aCondFT) > 0)
  268. {
  269. $aConditions[] = "which ".implode(" and ", $aCondFT);
  270. }
  271. // #@# todo - review textual description of the JOIN and search condition (is that still feasible?)
  272. $aConditions[] = $this->RenderCondition();
  273. $aCondPoint = array();
  274. foreach($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo)
  275. {
  276. $aCondPoint[] = $this->DescribeConditionPointTo($sExtKeyAttCode, $aPointingTo);
  277. }
  278. if (count($aCondPoint) > 0)
  279. {
  280. $aConditions[] = implode(" and ", $aCondPoint);
  281. }
  282. $aCondReferred= array();
  283. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  284. {
  285. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  286. {
  287. if ($oForeignFilter->IsAny()) continue;
  288. $aCondReferred[] = $this->DescribeConditionRefBy($sForeignClass, $sForeignExtKeyAttCode);
  289. }
  290. }
  291. foreach ($this->m_aRelatedTo as $aRelInfo)
  292. {
  293. $aCondReferred[] = $this->DescribeConditionRelTo($aRelInfo);
  294. }
  295. if (count($aCondReferred) > 0)
  296. {
  297. $aConditions[] = implode(" and ", $aCondReferred);
  298. }
  299. foreach ($this->m_aParentConditions as $aRelInfo)
  300. {
  301. $aCondReferred[] = $this->DescribeConditionParent($aRelInfo);
  302. }
  303. return implode(" and ", $aConditions);
  304. }
  305. public function __DescribeHTML()
  306. {
  307. try
  308. {
  309. $sConditionDesc = $this->DescribeConditions();
  310. }
  311. catch (MissingQueryArgument $e)
  312. {
  313. $sConditionDesc = '?missing query argument?';
  314. }
  315. if (!empty($sConditionDesc))
  316. {
  317. return "Objects of class '".$this->GetClass()."', $sConditionDesc";
  318. }
  319. return "Any object of class '".$this->GetClass()."'";
  320. }
  321. protected function TransferConditionExpression($oFilter, $aTranslation)
  322. {
  323. // Prevent collisions in the parameter names by renaming them if needed
  324. foreach($this->m_aParams as $sParam => $value)
  325. {
  326. if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam]))
  327. {
  328. // Generate a new and unique name for the collinding parameter
  329. $index = 1;
  330. while(array_key_exists($sParam.$index, $oFilter->m_aParams))
  331. {
  332. $index++;
  333. }
  334. $secondValue = $oFilter->m_aParams[$sParam];
  335. $oFilter->RenameParam($sParam, $sParam.$index);
  336. unset($oFilter->m_aParams[$sParam]);
  337. $oFilter->m_aParams[$sParam.$index] = $secondValue;
  338. }
  339. }
  340. //echo "<p>TransferConditionExpression:<br/>";
  341. //echo "Adding Conditions:<br/><pre>oFilter:\n".print_r($oFilter, true)."\naTranslation:\n".print_r($aTranslation, true)."</pre>\n";
  342. //echo "</p>";
  343. $oTranslated = $oFilter->GetCriteria()->Translate($aTranslation, false, false /* leave unresolved fields */);
  344. //echo "Adding Conditions (translated):<br/><pre>".print_r($oTranslated, true)."</pre>\n";
  345. $this->AddConditionExpression($oTranslated);
  346. $this->m_aParams = array_merge($this->m_aParams, $oFilter->m_aParams);
  347. }
  348. protected function RenameParam($sOldName, $sNewName)
  349. {
  350. $this->m_oSearchCondition->RenameParam($sOldName, $sNewName);
  351. foreach($this->m_aRelatedTo as $aRelatedTo)
  352. {
  353. $aRelatedTo['flt']->RenameParam($sOldName, $sNewName);
  354. }
  355. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  356. {
  357. foreach($aPointingTo as $iOperatorCode => $aFilter)
  358. {
  359. foreach($aFilter as $oExtFilter)
  360. {
  361. $oExtFilter->RenameParam($sOldName, $sNewName);
  362. }
  363. }
  364. }
  365. foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
  366. {
  367. foreach($aReferences as $sForeignExtKeyAttCode => $oForeignFilter)
  368. {
  369. $oForeignFilter->RenameParam($sOldName, $sNewName);
  370. }
  371. }
  372. foreach($this->m_aParentConditions as $aParent)
  373. {
  374. $aParent['expression']->RenameParam($sOldName, $sNewName);
  375. }
  376. }
  377. public function ResetCondition()
  378. {
  379. $this->m_oSearchCondition = new TrueExpression();
  380. $this->m_aParentConditions = array();
  381. // ? is that usefull/enough, do I need to rebuild the list after the subqueries ?
  382. }
  383. public function MergeConditionExpression($oExpression)
  384. {
  385. $this->m_oSearchCondition = $this->m_oSearchCondition->LogOr($oExpression);
  386. }
  387. public function AddConditionExpression($oExpression)
  388. {
  389. $this->m_oSearchCondition = $this->m_oSearchCondition->LogAnd($oExpression);
  390. }
  391. public function AddNameCondition($sName)
  392. {
  393. $oValueExpr = new ScalarExpression($sName);
  394. $oNameExpr = new FieldExpression('friendlyname', $this->GetClassAlias());
  395. $oNewCondition = new BinaryExpression($oNameExpr, '=', $oValueExpr);
  396. $this->AddConditionExpression($oNewCondition);
  397. }
  398. public function AddCondition($sFilterCode, $value, $sOpCode = null)
  399. {
  400. MyHelpers::CheckKeyInArray('filter code', $sFilterCode, MetaModel::GetClassFilterDefs($this->GetClass()));
  401. $oFilterDef = MetaModel::GetClassFilterDef($this->GetClass(), $sFilterCode);
  402. $oField = new FieldExpression($sFilterCode, $this->GetClassAlias());
  403. if (empty($sOpCode))
  404. {
  405. if ($sFilterCode == 'id')
  406. {
  407. $sOpCode = '=';
  408. }
  409. else
  410. {
  411. $oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sFilterCode);
  412. $oNewCondition = $oAttDef->GetSmartConditionExpression($value, $oField, $this->m_aParams);
  413. $this->AddConditionExpression($oNewCondition);
  414. return;
  415. }
  416. }
  417. MyHelpers::CheckKeyInArray('operator', $sOpCode, $oFilterDef->GetOperators());
  418. // Preserve backward compatibility - quick n'dirty way to change that API semantic
  419. //
  420. switch($sOpCode)
  421. {
  422. case 'SameDay':
  423. case 'SameMonth':
  424. case 'SameYear':
  425. case 'Today':
  426. case '>|':
  427. case '<|':
  428. case '=|':
  429. throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', array('operator' => $sOpCode));
  430. break;
  431. case "IN":
  432. if (!is_array($value)) $value = array($value);
  433. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  434. $sOQLCondition = $oField->Render()." IN $sListExpr";
  435. break;
  436. case "NOTIN":
  437. if (!is_array($value)) $value = array($value);
  438. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  439. $sOQLCondition = $oField->Render()." NOT IN $sListExpr";
  440. break;
  441. case 'Contains':
  442. $this->m_aParams[$sFilterCode] = "%$value%";
  443. $sOperator = 'LIKE';
  444. break;
  445. case 'Begins with':
  446. $this->m_aParams[$sFilterCode] = "$value%";
  447. $sOperator = 'LIKE';
  448. break;
  449. case 'Finishes with':
  450. $this->m_aParams[$sFilterCode] = "%$value";
  451. $sOperator = 'LIKE';
  452. break;
  453. default:
  454. $this->m_aParams[$sFilterCode] = $value;
  455. $sOperator = $sOpCode;
  456. }
  457. switch($sOpCode)
  458. {
  459. case "IN":
  460. case "NOTIN":
  461. $oNewCondition = Expression::FromOQL($sOQLCondition);
  462. break;
  463. case 'Contains':
  464. case 'Begins with':
  465. case 'Finishes with':
  466. default:
  467. $oRightExpr = new VariableExpression($sFilterCode);
  468. $oNewCondition = new BinaryExpression($oField, $sOperator, $oRightExpr);
  469. }
  470. $this->AddConditionExpression($oNewCondition);
  471. }
  472. /**
  473. * Specify a condition on external keys or link sets
  474. * @param sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
  475. * Example: infra_list->ci_id->location_id->country
  476. * @param value The value to match (can be an array => IN(val1, val2...)
  477. * @return void
  478. */
  479. public function AddConditionAdvanced($sAttSpec, $value)
  480. {
  481. $sClass = $this->GetClass();
  482. $iPos = strpos($sAttSpec, '->');
  483. if ($iPos !== false)
  484. {
  485. $sAttCode = substr($sAttSpec, 0, $iPos);
  486. $sSubSpec = substr($sAttSpec, $iPos + 2);
  487. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  488. {
  489. throw new Exception("Invalid attribute code '$sClass/$sAttCode' in condition specification '$sAttSpec'");
  490. }
  491. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  492. if ($oAttDef->IsLinkSet())
  493. {
  494. $sTargetClass = $oAttDef->GetLinkedClass();
  495. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  496. $oNewFilter = new DBObjectSearch($sTargetClass);
  497. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  498. $this->AddCondition_ReferencedBy($oNewFilter, $sExtKeyToMe);
  499. }
  500. elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  501. {
  502. $sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE);
  503. $oNewFilter = new DBObjectSearch($sTargetClass);
  504. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  505. $this->AddCondition_PointingTo($oNewFilter, $sAttCode);
  506. }
  507. else
  508. {
  509. throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key");
  510. }
  511. }
  512. else
  513. {
  514. // $sAttSpec is an attribute code
  515. //
  516. if (is_array($value))
  517. {
  518. $oField = new FieldExpression($sAttSpec, $this->GetClass());
  519. $oListExpr = ListExpression::FromScalars($value);
  520. $oInValues = new BinaryExpression($oField, 'IN', $oListExpr);
  521. $this->AddConditionExpression($oInValues);
  522. }
  523. else
  524. {
  525. $this->AddCondition($sAttSpec, $value);
  526. }
  527. }
  528. }
  529. public function AddCondition_FullText($sFullText)
  530. {
  531. $this->m_aFullText[] = $sFullText;
  532. }
  533. public function AddCondition_Parent($sAttCode, $iOperatorCode, $oExpression)
  534. {
  535. $oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sAttCode);
  536. if (!$oAttDef instanceof AttributeHierarchicalKey)
  537. {
  538. throw new Exception("AddCondition_Parent can only be used on hierarchical keys. '$sAttCode' is not a hierarchical key.");
  539. }
  540. $this->m_aParentConditions[] = array(
  541. 'attCode' => $sAttCode,
  542. 'operator' => $iOperatorCode,
  543. 'expression' => $oExpression,
  544. );
  545. }
  546. protected function AddToNameSpace(&$aClassAliases, &$aAliasTranslation, $bTranslateMainAlias = true)
  547. {
  548. if ($bTranslateMainAlias)
  549. {
  550. $sOrigAlias = $this->GetFirstJoinedClassAlias();
  551. if (array_key_exists($sOrigAlias, $aClassAliases))
  552. {
  553. $sNewAlias = MetaModel::GenerateUniqueAlias($aClassAliases, $sOrigAlias, $this->GetFirstJoinedClass());
  554. if (isset($this->m_aSelectedClasses[$sOrigAlias]))
  555. {
  556. $this->m_aSelectedClasses[$sNewAlias] = $this->GetFirstJoinedClass();
  557. unset($this->m_aSelectedClasses[$sOrigAlias]);
  558. }
  559. // TEMPORARY ALGORITHM (m_aClasses is not correctly updated, it is not possible to add a subtree onto a subnode)
  560. // Replace the element at the same position (unset + set is not enough because the hash array is ordered)
  561. $aPrevList = $this->m_aClasses;
  562. $this->m_aClasses = array();
  563. foreach ($aPrevList as $sSomeAlias => $sSomeClass)
  564. {
  565. if ($sSomeAlias == $sOrigAlias)
  566. {
  567. $this->m_aClasses[$sNewAlias] = $sSomeClass; // note: GetFirstJoinedClass now returns '' !!!
  568. }
  569. else
  570. {
  571. $this->m_aClasses[$sSomeAlias] = $sSomeClass;
  572. }
  573. }
  574. // Translate the condition expression with the new alias
  575. $aAliasTranslation[$sOrigAlias]['*'] = $sNewAlias;
  576. }
  577. // add the alias into the filter aliases list
  578. $aClassAliases[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
  579. }
  580. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  581. {
  582. foreach($aPointingTo as $iOperatorCode => $aFilter)
  583. {
  584. foreach($aFilter as $oFilter)
  585. {
  586. $oFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  587. }
  588. }
  589. }
  590. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  591. {
  592. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  593. {
  594. $oForeignFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  595. }
  596. }
  597. }
  598. // Browse the tree nodes recursively
  599. //
  600. protected function GetNode($sAlias)
  601. {
  602. if ($this->GetFirstJoinedClassAlias() == $sAlias)
  603. {
  604. return $this;
  605. }
  606. else
  607. {
  608. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  609. {
  610. foreach($aPointingTo as $iOperatorCode => $aFilter)
  611. {
  612. foreach($aFilter as $oFilter)
  613. {
  614. $ret = $oFilter->GetNode($sAlias);
  615. if (is_object($ret))
  616. {
  617. return $ret;
  618. }
  619. }
  620. }
  621. }
  622. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  623. {
  624. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  625. {
  626. $ret = $oForeignFilter->GetNode($sAlias);
  627. if (is_object($ret))
  628. {
  629. return $ret;
  630. }
  631. }
  632. }
  633. }
  634. // Not found
  635. return null;
  636. }
  637. public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS)
  638. {
  639. if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode))
  640. {
  641. throw new CoreWarning("The attribute code '$sExtKeyAttCode' is not an external key of the class '{$this->GetClass()}'");
  642. }
  643. $oAttExtKey = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
  644. if(!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass()))
  645. {
  646. 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()}");
  647. }
  648. if(($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey))
  649. {
  650. throw new CoreException("The specified tree operator $iOperatorCode is not applicable to the key '{$this->GetClass()}::$sExtKeyAttCode', which is not a HierarchicalKey");
  651. }
  652. // Note: though it seems to be a good practice to clone the given source filter
  653. // (as it was done and fixed an issue in MergeWith())
  654. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  655. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  656. // NO: $oFilter = $oFilter->DeepClone();
  657. // See also: Trac #639, and self::AddCondition_ReferencedBy()
  658. $aAliasTranslation = array();
  659. $res = $this->AddCondition_PointingTo_InNameSpace($oFilter, $sExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
  660. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  661. return $res;
  662. }
  663. protected function AddCondition_PointingTo_InNameSpace(DBObjectSearch $oFilter, $sExtKeyAttCode, &$aClassAliases, &$aAliasTranslation, $iOperatorCode)
  664. {
  665. // Find the node on which the new tree must be attached (most of the time it is "this")
  666. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  667. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  668. $oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode][] = $oFilter;
  669. }
  670. public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode)
  671. {
  672. $sForeignClass = $oFilter->GetClass();
  673. if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode))
  674. {
  675. throw new CoreException("The attribute code '$sForeignExtKeyAttCode' is not an external key of the class '{$sForeignClass}'");
  676. }
  677. $oAttExtKey = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  678. if(!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass()))
  679. {
  680. // à refaire en spécifique dans FromOQL
  681. 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()}");
  682. }
  683. // Note: though it seems to be a good practice to clone the given source filter
  684. // (as it was done and fixed an issue in MergeWith())
  685. // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
  686. // root cause: FromOQL relies on the fact that the passed filter can be modified later
  687. // NO: $oFilter = $oFilter->DeepClone();
  688. // See also: Trac #639, and self::AddCondition_PointingTo()
  689. $aAliasTranslation = array();
  690. $res = $this->AddCondition_ReferencedBy_InNameSpace($oFilter, $sForeignExtKeyAttCode, $this->m_aClasses, $aAliasTranslation);
  691. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  692. return $res;
  693. }
  694. protected function AddCondition_ReferencedBy_InNameSpace(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, &$aClassAliases, &$aAliasTranslation)
  695. {
  696. $sForeignClass = $oFilter->GetClass();
  697. // Find the node on which the new tree must be attached (most of the time it is "this")
  698. $oReceivingFilter = $this->GetNode($this->GetClassAlias());
  699. if (array_key_exists($sForeignClass, $this->m_aReferencedBy) && array_key_exists($sForeignExtKeyAttCode, $this->m_aReferencedBy[$sForeignClass]))
  700. {
  701. $oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode]->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation);
  702. }
  703. else
  704. {
  705. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  706. // #@# The condition expression found in that filter should not be used - could be another kind of structure like a join spec tree !!!!
  707. //$oNewFilter = $oFilter->DeepClone();
  708. //$oNewFilter->ResetCondition();
  709. $oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode]= $oFilter;
  710. }
  711. }
  712. public function AddCondition_RelatedTo(DBObjectSearch $oFilter, $sRelCode, $iMaxDepth)
  713. {
  714. MyHelpers::CheckValueInArray('relation code', $sRelCode, MetaModel::EnumRelations());
  715. $this->m_aRelatedTo[] = array('flt'=>$oFilter, 'relcode'=>$sRelCode, 'maxdepth'=>$iMaxDepth);
  716. }
  717. public function MergeWith($oFilter)
  718. {
  719. $oFilter = $oFilter->DeepClone();
  720. $aAliasTranslation = array();
  721. $res = $this->MergeWith_InNamespace($oFilter, $this->m_aClasses, $aAliasTranslation);
  722. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  723. return $res;
  724. }
  725. protected function MergeWith_InNamespace($oFilter, &$aClassAliases, &$aAliasTranslation)
  726. {
  727. if ($this->GetClass() != $oFilter->GetClass())
  728. {
  729. throw new CoreException("Attempting to merge a filter of class '{$this->GetClass()}' with a filter of class '{$oFilter->GetClass()}'");
  730. }
  731. // Translate search condition into our aliasing scheme
  732. $aAliasTranslation[$oFilter->GetClassAlias()]['*'] = $this->GetClassAlias();
  733. $this->m_aFullText = array_merge($this->m_aFullText, $oFilter->m_aFullText);
  734. $this->m_aRelatedTo = array_merge($this->m_aRelatedTo, $oFilter->m_aRelatedTo);
  735. foreach($oFilter->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
  736. {
  737. foreach($aPointingTo as $iOperatorCode => $aFilter)
  738. {
  739. foreach($aFilter as $oExtFilter)
  740. {
  741. $this->AddCondition_PointingTo_InNamespace($oExtFilter, $sExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
  742. }
  743. }
  744. }
  745. foreach($oFilter->m_aReferencedBy as $sForeignClass => $aReferences)
  746. {
  747. foreach($aReferences as $sForeignExtKeyAttCode => $oForeignFilter)
  748. {
  749. $this->AddCondition_ReferencedBy_InNamespace($oForeignFilter, $sForeignExtKeyAttCode, $aClassAliases, $aAliasTranslation);
  750. }
  751. }
  752. }
  753. public function GetCriteria() {return $this->m_oSearchCondition;}
  754. public function GetCriteria_FullText() {return $this->m_aFullText;}
  755. public function GetCriteria_PointingTo($sKeyAttCode = "")
  756. {
  757. if (empty($sKeyAttCode))
  758. {
  759. return $this->m_aPointingTo;
  760. }
  761. if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) return array();
  762. return $this->m_aPointingTo[$sKeyAttCode];
  763. }
  764. public function GetCriteria_ReferencedBy($sRemoteClass = "", $sForeignExtKeyAttCode = "")
  765. {
  766. if (empty($sRemoteClass))
  767. {
  768. return $this->m_aReferencedBy;
  769. }
  770. if (!array_key_exists($sRemoteClass, $this->m_aReferencedBy)) return null;
  771. if (empty($sForeignExtKeyAttCode))
  772. {
  773. return $this->m_aReferencedBy[$sRemoteClass];
  774. }
  775. if (!array_key_exists($sForeignExtKeyAttCode, $this->m_aReferencedBy[$sRemoteClass])) return null;
  776. return $this->m_aReferencedBy[$sRemoteClass][$sForeignExtKeyAttCode];
  777. }
  778. public function GetCriteria_RelatedTo()
  779. {
  780. return $this->m_aRelatedTo;
  781. }
  782. public function SetInternalParams($aParams)
  783. {
  784. return $this->m_aParams = $aParams;
  785. }
  786. public function GetInternalParams()
  787. {
  788. return $this->m_aParams;
  789. }
  790. public function GetQueryParams()
  791. {
  792. $aParams = array();
  793. $this->m_oSearchCondition->Render($aParams, true);
  794. return $aParams;
  795. }
  796. public function ListConstantFields()
  797. {
  798. return $this->m_oSearchCondition->ListConstantFields();
  799. }
  800. public function RenderCondition()
  801. {
  802. return $this->m_oSearchCondition->Render($this->m_aParams, false);
  803. }
  804. /**
  805. * Turn the parameters (:xxx) into scalar values in order to easily
  806. * serialize a search
  807. */
  808. public function ApplyParameters($aArgs)
  809. {
  810. return $this->m_oSearchCondition->ApplyParameters(array_merge($this->m_aParams, $aArgs));
  811. }
  812. public function serialize($bDevelopParams = false, $aContextParams = null)
  813. {
  814. $sOql = $this->ToOql($bDevelopParams, $aContextParams);
  815. return base64_encode(serialize(array($sOql, $this->m_aParams, $this->m_aModifierProperties)));
  816. }
  817. static public function unserialize($sValue)
  818. {
  819. $aData = unserialize(base64_decode($sValue));
  820. $sOql = $aData[0];
  821. $aParams = $aData[1];
  822. // We've tried to use gzcompress/gzuncompress, but for some specific queries
  823. // it was not working at all (See Trac #193)
  824. // gzuncompress was issuing a warning "data error" and the return object was null
  825. $oRetFilter = self::FromOQL($sOql, $aParams);
  826. $oRetFilter->m_aModifierProperties = $aData[2];
  827. return $oRetFilter;
  828. }
  829. // SImple BUt Structured Query Languag - SubuSQL
  830. //
  831. static private function Value2Expression($value)
  832. {
  833. $sRet = $value;
  834. if (is_array($value))
  835. {
  836. $sRet = VS_START.implode(', ', $value).VS_END;
  837. }
  838. else if (!is_numeric($value))
  839. {
  840. $sRet = "'".addslashes($value)."'";
  841. }
  842. return $sRet;
  843. }
  844. static private function Expression2Value($sExpr)
  845. {
  846. $retValue = $sExpr;
  847. if ((substr($sExpr, 0, 1) == "'") && (substr($sExpr, -1, 1) == "'"))
  848. {
  849. $sNoQuotes = substr($sExpr, 1, -1);
  850. return stripslashes($sNoQuotes);
  851. }
  852. if ((substr($sExpr, 0, 1) == VS_START) && (substr($sExpr, -1, 1) == VS_END))
  853. {
  854. $sNoBracket = substr($sExpr, 1, -1);
  855. $aRetValue = array();
  856. foreach (explode(",", $sNoBracket) as $sItem)
  857. {
  858. $aRetValue[] = self::Expression2Value(trim($sItem));
  859. }
  860. return $aRetValue;
  861. }
  862. return $retValue;
  863. }
  864. // Alternative to object mapping: the data are transfered directly into an array
  865. // This is 10 times faster than creating a set of objects, and makes sense when optimization is required
  866. /**
  867. * @param hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  868. */
  869. public function ToDataArray($aColumns = array(), $aOrderBy = array(), $aArgs = array())
  870. {
  871. $sSQL = MetaModel::MakeSelectQuery($this, $aOrderBy, $aArgs);
  872. $resQuery = CMDBSource::Query($sSQL);
  873. if (!$resQuery) return;
  874. if (count($aColumns) == 0)
  875. {
  876. $aColumns = array_keys(MetaModel::ListAttributeDefs($this->GetClass()));
  877. // Add the standard id (as first column)
  878. array_unshift($aColumns, 'id');
  879. }
  880. $aQueryCols = CMDBSource::GetColumns($resQuery);
  881. $sClassAlias = $this->GetClassAlias();
  882. $aColMap = array();
  883. foreach ($aColumns as $sAttCode)
  884. {
  885. $sColName = $sClassAlias.$sAttCode;
  886. if (in_array($sColName, $aQueryCols))
  887. {
  888. $aColMap[$sAttCode] = $sColName;
  889. }
  890. }
  891. $aRes = array();
  892. while ($aRow = CMDBSource::FetchArray($resQuery))
  893. {
  894. $aMappedRow = array();
  895. foreach ($aColMap as $sAttCode => $sColName)
  896. {
  897. $aMappedRow[$sAttCode] = $aRow[$sColName];
  898. }
  899. $aRes[] = $aMappedRow;
  900. }
  901. CMDBSource::FreeResult($resQuery);
  902. return $aRes;
  903. }
  904. public function ToOQL($bDevelopParams = false, $aContextParams = null)
  905. {
  906. // Currently unused, but could be useful later
  907. $bRetrofitParams = false;
  908. if ($bDevelopParams)
  909. {
  910. if (is_null($aContextParams))
  911. {
  912. $aParams = array_merge($this->m_aParams);
  913. }
  914. else
  915. {
  916. $aParams = array_merge($aContextParams, $this->m_aParams);
  917. }
  918. $aParams = MetaModel::PrepareQueryArguments($aParams);
  919. }
  920. else
  921. {
  922. // Leave it as is, the rendering will be made with parameters in clear
  923. $aParams = null;
  924. }
  925. $sSelectedClasses = implode(', ', array_keys($this->m_aSelectedClasses));
  926. $sRes = 'SELECT '.$sSelectedClasses.' FROM';
  927. $sRes .= ' '.$this->GetFirstJoinedClass().' AS '.$this->GetFirstJoinedClassAlias();
  928. $sRes .= $this->ToOQL_Joins();
  929. $sRes .= " WHERE ".$this->m_oSearchCondition->Render($aParams, $bRetrofitParams);
  930. // Temporary: add more info about other conditions, necessary to avoid strange behaviors with the cache
  931. foreach($this->m_aFullText as $sFullText)
  932. {
  933. $sRes .= " AND MATCHES '$sFullText'";
  934. }
  935. return $sRes;
  936. }
  937. protected function ToOQL_Joins()
  938. {
  939. $sRes = '';
  940. foreach($this->m_aPointingTo as $sExtKey => $aPointingTo)
  941. {
  942. foreach($aPointingTo as $iOperatorCode => $aFilter)
  943. {
  944. foreach($aFilter as $oFilter)
  945. {
  946. switch($iOperatorCode)
  947. {
  948. case TREE_OPERATOR_EQUALS:
  949. $sOperator = ' = ';
  950. break;
  951. case TREE_OPERATOR_BELOW:
  952. $sOperator = ' BELOW ';
  953. break;
  954. case TREE_OPERATOR_BELOW_STRICT:
  955. $sOperator = ' BELOW STRICT ';
  956. break;
  957. case TREE_OPERATOR_NOT_BELOW:
  958. $sOperator = ' NOT BELOW ';
  959. break;
  960. case TREE_OPERATOR_NOT_BELOW_STRICT:
  961. $sOperator = ' NOT BELOW STRICT ';
  962. break;
  963. case TREE_OPERATOR_ABOVE:
  964. $sOperator = ' ABOVE ';
  965. break;
  966. case TREE_OPERATOR_ABOVE_STRICT:
  967. $sOperator = ' ABOVE STRICT ';
  968. break;
  969. case TREE_OPERATOR_NOT_ABOVE:
  970. $sOperator = ' NOT ABOVE ';
  971. break;
  972. case TREE_OPERATOR_NOT_ABOVE_STRICT:
  973. $sOperator = ' NOT ABOVE STRICT ';
  974. break;
  975. }
  976. $sRes .= ' JOIN '.$oFilter->GetFirstJoinedClass().' AS '.$oFilter->GetFirstJoinedClassAlias().' ON '.$this->GetFirstJoinedClassAlias().'.'.$sExtKey.$sOperator.$oFilter->GetFirstJoinedClassAlias().'.id';
  977. $sRes .= $oFilter->ToOQL_Joins();
  978. }
  979. }
  980. }
  981. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  982. {
  983. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  984. {
  985. $sRes .= ' JOIN '.$oForeignFilter->GetFirstJoinedClass().' AS '.$oForeignFilter->GetFirstJoinedClassAlias().' ON '.$oForeignFilter->GetFirstJoinedClassAlias().'.'.$sForeignExtKeyAttCode.' = '.$this->GetFirstJoinedClassAlias().'.id';
  986. $sRes .= $oForeignFilter->ToOQL_Joins();
  987. }
  988. }
  989. return $sRes;
  990. }
  991. protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases)
  992. {
  993. if ($oExpression instanceof BinaryOqlExpression)
  994. {
  995. $sOperator = $oExpression->GetOperator();
  996. $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
  997. $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
  998. return new BinaryExpression($oLeft, $sOperator, $oRight);
  999. }
  1000. elseif ($oExpression instanceof FieldOqlExpression)
  1001. {
  1002. $sClassAlias = $oExpression->GetParent();
  1003. $sFltCode = $oExpression->GetName();
  1004. if (empty($sClassAlias))
  1005. {
  1006. // Need to find the right alias
  1007. // Build an array of field => array of aliases
  1008. $aFieldClasses = array();
  1009. foreach($aClassAliases as $sAlias => $sReal)
  1010. {
  1011. foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode)
  1012. {
  1013. $aFieldClasses[$sAnFltCode][] = $sAlias;
  1014. }
  1015. }
  1016. $sClassAlias = $aFieldClasses[$sFltCode][0];
  1017. }
  1018. return new FieldExpression($sFltCode, $sClassAlias);
  1019. }
  1020. elseif ($oExpression instanceof VariableOqlExpression)
  1021. {
  1022. return new VariableExpression($oExpression->GetName());
  1023. }
  1024. elseif ($oExpression instanceof TrueOqlExpression)
  1025. {
  1026. return new TrueExpression;
  1027. }
  1028. elseif ($oExpression instanceof ScalarOqlExpression)
  1029. {
  1030. return new ScalarExpression($oExpression->GetValue());
  1031. }
  1032. elseif ($oExpression instanceof ListOqlExpression)
  1033. {
  1034. $aItems = array();
  1035. foreach ($oExpression->GetItems() as $oItemExpression)
  1036. {
  1037. $aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases);
  1038. }
  1039. return new ListExpression($aItems);
  1040. }
  1041. elseif ($oExpression instanceof FunctionOqlExpression)
  1042. {
  1043. $aArgs = array();
  1044. foreach ($oExpression->GetArgs() as $oArgExpression)
  1045. {
  1046. $aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases);
  1047. }
  1048. return new FunctionExpression($oExpression->GetVerb(), $aArgs);
  1049. }
  1050. elseif ($oExpression instanceof IntervalOqlExpression)
  1051. {
  1052. return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit());
  1053. }
  1054. else
  1055. {
  1056. throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery));
  1057. }
  1058. }
  1059. // Create a search definition that leads to 0 result, still a valid search object
  1060. static public function FromEmptySet($sClass)
  1061. {
  1062. $oResultFilter = new DBObjectSearch($sClass);
  1063. $oResultFilter->m_oSearchCondition = new FalseExpression;
  1064. return $oResultFilter;
  1065. }
  1066. static protected $m_aOQLQueries = array();
  1067. // Do not filter out depending on user rights
  1068. // In particular when we are currently in the process of evaluating the user rights...
  1069. static public function FromOQL_AllData($sQuery, $aParams = null)
  1070. {
  1071. $oRes = self::FromOQL($sQuery, $aParams);
  1072. $oRes->AllowAllData();
  1073. return $oRes;
  1074. }
  1075. static public function FromOQL($sQuery, $aParams = null)
  1076. {
  1077. if (empty($sQuery)) return null;
  1078. // Query caching
  1079. $bOQLCacheEnabled = true;
  1080. if ($bOQLCacheEnabled && array_key_exists($sQuery, self::$m_aOQLQueries))
  1081. {
  1082. // hit!
  1083. $oClone = self::$m_aOQLQueries[$sQuery]->DeepClone();
  1084. if (!is_null($aParams))
  1085. {
  1086. $oClone->m_aParams = $aParams;
  1087. }
  1088. return $oClone;
  1089. }
  1090. $oOql = new OqlInterpreter($sQuery);
  1091. $oOqlQuery = $oOql->ParseObjectQuery();
  1092. $oMetaModel = new ModelReflectionRuntime();
  1093. $oOqlQuery->Check($oMetaModel, $sQuery); // Exceptions thrown in case of issue
  1094. $sClass = $oOqlQuery->GetClass();
  1095. $sClassAlias = $oOqlQuery->GetClassAlias();
  1096. $oResultFilter = new DBObjectSearch($sClass, $sClassAlias);
  1097. $aAliases = array($sClassAlias => $sClass);
  1098. // Maintain an array of filters, because the flat list is in fact referring to a tree
  1099. // And this will be an easy way to dispatch the conditions
  1100. // $oResultFilter will be referenced by the other filters, or the other way around...
  1101. $aJoinItems = array($sClassAlias => $oResultFilter);
  1102. $aJoinSpecs = $oOqlQuery->GetJoins();
  1103. if (is_array($aJoinSpecs))
  1104. {
  1105. foreach ($aJoinSpecs as $oJoinSpec)
  1106. {
  1107. $sJoinClass = $oJoinSpec->GetClass();
  1108. $sJoinClassAlias = $oJoinSpec->GetClassAlias();
  1109. // Assumption: ext key on the left only !!!
  1110. // normalization should take care of this
  1111. $oLeftField = $oJoinSpec->GetLeftField();
  1112. $sFromClass = $oLeftField->GetParent();
  1113. $sExtKeyAttCode = $oLeftField->GetName();
  1114. $oRightField = $oJoinSpec->GetRightField();
  1115. $sToClass = $oRightField->GetParent();
  1116. $aAliases[$sJoinClassAlias] = $sJoinClass;
  1117. $aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias);
  1118. if ($sFromClass == $sJoinClassAlias)
  1119. {
  1120. $oReceiver = $aJoinItems[$sToClass];
  1121. $oNewComer = $aJoinItems[$sFromClass];
  1122. $aAliasTranslation = array();
  1123. $oReceiver->AddCondition_ReferencedBy_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation);
  1124. }
  1125. else
  1126. {
  1127. $sOperator = $oJoinSpec->GetOperator();
  1128. switch($sOperator)
  1129. {
  1130. case '=':
  1131. $iOperatorCode = TREE_OPERATOR_EQUALS;
  1132. break;
  1133. case 'BELOW':
  1134. $iOperatorCode = TREE_OPERATOR_BELOW;
  1135. break;
  1136. case 'BELOW_STRICT':
  1137. $iOperatorCode = TREE_OPERATOR_BELOW_STRICT;
  1138. break;
  1139. case 'NOT_BELOW':
  1140. $iOperatorCode = TREE_OPERATOR_NOT_BELOW;
  1141. break;
  1142. case 'NOT_BELOW_STRICT':
  1143. $iOperatorCode = TREE_OPERATOR_NOT_BELOW_STRICT;
  1144. break;
  1145. case 'ABOVE':
  1146. $iOperatorCode = TREE_OPERATOR_ABOVE;
  1147. break;
  1148. case 'ABOVE_STRICT':
  1149. $iOperatorCode = TREE_OPERATOR_ABOVE_STRICT;
  1150. break;
  1151. case 'NOT_ABOVE':
  1152. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE;
  1153. break;
  1154. case 'NOT_ABOVE_STRICT':
  1155. $iOperatorCode = TREE_OPERATOR_NOT_ABOVE_STRICT;
  1156. break;
  1157. }
  1158. $oReceiver = $aJoinItems[$sFromClass];
  1159. $oNewComer = $aJoinItems[$sToClass];
  1160. $aAliasTranslation = array();
  1161. $oReceiver->AddCondition_PointingTo_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
  1162. }
  1163. }
  1164. }
  1165. // Check and prepare the select information
  1166. $aSelected = array();
  1167. foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails)
  1168. {
  1169. $sClassToSelect = $oClassDetails->GetValue();
  1170. $aSelected[$sClassToSelect] = $aAliases[$sClassToSelect];
  1171. }
  1172. $oResultFilter->m_aClasses = $aAliases;
  1173. $oResultFilter->SetSelectedClasses($aSelected);
  1174. $oConditionTree = $oOqlQuery->GetCondition();
  1175. if ($oConditionTree instanceof Expression)
  1176. {
  1177. $oResultFilter->m_oSearchCondition = $oResultFilter->OQLExpressionToCondition($sQuery, $oConditionTree, $aAliases);
  1178. }
  1179. if (!is_null($aParams))
  1180. {
  1181. $oResultFilter->m_aParams = $aParams;
  1182. }
  1183. if ($bOQLCacheEnabled)
  1184. {
  1185. self::$m_aOQLQueries[$sQuery] = $oResultFilter->DeepClone();
  1186. }
  1187. return $oResultFilter;
  1188. }
  1189. public function toxpath()
  1190. {
  1191. // #@# a voir...
  1192. }
  1193. static public function fromxpath()
  1194. {
  1195. // #@# a voir...
  1196. }
  1197. }
  1198. ?>