dbobjectsearch.class.php 30 KB

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