dbobjectsearch.class.php 41 KB

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