dbobjectsearch.class.php 30 KB

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