dbobjectsearch.class.php 42 KB

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