dbobjectsearch.class.php 35 KB

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