dbobjectsearch.class.php 35 KB

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