dbobjectsearch.class.php 41 KB

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