dbobjectsearch.class.php 41 KB

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