dbobjectsearch.class.php 42 KB

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