dbobjectsearch.class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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. class DBObjectSearch
  25. {
  26. private $m_aClasses; // queried classes (alias => class name), the first item is the class corresponding to this filter (the rest is coming from subfilters)
  27. private $m_aSelectedClasses; // selected for the output (alias => class name)
  28. private $m_oSearchCondition;
  29. private $m_aParams;
  30. private $m_aFullText;
  31. private $m_aPointingTo;
  32. private $m_aReferencedBy;
  33. private $m_aRelatedTo;
  34. // By default, some information may be hidden to the current user
  35. // But it may happen that we need to disable that feature
  36. private $m_bAllowAllData = false;
  37. public function __construct($sClass, $sClassAlias = null)
  38. {
  39. if (is_null($sClassAlias)) $sClassAlias = $sClass;
  40. assert('is_string($sClass)');
  41. assert('MetaModel::IsValidClass($sClass)'); // #@# could do better than an assert, or at least give the caller's reference
  42. // => idee d'un assert avec call stack (autre utilisation = echec sur query SQL)
  43. $this->m_aSelectedClasses = array($sClassAlias => $sClass);
  44. $this->m_aClasses = array($sClassAlias => $sClass);
  45. $this->m_oSearchCondition = new TrueExpression;
  46. $this->m_aParams = array();
  47. $this->m_aFullText = array();
  48. $this->m_aPointingTo = array();
  49. $this->m_aReferencedBy = array();
  50. $this->m_aRelatedTo = array();
  51. }
  52. public function AllowAllData() {$this->m_bAllowAllData = true;}
  53. public function IsAllDataAllowed() {return $this->m_bAllowAllData;}
  54. public function GetClassName($sAlias) {return $this->m_aClasses[$sAlias];}
  55. public function GetJoinedClasses() {return $this->m_aClasses;}
  56. public function GetClass()
  57. {
  58. return reset($this->m_aSelectedClasses);
  59. }
  60. public function GetClassAlias()
  61. {
  62. reset($this->m_aSelectedClasses);
  63. return key($this->m_aSelectedClasses);
  64. }
  65. public function GetFirstJoinedClass()
  66. {
  67. return reset($this->m_aClasses);
  68. }
  69. public function GetFirstJoinedClassAlias()
  70. {
  71. reset($this->m_aClasses);
  72. return key($this->m_aClasses);
  73. }
  74. public function SetSelectedClasses($aNewSet)
  75. {
  76. $this->m_aSelectedClasses = array();
  77. foreach ($aNewSet as $sAlias => $sClass)
  78. {
  79. if (!array_key_exists($sAlias, $this->m_aClasses))
  80. {
  81. throw new CoreException('Unexpected class alias', array('alias'=>$sAlias, 'expected'=>$this->m_aClasses));
  82. }
  83. $this->m_aSelectedClasses[$sAlias] = $sClass;
  84. }
  85. }
  86. public function GetSelectedClasses()
  87. {
  88. return $this->m_aSelectedClasses;
  89. }
  90. public function IsAny()
  91. {
  92. // #@# todo - if (!$this->m_oSearchCondition->IsTrue()) return false;
  93. if (count($this->m_aFullText) > 0) return false;
  94. if (count($this->m_aPointingTo) > 0) return false;
  95. if (count($this->m_aReferencedBy) > 0) return false;
  96. if (count($this->m_aRelatedTo) > 0) return false;
  97. return true;
  98. }
  99. public function Describe()
  100. {
  101. // To replace __Describe
  102. }
  103. public function DescribeConditionPointTo($sExtKeyAttCode)
  104. {
  105. if (!isset($this->m_aPointingTo[$sExtKeyAttCode])) return "";
  106. $oFilter = $this->m_aPointingTo[$sExtKeyAttCode];
  107. if ($oFilter->IsAny()) return "";
  108. $oAtt = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
  109. return $oAtt->GetLabel()." having ({$oFilter->DescribeConditions()})";
  110. }
  111. public function DescribeConditionRefBy($sForeignClass, $sForeignExtKeyAttCode)
  112. {
  113. if (!isset($this->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode])) return "";
  114. $oFilter = $this->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode];
  115. if ($oFilter->IsAny()) return "";
  116. $oAtt = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  117. return "being ".$oAtt->GetLabel()." for ".$sForeignClass."s in ({$oFilter->DescribeConditions()})";
  118. }
  119. public function DescribeConditionRelTo($aRelInfo)
  120. {
  121. $oFilter = $aRelInfo['flt'];
  122. $sRelCode = $aRelInfo['relcode'];
  123. $iMaxDepth = $aRelInfo['maxdepth'];
  124. return "related ($sRelCode... peut mieux faire !, $iMaxDepth dig depth) to a {$oFilter->GetClass()} ({$oFilter->DescribeConditions()})";
  125. }
  126. public function DescribeConditions()
  127. {
  128. $aConditions = array();
  129. $aCondFT = array();
  130. foreach($this->m_aFullText as $sFullText)
  131. {
  132. $aCondFT[] = " contain word(s) '$sFullText'";
  133. }
  134. if (count($aCondFT) > 0)
  135. {
  136. $aConditions[] = "which ".implode(" and ", $aCondFT);
  137. }
  138. // #@# todo - review textual description of the JOIN and search condition (is that still feasible?)
  139. $aConditions[] = $this->RenderCondition();
  140. $aCondPoint = array();
  141. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$oFilter)
  142. {
  143. if ($oFilter->IsAny()) continue;
  144. $aCondPoint[] = $this->DescribeConditionPointTo($sExtKeyAttCode);
  145. }
  146. if (count($aCondPoint) > 0)
  147. {
  148. $aConditions[] = implode(" and ", $aCondPoint);
  149. }
  150. $aCondReferred= array();
  151. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  152. {
  153. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  154. {
  155. if ($oForeignFilter->IsAny()) continue;
  156. $aCondReferred[] = $this->DescribeConditionRefBy($sForeignClass, $sForeignExtKeyAttCode);
  157. }
  158. }
  159. foreach ($this->m_aRelatedTo as $aRelInfo)
  160. {
  161. $aCondReferred[] = $this->DescribeConditionRelTo($aRelInfo);
  162. }
  163. if (count($aCondReferred) > 0)
  164. {
  165. $aConditions[] = implode(" and ", $aCondReferred);
  166. }
  167. return implode(" and ", $aConditions);
  168. }
  169. public function __DescribeHTML()
  170. {
  171. try
  172. {
  173. $sConditionDesc = $this->DescribeConditions();
  174. }
  175. catch (MissingQueryArgument $e)
  176. {
  177. $sConditionDesc = '?missing query argument?';
  178. }
  179. if (!empty($sConditionDesc))
  180. {
  181. return "Objects of class '".$this->GetClass()."', $sConditionDesc";
  182. }
  183. return "Any object of class '".$this->GetClass()."'";
  184. }
  185. protected function TransferConditionExpression($oFilter, $aTranslation)
  186. {
  187. $oTranslated = $oFilter->GetCriteria()->Translate($aTranslation, false, false /* leave unresolved fields */);
  188. $this->AddConditionExpression($oTranslated);
  189. // #@# what about collisions in parameter names ???
  190. $this->m_aParams = array_merge($this->m_aParams, $oFilter->m_aParams);
  191. }
  192. public function ResetCondition()
  193. {
  194. $this->m_oSearchCondition = new TrueExpression();
  195. // ? is that usefull/enough, do I need to rebuild the list after the subqueries ?
  196. }
  197. public function MergeConditionExpression($oExpression)
  198. {
  199. $this->m_oSearchCondition = $this->m_oSearchCondition->LogOr($oExpression);
  200. }
  201. public function AddConditionExpression($oExpression)
  202. {
  203. $this->m_oSearchCondition = $this->m_oSearchCondition->LogAnd($oExpression);
  204. }
  205. public function AddNameCondition($sName)
  206. {
  207. $oValueExpr = new ScalarExpression($sName);
  208. $oNameExpr = new FieldExpression('friendlyname', $this->GetClassAlias());
  209. $oNewCondition = new BinaryExpression($oNameExpr, '=', $oValueExpr);
  210. $this->AddConditionExpression($oNewCondition);
  211. }
  212. public function AddCondition($sFilterCode, $value, $sOpCode = null)
  213. {
  214. MyHelpers::CheckKeyInArray('filter code', $sFilterCode, MetaModel::GetClassFilterDefs($this->GetClass()));
  215. $oFilterDef = MetaModel::GetClassFilterDef($this->GetClass(), $sFilterCode);
  216. $oField = new FieldExpression($sFilterCode, $this->GetClassAlias());
  217. if (empty($sOpCode))
  218. {
  219. if ($sFilterCode == 'id')
  220. {
  221. $sOpCode = '=';
  222. }
  223. else
  224. {
  225. $oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sFilterCode);
  226. $oNewCondition = $oAttDef->GetSmartConditionExpression($value, $oField, $this->m_aParams);
  227. $this->AddConditionExpression($oNewCondition);
  228. return;
  229. }
  230. }
  231. MyHelpers::CheckKeyInArray('operator', $sOpCode, $oFilterDef->GetOperators());
  232. // Preserve backward compatibility - quick n'dirty way to change that API semantic
  233. //
  234. switch($sOpCode)
  235. {
  236. case 'SameDay':
  237. case 'SameMonth':
  238. case 'SameYear':
  239. case 'Today':
  240. case '>|':
  241. case '<|':
  242. case '=|':
  243. throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', array('operator' => $sOpCode));
  244. break;
  245. case "IN":
  246. if (!is_array($value)) $value = array($value);
  247. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  248. $sOQLCondition = $oField->Render()." IN $sListExpr";
  249. break;
  250. case "NOTIN":
  251. if (!is_array($value)) $value = array($value);
  252. $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
  253. $sOQLCondition = $oField->Render()." NOT IN $sListExpr";
  254. break;
  255. case 'Contains':
  256. $this->m_aParams[$sFilterCode] = "%$value%";
  257. $sOperator = 'LIKE';
  258. break;
  259. case 'Begins with':
  260. $this->m_aParams[$sFilterCode] = "$value%";
  261. $sOperator = 'LIKE';
  262. break;
  263. case 'Finishes with':
  264. $this->m_aParams[$sFilterCode] = "%$value";
  265. $sOperator = 'LIKE';
  266. break;
  267. default:
  268. $this->m_aParams[$sFilterCode] = $value;
  269. $sOperator = $sOpCode;
  270. }
  271. switch($sOpCode)
  272. {
  273. case "IN":
  274. case "NOTIN":
  275. $oNewCondition = Expression::FromOQL($sOQLCondition);
  276. break;
  277. case 'Contains':
  278. case 'Begins with':
  279. case 'Finishes with':
  280. default:
  281. $oRightExpr = new VariableExpression($sFilterCode);
  282. $oNewCondition = new BinaryExpression($oField, $sOperator, $oRightExpr);
  283. }
  284. $this->AddConditionExpression($oNewCondition);
  285. }
  286. /**
  287. * Specify a condition on external keys or link sets
  288. * @param sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
  289. * Example: infra_list->ci_id->location_id->country
  290. * @param value The value to match
  291. * @return void
  292. */
  293. public function AddConditionAdvanced($sAttSpec, $value)
  294. {
  295. $sClass = $this->GetClass();
  296. $iPos = strpos($sAttSpec, '->');
  297. if ($iPos !== false)
  298. {
  299. $sAttCode = substr($sAttSpec, 0, $iPos);
  300. $sSubSpec = substr($sAttSpec, $iPos + 2);
  301. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  302. {
  303. throw new Exception("Invalid attribute code '$sClass/$sAttCode' in condition specification '$sAttSpec'");
  304. }
  305. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  306. if ($oAttDef->IsLinkSet())
  307. {
  308. $sTargetClass = $oAttDef->GetLinkedClass();
  309. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  310. $oNewFilter = new DBObjectSearch($sTargetClass);
  311. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  312. $this->AddCondition_ReferencedBy($oNewFilter, $sExtKeyToMe);
  313. }
  314. elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  315. {
  316. $sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE);
  317. $oNewFilter = new DBObjectSearch($sTargetClass);
  318. $oNewFilter->AddConditionAdvanced($sSubSpec, $value);
  319. $this->AddCondition_PointingTo($oNewFilter, $sAttCode);
  320. }
  321. else
  322. {
  323. throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key");
  324. }
  325. }
  326. else
  327. {
  328. // $sAttSpec is an attribute code
  329. //
  330. $this->AddCondition($sAttSpec, $value);
  331. }
  332. }
  333. public function AddCondition_FullText($sFullText)
  334. {
  335. $this->m_aFullText[] = $sFullText;
  336. }
  337. protected function AddToNameSpace(&$aClassAliases, &$aAliasTranslation)
  338. {
  339. $sOrigAlias = $this->GetClassAlias();
  340. if (array_key_exists($sOrigAlias, $aClassAliases))
  341. {
  342. $sNewAlias = MetaModel::GenerateUniqueAlias($aClassAliases, $sOrigAlias, $this->GetClass());
  343. $this->m_aSelectedClasses[$sNewAlias] = $this->GetClass();
  344. unset($this->m_aSelectedClasses[$sOrigAlias]);
  345. // Translate the condition expression with the new alias
  346. $aAliasTranslation[$sOrigAlias]['*'] = $sNewAlias;
  347. }
  348. // add the alias into the filter aliases list
  349. $aClassAliases[$this->GetClassAlias()] = $this->GetClass();
  350. foreach($this->m_aPointingTo as $sExtKeyAttCode=>$oFilter)
  351. {
  352. $oFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  353. }
  354. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  355. {
  356. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  357. {
  358. $oForeignFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
  359. }
  360. }
  361. }
  362. public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode)
  363. {
  364. $aAliasTranslation = array();
  365. $res = $this->AddCondition_PointingTo_InNameSpace($oFilter, $sExtKeyAttCode, $this->m_aClasses, $aAliasTranslation);
  366. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  367. return $res;
  368. }
  369. protected function AddCondition_PointingTo_InNameSpace(DBObjectSearch $oFilter, $sExtKeyAttCode, &$aClassAliases, &$aAliasTranslation)
  370. {
  371. if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode))
  372. {
  373. throw new CoreWarning("The attribute code '$sExtKeyAttCode' is not an external key of the class '{$this->GetClass()}' - the condition will be ignored");
  374. }
  375. $oAttExtKey = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
  376. if(!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass()))
  377. {
  378. 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()}");
  379. }
  380. if (array_key_exists($sExtKeyAttCode, $this->m_aPointingTo))
  381. {
  382. $this->m_aPointingTo[$sExtKeyAttCode]->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation);
  383. }
  384. else
  385. {
  386. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  387. // #@# The condition expression found in that filter should not be used - could be another kind of structure like a join spec tree !!!!
  388. // $oNewFilter = clone $oFilter;
  389. // $oNewFilter->ResetCondition();
  390. $this->m_aPointingTo[$sExtKeyAttCode] = $oFilter;
  391. }
  392. }
  393. public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode)
  394. {
  395. $aAliasTranslation = array();
  396. $res = $this->AddCondition_ReferencedBy_InNameSpace($oFilter, $sForeignExtKeyAttCode, $this->m_aClasses, $aAliasTranslation);
  397. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  398. return $res;
  399. }
  400. protected function AddCondition_ReferencedBy_InNameSpace(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, &$aClassAliases, &$aAliasTranslation)
  401. {
  402. $sForeignClass = $oFilter->GetClass();
  403. $sForeignClassAlias = $oFilter->GetClassAlias();
  404. if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode))
  405. {
  406. throw new CoreException("The attribute code '$sForeignExtKeyAttCode' is not an external key of the class '{$sForeignClass}' - the condition will be ignored");
  407. }
  408. $oAttExtKey = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
  409. if(!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass()))
  410. {
  411. 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()}");
  412. }
  413. if (array_key_exists($sForeignClass, $this->m_aReferencedBy) && array_key_exists($sForeignExtKeyAttCode, $this->m_aReferencedBy[$sForeignClass]))
  414. {
  415. $this->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode]->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation);
  416. }
  417. else
  418. {
  419. $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
  420. // #@# The condition expression found in that filter should not be used - could be another kind of structure like a join spec tree !!!!
  421. //$oNewFilter = clone $oFilter;
  422. //$oNewFilter->ResetCondition();
  423. $this->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode]= $oFilter;
  424. }
  425. }
  426. public function AddCondition_LinkedTo(DBObjectSearch $oLinkFilter, $sExtKeyAttCodeToMe, $sExtKeyAttCodeTarget, DBObjectSearch $oFilterTarget)
  427. {
  428. $oLinkFilterFinal = clone $oLinkFilter;
  429. $oLinkFilterFinal->AddCondition_PointingTo($sExtKeyAttCodeToMe);
  430. $this->AddCondition_ReferencedBy($oLinkFilterFinal, $sExtKeyAttCodeToMe);
  431. }
  432. public function AddCondition_RelatedTo(DBObjectSearch $oFilter, $sRelCode, $iMaxDepth)
  433. {
  434. MyHelpers::CheckValueInArray('relation code', $sRelCode, MetaModel::EnumRelations());
  435. $this->m_aRelatedTo[] = array('flt'=>$oFilter, 'relcode'=>$sRelCode, 'maxdepth'=>$iMaxDepth);
  436. }
  437. public function MergeWith($oFilter)
  438. {
  439. $aAliasTranslation = array();
  440. $res = $this->MergeWith_InNamespace($oFilter, $this->m_aClasses, $aAliasTranslation);
  441. $this->TransferConditionExpression($oFilter, $aAliasTranslation);
  442. return $res;
  443. }
  444. protected function MergeWith_InNamespace($oFilter, &$aClassAliases, &$aAliasTranslation)
  445. {
  446. if ($this->GetClass() != $oFilter->GetClass())
  447. {
  448. throw new CoreException("Attempting to merge a filter of class '{$this->GetClass()}' with a filter of class '{$oFilter->GetClass()}'");
  449. }
  450. // Translate search condition into our aliasing scheme
  451. $aAliasTranslation[$oFilter->GetClassAlias()]['*'] = $this->GetClassAlias();
  452. $this->m_aFullText = array_merge($this->m_aFullText, $oFilter->m_aFullText);
  453. $this->m_aRelatedTo = array_merge($this->m_aRelatedTo, $oFilter->m_aRelatedTo);
  454. foreach($oFilter->m_aPointingTo as $sExtKeyAttCode=>$oExtFilter)
  455. {
  456. $this->AddCondition_PointingTo_InNamespace($oExtFilter, $sExtKeyAttCode, $aClassAliases, $aAliasTranslation);
  457. }
  458. foreach($oFilter->m_aReferencedBy as $sForeignClass => $aReferences)
  459. {
  460. foreach($aReferences as $sForeignExtKeyAttCode => $oForeignFilter)
  461. {
  462. $this->AddCondition_ReferencedBy_InNamespace($oForeignFilter, $sForeignExtKeyAttCode, $aClassAliases, $aAliasTranslation);
  463. }
  464. }
  465. }
  466. public function GetCriteria() {return $this->m_oSearchCondition;}
  467. public function GetCriteria_FullText() {return $this->m_aFullText;}
  468. public function GetCriteria_PointingTo($sKeyAttCode = "")
  469. {
  470. if (empty($sKeyAttCode))
  471. {
  472. return $this->m_aPointingTo;
  473. }
  474. if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) return null;
  475. return $this->m_aPointingTo[$sKeyAttCode];
  476. }
  477. public function GetCriteria_ReferencedBy($sRemoteClass = "", $sForeignExtKeyAttCode = "")
  478. {
  479. if (empty($sRemoteClass))
  480. {
  481. return $this->m_aReferencedBy;
  482. }
  483. if (!array_key_exists($sRemoteClass, $this->m_aReferencedBy)) return null;
  484. if (empty($sForeignExtKeyAttCode))
  485. {
  486. return $this->m_aReferencedBy[$sRemoteClass];
  487. }
  488. if (!array_key_exists($sForeignExtKeyAttCode, $this->m_aReferencedBy[$sRemoteClass])) return null;
  489. return $this->m_aReferencedBy[$sRemoteClass][$sForeignExtKeyAttCode];
  490. }
  491. public function GetCriteria_RelatedTo()
  492. {
  493. return $this->m_aRelatedTo;
  494. }
  495. public function GetInternalParams()
  496. {
  497. return $this->m_aParams;
  498. }
  499. public function RenderCondition()
  500. {
  501. return $this->m_oSearchCondition->Render($this->m_aParams, false);
  502. }
  503. public function serialize($bDevelopParams = false, $aContextParams = null)
  504. {
  505. $sOql = $this->ToOql($bDevelopParams, $aContextParams);
  506. return base64_encode(serialize(array($sOql, $this->m_aParams)));
  507. }
  508. static public function unserialize($sValue)
  509. {
  510. $aData = unserialize(base64_decode($sValue));
  511. $sOql = $aData[0];
  512. $aParams = $aData[1];
  513. // We've tried to use gzcompress/gzuncompress, but for some specific queries
  514. // it was not working at all (See Trac #193)
  515. // gzuncompress was issuing a warning "data error" and the return object was null
  516. return self::FromOQL($sOql, $aParams);
  517. }
  518. // SImple BUt Structured Query Languag - SubuSQL
  519. //
  520. static private function Value2Expression($value)
  521. {
  522. $sRet = $value;
  523. if (is_array($value))
  524. {
  525. $sRet = VS_START.implode(', ', $value).VS_END;
  526. }
  527. else if (!is_numeric($value))
  528. {
  529. $sRet = "'".addslashes($value)."'";
  530. }
  531. return $sRet;
  532. }
  533. static private function Expression2Value($sExpr)
  534. {
  535. $retValue = $sExpr;
  536. if ((substr($sExpr, 0, 1) == "'") && (substr($sExpr, -1, 1) == "'"))
  537. {
  538. $sNoQuotes = substr($sExpr, 1, -1);
  539. return stripslashes($sNoQuotes);
  540. }
  541. if ((substr($sExpr, 0, 1) == VS_START) && (substr($sExpr, -1, 1) == VS_END))
  542. {
  543. $sNoBracket = substr($sExpr, 1, -1);
  544. $aRetValue = array();
  545. foreach (explode(",", $sNoBracket) as $sItem)
  546. {
  547. $aRetValue[] = self::Expression2Value(trim($sItem));
  548. }
  549. return $aRetValue;
  550. }
  551. return $retValue;
  552. }
  553. // Alternative to object mapping: the data are transfered directly into an array
  554. // This is 10 times faster than creating a set of objects, and makes sense when optimization is required
  555. public function ToDataArray($aColumns = array(), $aOrderBy = array(), $aArgs = array())
  556. {
  557. $sSQL = MetaModel::MakeSelectQuery($this, $aOrderBy, $aArgs);
  558. $resQuery = CMDBSource::Query($sSQL);
  559. if (!$resQuery) return;
  560. if (count($aColumns) == 0)
  561. {
  562. $aColumns = array_keys(MetaModel::ListAttributeDefs($this->GetClass()));
  563. // Add the standard id (as first column)
  564. array_unshift($aColumns, 'id');
  565. }
  566. $aQueryCols = CMDBSource::GetColumns($resQuery);
  567. $sClassAlias = $this->GetClassAlias();
  568. $aColMap = array();
  569. foreach ($aColumns as $sAttCode)
  570. {
  571. $sColName = $sClassAlias.$sAttCode;
  572. if (in_array($sColName, $aQueryCols))
  573. {
  574. $aColMap[$sAttCode] = $sColName;
  575. }
  576. }
  577. $aRes = array();
  578. while ($aRow = CMDBSource::FetchArray($resQuery))
  579. {
  580. $aMappedRow = array();
  581. foreach ($aColMap as $sAttCode => $sColName)
  582. {
  583. $aMappedRow[$sAttCode] = $aRow[$sColName];
  584. }
  585. $aRes[] = $aMappedRow;
  586. }
  587. CMDBSource::FreeResult($resQuery);
  588. return $aRes;
  589. }
  590. public function ToOQL($bDevelopParams = false, $aContextParams = null)
  591. {
  592. // Currently unused, but could be useful later
  593. $bRetrofitParams = false;
  594. if ($bDevelopParams)
  595. {
  596. if (is_null($aContextParams))
  597. {
  598. $aParams = array_merge($this->m_aParams);
  599. }
  600. else
  601. {
  602. $aParams = array_merge($aContextParams, $this->m_aParams);
  603. }
  604. }
  605. else
  606. {
  607. // Leave it as is, the rendering will be made with parameters in clear
  608. $aParams = null;
  609. }
  610. $sSelectedClasses = implode(', ', array_keys($this->m_aSelectedClasses));
  611. $sRes = 'SELECT '.$sSelectedClasses.' FROM';
  612. $sRes .= ' '.$this->GetClass().' AS '.$this->GetClassAlias();
  613. $sRes .= $this->ToOQL_Joins();
  614. $sRes .= " WHERE ".$this->m_oSearchCondition->Render($aParams, $bRetrofitParams);
  615. // Temporary: add more info about other conditions, necessary to avoid strange behaviors with the cache
  616. foreach($this->m_aFullText as $sFullText)
  617. {
  618. $sRes .= " AND MATCHES '$sFullText'";
  619. }
  620. return $sRes;
  621. }
  622. protected function ToOQL_Joins()
  623. {
  624. $sRes = '';
  625. foreach($this->m_aPointingTo as $sExtKey=>$oFilter)
  626. {
  627. $sRes .= ' JOIN '.$oFilter->GetClass().' AS '.$oFilter->GetClassAlias().' ON '.$this->GetClassAlias().'.'.$sExtKey.' = '.$oFilter->GetClassAlias().'.id';
  628. $sRes .= $oFilter->ToOQL_Joins();
  629. }
  630. foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
  631. {
  632. foreach($aReferences as $sForeignExtKeyAttCode=>$oForeignFilter)
  633. {
  634. $sRes .= ' JOIN '.$oForeignFilter->GetClass().' AS '.$oForeignFilter->GetClassAlias().' ON '.$oForeignFilter->GetClassAlias().'.'.$sForeignExtKeyAttCode.' = '.$this->GetClassAlias().'.id';
  635. $sRes .= $oForeignFilter->ToOQL_Joins();
  636. }
  637. }
  638. return $sRes;
  639. }
  640. protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases)
  641. {
  642. if ($oExpression instanceof BinaryOqlExpression)
  643. {
  644. $sOperator = $oExpression->GetOperator();
  645. $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
  646. $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
  647. return new BinaryExpression($oLeft, $sOperator, $oRight);
  648. }
  649. elseif ($oExpression instanceof FieldOqlExpression)
  650. {
  651. $sClassAlias = $oExpression->GetParent();
  652. $sFltCode = $oExpression->GetName();
  653. if (empty($sClassAlias))
  654. {
  655. // Try to find an alias
  656. // Build an array of field => array of aliases
  657. $aFieldClasses = array();
  658. foreach($aClassAliases as $sAlias => $sReal)
  659. {
  660. foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode)
  661. {
  662. $aFieldClasses[$sAnFltCode][] = $sAlias;
  663. }
  664. }
  665. if (!array_key_exists($sFltCode, $aFieldClasses))
  666. {
  667. throw new OqlNormalizeException('Unknown filter code', $sQuery, $oExpression->GetNameDetails(), array_keys($aFieldClasses));
  668. }
  669. if (count($aFieldClasses[$sFltCode]) > 1)
  670. {
  671. throw new OqlNormalizeException('Ambiguous filter code', $sQuery, $oExpression->GetNameDetails());
  672. }
  673. $sClassAlias = $aFieldClasses[$sFltCode][0];
  674. }
  675. else
  676. {
  677. if (!array_key_exists($sClassAlias, $aClassAliases))
  678. {
  679. throw new OqlNormalizeException('Unknown class [alias]', $sQuery, $oExpression->GetParentDetails(), array_keys($aClassAliases));
  680. }
  681. $sClass = $aClassAliases[$sClassAlias];
  682. if (!MetaModel::IsValidFilterCode($sClass, $sFltCode))
  683. {
  684. throw new OqlNormalizeException('Unknown filter code', $sQuery, $oExpression->GetNameDetails(), MetaModel::GetFiltersList($sClass));
  685. }
  686. }
  687. return new FieldExpression($sFltCode, $sClassAlias);
  688. }
  689. elseif ($oExpression instanceof VariableOqlExpression)
  690. {
  691. return new VariableExpression($oExpression->GetName());
  692. }
  693. elseif ($oExpression instanceof TrueOqlExpression)
  694. {
  695. return new TrueExpression;
  696. }
  697. elseif ($oExpression instanceof ScalarOqlExpression)
  698. {
  699. return new ScalarExpression($oExpression->GetValue());
  700. }
  701. elseif ($oExpression instanceof ListOqlExpression)
  702. {
  703. $aItems = array();
  704. foreach ($oExpression->GetItems() as $oItemExpression)
  705. {
  706. $aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases);
  707. }
  708. return new ListExpression($aItems);
  709. }
  710. elseif ($oExpression instanceof FunctionOqlExpression)
  711. {
  712. $aArgs = array();
  713. foreach ($oExpression->GetArgs() as $oArgExpression)
  714. {
  715. $aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases);
  716. }
  717. return new FunctionExpression($oExpression->GetVerb(), $aArgs);
  718. }
  719. elseif ($oExpression instanceof IntervalOqlExpression)
  720. {
  721. return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit());
  722. }
  723. else
  724. {
  725. throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery));
  726. }
  727. }
  728. // Create a search definition that leads to 0 result, still a valid search object
  729. static public function FromEmptySet($sClass)
  730. {
  731. $oResultFilter = new DBObjectSearch($sClass);
  732. $oResultFilter->m_oSearchCondition = new FalseExpression;
  733. return $oResultFilter;
  734. }
  735. static protected $m_aOQLQueries = array();
  736. // Do not filter out depending on user rights
  737. // In particular when we are currently in the process of evaluating the user rights...
  738. static public function FromOQL_AllData($sQuery, $aParams = null)
  739. {
  740. $oRes = self::FromOQL($sQuery, $aParams);
  741. $oRes->AllowAllData();
  742. return $oRes;
  743. }
  744. static public function FromOQL($sQuery, $aParams = null)
  745. {
  746. if (empty($sQuery)) return null;
  747. // Query caching
  748. $bOQLCacheEnabled = true;
  749. if ($bOQLCacheEnabled && array_key_exists($sQuery, self::$m_aOQLQueries))
  750. {
  751. // hit!
  752. return clone self::$m_aOQLQueries[$sQuery];
  753. }
  754. $oOql = new OqlInterpreter($sQuery);
  755. $oOqlQuery = $oOql->ParseObjectQuery();
  756. $sClass = $oOqlQuery->GetClass();
  757. $sClassAlias = $oOqlQuery->GetClassAlias();
  758. if (!MetaModel::IsValidClass($sClass))
  759. {
  760. throw new OqlNormalizeException('Unknown class', $sQuery, $oOqlQuery->GetClassDetails(), MetaModel::GetClasses());
  761. }
  762. $oResultFilter = new DBObjectSearch($sClass, $sClassAlias);
  763. $aAliases = array($sClassAlias => $sClass);
  764. // Maintain an array of filters, because the flat list is in fact referring to a tree
  765. // And this will be an easy way to dispatch the conditions
  766. // $oResultFilter will be referenced by the other filters, or the other way around...
  767. $aJoinItems = array($sClassAlias => $oResultFilter);
  768. $aJoinSpecs = $oOqlQuery->GetJoins();
  769. if (is_array($aJoinSpecs))
  770. {
  771. foreach ($aJoinSpecs as $oJoinSpec)
  772. {
  773. $sJoinClass = $oJoinSpec->GetClass();
  774. $sJoinClassAlias = $oJoinSpec->GetClassAlias();
  775. if (!MetaModel::IsValidClass($sJoinClass))
  776. {
  777. throw new OqlNormalizeException('Unknown class', $sQuery, $oJoinSpec->GetClassDetails(), MetaModel::GetClasses());
  778. }
  779. if (array_key_exists($sJoinClassAlias, $aAliases))
  780. {
  781. if ($sJoinClassAlias != $sJoinClass)
  782. {
  783. throw new OqlNormalizeException('Duplicate class alias', $sQuery, $oJoinSpec->GetClassAliasDetails());
  784. }
  785. else
  786. {
  787. throw new OqlNormalizeException('Duplicate class name', $sQuery, $oJoinSpec->GetClassDetails());
  788. }
  789. }
  790. // Assumption: ext key on the left only !!!
  791. // normalization should take care of this
  792. $oLeftField = $oJoinSpec->GetLeftField();
  793. $sFromClass = $oLeftField->GetParent();
  794. $sExtKeyAttCode = $oLeftField->GetName();
  795. $oRightField = $oJoinSpec->GetRightField();
  796. $sToClass = $oRightField->GetParent();
  797. $sPKeyDescriptor = $oRightField->GetName();
  798. if ($sPKeyDescriptor != 'id')
  799. {
  800. throw new OqlNormalizeException('Wrong format for Join clause (right hand), expecting an id', $sQuery, $oRightField->GetNameDetails(), array('id'));
  801. }
  802. $aAliases[$sJoinClassAlias] = $sJoinClass;
  803. $aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias);
  804. if (!array_key_exists($sFromClass, $aJoinItems))
  805. {
  806. throw new OqlNormalizeException('Unknown class in join condition (left expression)', $sQuery, $oLeftField->GetParentDetails(), array_keys($aJoinItems));
  807. }
  808. if (!array_key_exists($sToClass, $aJoinItems))
  809. {
  810. throw new OqlNormalizeException('Unknown class in join condition (right expression)', $sQuery, $oRightField->GetParentDetails(), array_keys($aJoinItems));
  811. }
  812. $aExtKeys = array_keys(MetaModel::GetExternalKeys($aAliases[$sFromClass]));
  813. if (!in_array($sExtKeyAttCode, $aExtKeys))
  814. {
  815. throw new OqlNormalizeException('Unknown external key in join condition (left expression)', $sQuery, $oLeftField->GetNameDetails(), $aExtKeys);
  816. }
  817. if ($sFromClass == $sJoinClassAlias)
  818. {
  819. $aJoinItems[$sToClass]->AddCondition_ReferencedBy($aJoinItems[$sFromClass], $sExtKeyAttCode);
  820. }
  821. else
  822. {
  823. $aJoinItems[$sFromClass]->AddCondition_PointingTo($aJoinItems[$sToClass], $sExtKeyAttCode);
  824. }
  825. }
  826. }
  827. // Check and prepare the select information
  828. $aSelected = array();
  829. foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails)
  830. {
  831. $sClassToSelect = $oClassDetails->GetValue();
  832. if (!array_key_exists($sClassToSelect, $aAliases))
  833. {
  834. throw new OqlNormalizeException('Unknown class [alias]', $sQuery, $oClassDetails, array_keys($aAliases));
  835. }
  836. $aSelected[$sClassToSelect] = $aAliases[$sClassToSelect];
  837. }
  838. $oResultFilter->m_aClasses = $aAliases;
  839. $oResultFilter->SetSelectedClasses($aSelected);
  840. $oConditionTree = $oOqlQuery->GetCondition();
  841. if ($oConditionTree instanceof Expression)
  842. {
  843. $oResultFilter->m_oSearchCondition = $oResultFilter->OQLExpressionToCondition($sQuery, $oConditionTree, $aAliases);
  844. }
  845. if (!is_null($aParams))
  846. {
  847. $oResultFilter->m_aParams = $aParams;
  848. }
  849. if ($bOQLCacheEnabled)
  850. {
  851. self::$m_aOQLQueries[$sQuery] = clone $oResultFilter;
  852. }
  853. return $oResultFilter;
  854. }
  855. public function toxpath()
  856. {
  857. // #@# a voir...
  858. }
  859. static public function fromxpath()
  860. {
  861. // #@# a voir...
  862. }
  863. }
  864. ?>