dbobjectsearch.class.php 44 KB

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