dbobjectsearch.class.php 42 KB

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