dbobjectsearch.class.php 42 KB

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