dbobjectsearch.class.php 43 KB

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