dbobjectsearch.class.php 43 KB

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