dbobjectsearch.class.php 30 KB

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