dbobjectsearch.class.php 32 KB

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