dbobjectsearch.class.php 42 KB

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