qbf.module 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. <?php
  2. /**
  3. * @file
  4. * Query By Form
  5. *
  6. * This module allows node modules to add a query by form tab for their node
  7. * types to the default search form
  8. *
  9. * @copyright 2008-2009 Ouest Systemes Informatiques (OSInet)
  10. * @author Frederic G. MARAND
  11. * @license Licensed under the CeCILL 2.0 and the General Public Licence version 2 or later
  12. * @package QBF
  13. */
  14. // $Id: qbf.module,v 1.9.4.6 2009-03-21 16:53:31 marand Exp $
  15. /**
  16. * Saved error reporting level.
  17. *
  18. * QBF module is supposed to pass parsing at E_ALL|E_STRICT, but other modules
  19. * may not be so strict, so we save the level at the start of the module and
  20. * restore it at the end of the module.
  21. */
  22. global $_qbf_er;
  23. $_qbf_er = error_reporting(E_ALL | E_STRICT);
  24. /**
  25. * Remove this element from the generated form
  26. */
  27. define('QBF_LEVEL_REMOVE', 0);
  28. /**
  29. * This element is only for display in the generated form: do not include it
  30. * in the query vector.
  31. */
  32. define('QBF_LEVEL_DISPLAY', 1);
  33. /**
  34. * Include this element in the generated form and in the query vector, but do
  35. * not mark it as required.
  36. */
  37. define('QBF_LEVEL_OPTIONAL', 2);
  38. /**
  39. * Include this element in the generated form and in the query vector, and
  40. * mark it as required.
  41. */
  42. define('QBF_LEVEL_REQUIRED', 3);
  43. /**
  44. * The main QBF path.
  45. *
  46. * It MUST be a single component path, without a "/", otherwise qbf_menu() will
  47. * need to be changed.
  48. *
  49. * @ingroup paths
  50. * @see qbf_menu()
  51. */
  52. define('QBF_PATH_MAIN', 'qbf');
  53. /**
  54. * The QBF autocomplete path for search fields
  55. * @ingroup paths
  56. */
  57. define('QBF_PATH_AC', 'qbf/ac');
  58. /**
  59. * The path to the QBF settings page
  60. */
  61. define('QBF_PATH_SETTINGS', 'admin/settings/qbf');
  62. /**
  63. * Authorize use of QBF searches
  64. */
  65. define('QBF_PERM_QUERY', 'use QBF search functions');
  66. /**
  67. * Authorize QBF administration
  68. */
  69. define('QBF_PERM_ADMIN', 'administer QBF');
  70. /**
  71. * The name of the table used to store queries
  72. */
  73. define('QBF_TABLE_NAME', 'qbf_queries');
  74. /**
  75. * Notify owner about saved query deletions, variable name.
  76. */
  77. define('QBF_VAR_NOTIFY_DELETE', 'qbf_notify_delete');
  78. /**
  79. * Notify owner about saved query deletions, default value.
  80. */
  81. define('QBF_DEF_NOTIFY_DELETE', FALSE);
  82. /**
  83. * A class wrapper for saved QBF queries
  84. */
  85. class Qbf_Query
  86. {
  87. public $qid;
  88. public $uid;
  89. public $name;
  90. public $type;
  91. public $query;
  92. public $created;
  93. public $updated;
  94. /**
  95. * Constructor
  96. *
  97. * @param string $name
  98. * @param array $ar_values
  99. * @return void
  100. */
  101. public function __construct($type, $name, $ar_values)
  102. {
  103. global $user;
  104. $this->qid = 0; // will be autoset by the DB serial
  105. $this->uid = $user->uid;
  106. $this->type = $type;
  107. $this->name = $name;
  108. $this->query = serialize($ar_values);
  109. $this->created = $this->updated = time();
  110. }
  111. /**
  112. * Save a named query to the DB, erasing previous homonym queries is any exists.
  113. *
  114. * @return int
  115. */
  116. public function save()
  117. {
  118. // Avoid duplicates
  119. if (!empty($this->name))
  120. {
  121. $sq = "DELETE FROM {%s} WHERE name = '%s' AND uid = '%d' ";
  122. db_query($sq, QBF_TABLE_NAME, $this->name, $this->uid);
  123. // $n = db_affected_rows(); // Know how many homonym queries we deleted
  124. }
  125. $ret = drupal_write_record(QBF_TABLE_NAME, $this); // no update param: we just deleted the previous version
  126. if ($ret) // has to be SAVED_NEW, by construction
  127. {
  128. $ret = $this->qid; // from serial
  129. }
  130. return $ret;
  131. }
  132. }
  133. /**
  134. * Recursively build a query array from the form and its values
  135. *
  136. * In the current version, element names are supposed to be unique, even at
  137. * different levels in the tree.
  138. *
  139. * @ingroup forms
  140. * @param array $form
  141. * @param array $form_values
  142. */
  143. function _qbf_extract_query($element_id, $form, $form_values)
  144. {
  145. // Elements which are unnamed (form), removed, or display-only have no place in the query
  146. if (!empty($element_id) && array_key_exists('#qbf', $form) && array_key_exists('#level', $form['#qbf'])
  147. && $form['#qbf']['#level'] >= QBF_LEVEL_OPTIONAL)
  148. {
  149. $ret = array($element_id => $form_values[$element_id]);
  150. }
  151. else
  152. {
  153. $ret = array();
  154. }
  155. // QBF level is not inherited, so this loop is outside the "if" above
  156. foreach (element_children($form) as $child_name)
  157. {
  158. $ret += _qbf_extract_query($child_name, $form[$child_name], $form_values);
  159. }
  160. return $ret;
  161. }
  162. /**
  163. * Delete a query by qid
  164. *
  165. * In the qbf/<qid>/delete case, $query has been tested for validity and access
  166. * in qbf_query_load(), so it is safe and accessible.
  167. *
  168. * Outside this context, the function can also be invoken with just a qid, and
  169. * the same check via qbf_query_load() will be performed.
  170. *
  171. * @param mixed $query
  172. * int or object
  173. */
  174. function _qbf_query_delete($query)
  175. {
  176. global $user;
  177. if (is_int($query))
  178. {
  179. $query = qbf_query_load($query);
  180. }
  181. if ($query) // access already checked in explicit or implicit qbf_query_load
  182. {
  183. $qid = $query->qid;
  184. $sq = 'DELETE FROM %s WHERE qid = %d ';
  185. $q = db_query($sq, QBF_TABLE_NAME, $qid);
  186. $message = t('Query @id "@name" has been deleted.', array
  187. (
  188. '@id' => $qid,
  189. '@name' => $query->name,
  190. ));
  191. drupal_set_message($message, 'status');
  192. $link = l($qid, QBF_PATH_MAIN .'/'. $qid .'/delete');
  193. $notify = variable_get(QBF_VAR_NOTIFY_DELETE, QBF_DEF_NOTIFY_DELETE);
  194. watchdog('qbf', $message, NULL, WATCHDOG_NOTICE, $link);
  195. // access check: we only send the message to the query owner, so access is
  196. // granted without an additional check
  197. if ($notify /* && $query->uid != $user->uid */)
  198. {
  199. $owner = user_load(array('uid' => $query->uid));
  200. $language = user_preferred_language($account);
  201. $params = array
  202. (
  203. 'query' => $query,
  204. 'owner' => $owner, // unused by default, but can be used in a hook_mail_alter() implementation
  205. 'deletor' => $user,
  206. 'language' => $language,
  207. );
  208. $ret = drupal_mail('qbf', __FUNCTION__, $user->mail, $language, $params, $user->mail);
  209. drupal_set_message(t('User !link has been informed', array
  210. (
  211. '!link' => l($account->name, 'user/'. $query->uid),
  212. )));
  213. // dsm(array("QQD, ret" => $ret));
  214. }
  215. }
  216. else {
  217. $message = t('Failed attempt to delete query @qid. Administrator has been alerted.', array
  218. (
  219. '@qid' => $qid,
  220. ));
  221. drupal_set_message($message, 'error');
  222. watchdog('qbf', $message, NULL, WATCHDOG_ERROR, $link);
  223. }
  224. drupal_goto();
  225. }
  226. /**
  227. * Transform a form element for QBF.
  228. *
  229. * QBF-specific properties are:
  230. * - #qbf : array of properties
  231. * - #level: only within #qbf
  232. *
  233. * See QBF_* constants
  234. *
  235. * @ingroup forms
  236. * @param string $key
  237. * @param array $element
  238. * @return void
  239. */
  240. function _qbf_transform_element($key, $element) {
  241. // dsm(array('key' => $key, 'element' => $element));
  242. /**
  243. * List default type transformations applied to widget by FAPI.
  244. *
  245. * Types without a default transformation are not transformed
  246. */
  247. static $ar_default_type_transformations = array
  248. (
  249. 'button' => NULL, // no content
  250. 'file' => NULL, // non-querable (yet ?)
  251. 'image_button' => NULL, // new in D6
  252. 'markup' => NULL, // no content
  253. 'password' => NULL, // forbidden
  254. 'radio' => NULL, // single radio is useless, unlike a set of them
  255. 'submit' => NULL, // no content
  256. 'textarea' => 'textfield', // reduce text for searches
  257. // Don't transform these:
  258. // 'checkbox' => NULL,
  259. // 'checkboxes' => NULL,
  260. // 'date' => NULL,
  261. // 'fieldset' => NULL, // useful visually
  262. // 'form' => NULL, // removing it would delete the whole shebang
  263. // 'hidden' => NULL, // non-querable visually, but may be useful
  264. // 'item' => NULL,
  265. // 'radios' => NULL,
  266. // 'select' => NULL,
  267. // 'textfield' => NULL,
  268. // 'value' => 'value',
  269. // 'weight' => NULL,
  270. );
  271. /**
  272. * List default property transformations applied to widget by FAPI property.
  273. *
  274. * Properties without a default transformation are not transformed
  275. */
  276. static $ar_default_property_transformations = array
  277. (
  278. // Standard properties
  279. '#action' => NULL,
  280. '#after_build' => NULL,
  281. // '#base' => NULL, // gone in D6
  282. '#button_type' => NULL,
  283. '#built' => NULL,
  284. '#description' => NULL,
  285. '#method' => NULL,
  286. '#parents' => NULL,
  287. '#redirect' => NULL,
  288. '#ref' => NULL,
  289. '#required' => NULL,
  290. '#rows' => NULL,
  291. '#submit' => NULL,
  292. '#tree' => NULL,
  293. '#validate' => NULL,
  294. );
  295. /**
  296. * List properties causing causing element removal.
  297. *
  298. * The key is the property name, the value is the one causing removal.
  299. */
  300. static $ar_killer_properties = array
  301. (
  302. '#disabled' => TRUE,
  303. );
  304. // Transform type
  305. $source_type = $element['#type'];
  306. // .. Default transformation
  307. $dest_type = array_key_exists($source_type, $ar_default_type_transformations)
  308. ? $ar_default_type_transformations[$source_type]
  309. : $source_type;
  310. // .. Apply form-defined type override
  311. if (isset($element['#qbf']['#type']))
  312. {
  313. $dest_type = $element['#qbf']['#type'];
  314. }
  315. if (is_null($dest_type))
  316. {
  317. $ret = NULL;
  318. }
  319. else
  320. {
  321. $ret = $element;
  322. $ret['#type'] = $dest_type;
  323. if (!array_key_exists('#qbf', $element) || $element['#qbf']['#level'] == QBF_LEVEL_REMOVE)
  324. {
  325. $ret = NULL;
  326. }
  327. else
  328. {
  329. foreach (element_properties($element) as $property_name)
  330. {
  331. // Apply killer properties first to avoid useless work
  332. if (array_key_exists($property_name, $ar_killer_properties)
  333. && ($element[$property_name] = $ar_killer_properties[$property_name]))
  334. {
  335. $ret = NULL;
  336. break;
  337. }
  338. // Now transform or copy remaining properties
  339. if (array_key_exists($property_name, $ar_default_property_transformations))
  340. {
  341. $ret[$property_name] = $ar_default_property_transformations[$property_name];
  342. }
  343. else
  344. {
  345. $ret[$property_name] = $element[$property_name];
  346. }
  347. // And apply form-defined property overrides
  348. if ($property_name == '#qbf')
  349. {
  350. foreach ($element[$property_name] as $override_name => $override_value)
  351. {
  352. $ret[$override_name] = $override_value;
  353. }
  354. }
  355. }
  356. // Recursively transform children
  357. foreach (element_children($element) as $child_name)
  358. {
  359. $child = _qbf_transform_element($child_name, $element[$child_name]);
  360. if (is_null($child))
  361. {
  362. unset($ret[$child_name]);
  363. }
  364. else
  365. {
  366. $ret[$child_name] = $child;
  367. }
  368. }
  369. }
  370. }
  371. //dsm(array('key' => $key, 'transformed element' => $ret));
  372. return $ret;
  373. }
  374. /**
  375. * Implement the former hook_settings().
  376. *
  377. * @return array
  378. */
  379. function qbf_admin_settings()
  380. {
  381. $form = array();
  382. $form[QBF_VAR_NOTIFY_DELETE] = array
  383. (
  384. '#type' => 'checkbox',
  385. '#default_value' => variable_get(QBF_VAR_NOTIFY_DELETE, QBF_DEF_NOTIFY_DELETE),
  386. '#title' => t('Notify users when one of their saved searches has been deleted'),
  387. );
  388. return system_settings_form($form);
  389. }
  390. /**
  391. * Submit handler for qbf_form, Save search button.
  392. *
  393. * @param array $form
  394. * @param array $form_state
  395. * @return integer
  396. * The id of the saved query.
  397. */
  398. function qbf_form_save_submit($form, &$form_state)
  399. {
  400. $qid = _qbf_save($form_state['values']['form_id'], $form_state);
  401. drupal_set_message(t('Your query was saved as "@name".',
  402. array('@name' => $form_state['values']['qbf_save_name'])));
  403. global $user;
  404. $form_state['redirect'] = "user/$user->uid/qbf";
  405. return $qid;
  406. }
  407. /**
  408. * Implement hook_forms().
  409. *
  410. * @link http://drupal.org/node/144132#hook-forms @endlink
  411. *
  412. * hook_qbf_register() returns an array of QBF-able node types, indexed by the
  413. * query type, with the following properties:
  414. * - form: the name of the hook_form() implementation (a $form_id)
  415. * - label: the human-readable type name under which the queries are saved by QBF
  416. * - callback: the function QBF must invoke to query the node type. It will
  417. * receive the query type and a filtered version of $form_state['values']
  418. * containing only valid node fields, and must return a themed grid of query
  419. * results, which will be displayed as a #markup FAPI element. In advanced
  420. * uses, a single callback can be used for several query types by using the
  421. * query type parameter to know what the values apply to.
  422. *
  423. * @ingroup forms
  424. * @ingroup hooks
  425. * @param string $form_id
  426. * @param array $args
  427. * @return array
  428. */
  429. function qbf_forms($qbf_form_id, $args)
  430. {
  431. $hook_name = 'qbf_register';
  432. // dsm(array("QBF_forms $qbf_form_id" => $args));
  433. // More efficient than using module_invoke_all: we avoid array-merging + re-looping
  434. foreach (module_implements($hook_name) as $module)
  435. {
  436. $arImplementations = module_invoke($module, $hook_name);
  437. // dsm($arImplementations);
  438. foreach ($arImplementations as $query_type => $query_info)
  439. {
  440. $forms['qbf_' . $query_info['form']] = array
  441. (
  442. 'callback' => 'qbf_form',
  443. 'callback arguments' => array($query_info, $qbf_form_id, $args),
  444. );
  445. }
  446. }
  447. return $forms;
  448. }
  449. /**
  450. * List queries owned by a given user.
  451. *
  452. * @param int $uid > 0
  453. * @return array
  454. */
  455. function qbf_get_queries_by_user($uid = NULL)
  456. {
  457. if (is_null($uid))
  458. {
  459. global $user;
  460. $uid = $user->uid;
  461. }
  462. $sq = 'SELECT qq.qid, qq.uid, qq.name, qq.query, qq.updated '
  463. . 'FROM {%s} qq '
  464. . 'WHERE qq.uid = %d '
  465. . 'ORDER BY qq.name ';
  466. // no db_rewrite_sql: this function is not in a menu callback, so it is up to
  467. // the caller to check access
  468. $q = db_query($sq, QBF_TABLE_NAME, $uid);
  469. $ret = array();
  470. while ($o = db_fetch_object($q))
  471. {
  472. $ret[$o->qid] = $o; // qid is the PK, so it is present and unique
  473. }
  474. return $ret;
  475. }
  476. /**
  477. * Implement hook_menu().
  478. *
  479. * @return array
  480. */
  481. function qbf_menu()
  482. {
  483. $items = array();
  484. $items[QBF_PATH_MAIN . '/demo'] = array
  485. (
  486. 'title' => 'QBF Demo',
  487. 'access arguments' => array(QBF_PERM_QUERY),
  488. 'page callback' => 'qbf_show',
  489. 'type' => MENU_NORMAL_ITEM,
  490. );
  491. $items[QBF_PATH_SETTINGS] = array
  492. (
  493. 'title' => 'Query-By-Form',
  494. 'access arguments' => array(QBF_PERM_ADMIN),
  495. 'page callback' => 'drupal_get_form',
  496. 'page arguments' => array('qbf_admin_settings'),
  497. 'type' => MENU_NORMAL_ITEM,
  498. );
  499. $items[QBF_PATH_MAIN . '/%qbf_query/delete'] = array
  500. (
  501. 'type' => MENU_CALLBACK,
  502. 'access arguments' => array(QBF_PERM_QUERY),
  503. 'page callback' => '_qbf_query_delete',
  504. 'page arguments' => array(1),
  505. );
  506. return $items;
  507. }
  508. /**
  509. * Implement hook_mail().
  510. *
  511. * @param string $key
  512. * @param array $message
  513. * @param array $params
  514. * @return void
  515. */
  516. function qbf_mail($key, &$message, $params)
  517. {
  518. // dsm(array('QBF_mail key' => $key, 'message' => $message, 'params' => $params));
  519. $deletor_tokens = user_mail_tokens($params['deletor'], $params['language']->language);
  520. $tokens = array_merge($deletor_tokens, array
  521. (
  522. '!qname' => $params['query']->name,
  523. '!qid' => $params['query']->qid,
  524. ));
  525. $message['subject'] = t('Effacement d\'une recherche !site enregistrée', $tokens);
  526. $message['body'] = t("!date\n\nVotre recherche !qid: !qname\nsur le site !site vient d'être effacée par !username.", $tokens);
  527. }
  528. /**
  529. * Implement hook_perm().
  530. *
  531. * @todo D7: Format will change
  532. * @see http://drupal.org/node/224333#descriptions-permissions
  533. *
  534. * @ingroup hooks
  535. * @return array
  536. */
  537. function qbf_perm()
  538. {
  539. $ret = array
  540. (
  541. QBF_PERM_ADMIN,
  542. QBF_PERM_QUERY,
  543. );
  544. return $ret;
  545. }
  546. /**
  547. * Load a saved QBF query.
  548. *
  549. * @see qbf_import_values()
  550. * @link http://drupal.org/node/109153#load @endlink
  551. *
  552. * @param int $qid
  553. * @return array A form_values array usable by qbf_import_values
  554. */
  555. function qbf_query_load($qid)
  556. {
  557. static $query = NULL;
  558. if (is_null($query))
  559. {
  560. $sq = 'SELECT qq.qid, qq.uid, qq.query, qq.name '
  561. . 'FROM {%s} qq '
  562. . 'WHERE qq.qid = %d ';
  563. // db_rewrite_sql does not apply here: access control is further down
  564. $q = db_query($sq, QBF_TABLE_NAME, $qid);
  565. $query = db_fetch_object($q); // 0 or 1 row: we are querying on the primary key
  566. // FALSE does not happen: only NULL or a value can be here
  567. if ($query !== NULL)
  568. {
  569. $query->query = unserialize($query->query);
  570. //dsm($query);
  571. }
  572. }
  573. global $user;
  574. $ret = (isset($query) && isset($query->uid) && (($query->uid == $user->uid) || user_access(QBF_PERM_ADMIN)))
  575. ? $query
  576. : FALSE;
  577. return $ret;
  578. }
  579. /**
  580. * Provide an optional automatic mapping mechanism for query building.
  581. *
  582. * This function takes a partly built query map $ar_queryMap, and a defaults
  583. * array to complete it in $ar_defaults, and returns a fully built query array
  584. * ready to be used for querying.
  585. *
  586. * @param array $ar_query_map
  587. * @param array $ar_defaults
  588. * @return array
  589. */
  590. function qbf_query_mapper($ar_query_map = array(), $ar_defaults = array())
  591. {
  592. $ret = array();
  593. foreach ($ar_query_map as $name => $value)
  594. {
  595. // accept NULL, empty strings...
  596. if (!is_array($value))
  597. {
  598. $value = array();
  599. }
  600. $item = $value;
  601. foreach ($ar_defaults as $default_key => $default_value)
  602. {
  603. if (!array_key_exists($default_key, $item))
  604. {
  605. $item[$default_key] = is_null($default_value)
  606. ? $name
  607. : $default_value;
  608. }
  609. // else if is already in $item, so we don't touch it
  610. }
  611. $ret[$name] = $item;
  612. }
  613. return $ret;
  614. }
  615. error_reporting($_qbf_er);
  616. function qbf___________________________________________________(){}
  617. // ======== D6 LIMIT ==================================================================================================
  618. /* TODO Node previews and adding form fields to the node form.
  619. There is a subtle but important difference in the way node previews (and other
  620. such operations) are carried out when adding or editing a node. With the new
  621. Forms API, the node form is handled as a multi-step form. When the node form
  622. is previewed, all the form values are submitted, and the form is rebuilt with
  623. those form values put into $form['#node']. Thus, form elements that are added
  624. to the node form will lose any user input unless they set their '#default_value'
  625. elements using this embedded node object. */
  626. /**
  627. * Transform a form array for QBF.
  628. *
  629. * This function obtains the form array from the hook_form() implementation, and
  630. * transforms it by modifying widgets to other types where needed.
  631. *
  632. * Any additional parameter passed to the function is transmitted to the
  633. * hook_form() implementation.
  634. *
  635. * @ingroup forms
  636. * @param string $form_id
  637. * @param array $form_state
  638. * @return array
  639. */
  640. function qbf_transform_form($form_state, $form_id)
  641. {
  642. // Fetch the basic form and rename it, passing it the caller's arguments
  643. $form = drupal_retrieve_form($form_id, $form_state, NULL, $form_state);
  644. $node = new stdClass();
  645. $form = $form_id($node, $form_state);
  646. $new_form_id = "qbf_$form_id";
  647. // Only keep the children of the form and QBF properties on the form itself
  648. $elements = array();
  649. $new_form = array();
  650. $new_form['#qbf_source_form_id'] = $form_id;
  651. if (in_array('#qbf', element_properties($form)))
  652. {
  653. $new_form += $form['#qbf'];
  654. }
  655. foreach (element_children($form) as $key)
  656. {
  657. // dsm("Transforming $key, type " . $form[$key]['#type']);
  658. $new_element = _qbf_transform_element($key, $form[$key]);
  659. if (!is_null($new_element))
  660. {
  661. $new_form[$key] = $new_element;
  662. }
  663. }
  664. $new_form['#id'] = $new_form_id;
  665. // @todo #multistep -> #rebuild au submit
  666. // $new_form['#multistep'] = TRUE;
  667. // Do not set #redirect, even to FALSE (submit handlers)
  668. // $new_form['#redirect'] = FALSE;
  669. $new_form['#after_build'][] = 'qbf_after_build';
  670. $new_form['#submit'] = array('qbf_submit');
  671. // dsm($new_form);
  672. return $new_form;
  673. }
  674. /**
  675. * Insert the query results at the bottom of the query form.
  676. *
  677. * @ingroup forms
  678. * @param array $form
  679. * @param array $form_values
  680. * @return array
  681. */
  682. function qbf_after_build($form, $form_values) {
  683. if (empty($form['#post'])) {
  684. return $form;
  685. }
  686. // If #post is not empty, we are indeed querying
  687. $ar_query = _qbf_extract_query($form, $form_values);
  688. /* This function is called at the end of the form building process, which
  689. * means that child properties of #qbf have already been upgraded to element
  690. * properties. So we look for $form['#callback'] and not
  691. * $form['#qbf']['#callback']
  692. */
  693. if (isset($form['#callback']) && function_exists($function = $form['#callback'])) {
  694. $results = $function($ar_query);
  695. }
  696. else {
  697. drupal_set_message(t('QBF: incorrect callback function for search'), 'error');
  698. }
  699. $form['qbf_query_results'] = array
  700. (
  701. '#type' => 'markup',
  702. '#value' => $results,
  703. '#weight' => 10,
  704. );
  705. return $form;
  706. }
  707. /**
  708. * Load a form_values array into a form used by QBF.
  709. *
  710. * This is typically useful when loading saved queries using qbf_query_load().
  711. * For other cases, the mechanisms built within FAPI should be used instead.
  712. *
  713. * @see qbf_query_load()
  714. *
  715. * @ingroup forms
  716. * @param array $form
  717. * @param array $form_values
  718. * @return array The modified form
  719. */
  720. function qbf_import_values($element, $form_values) {
  721. foreach (element_children($element) as $child_name) {
  722. if (!empty($form_values[$child_name])) {
  723. $element[$child_name]['#qbf']['#default_value'] = $form_values[$child_name];
  724. }
  725. $element[$child_name] = qbf_import_values($element[$child_name], $form_values);
  726. }
  727. return $element;
  728. }
  729. /**
  730. * Save a query and return its qid.
  731. *
  732. * @ingroup forms
  733. *
  734. * @param $form_id string
  735. * @param $form_state array
  736. * @return int
  737. */
  738. function _qbf_save($form_id, $form_state)
  739. {
  740. if (user_is_anonymous())
  741. {
  742. $warning = t('Attempt by anonymous user to save a QBF query. Should not happen.');
  743. drupal_set_message($warning, 'error');
  744. watchdog('qbf', $warning, NULL, WATCHDOG_WARNING);
  745. $ret = 0;
  746. }
  747. else
  748. {
  749. // @FIXME check whether form_state is now needed. It wasn't in QBF for D5
  750. $form = drupal_retrieve_form($form_id, $form_state);
  751. // dsm($form, "retrieve");
  752. drupal_prepare_form($form_id, $form, $form_state);
  753. // dsm($form, "prepare");
  754. $name = $form_state['values']['qbf_save_name'];
  755. $type = $form_state['values']['qbf_save_type'];
  756. // dsm($form_state);
  757. $form_values = _qbf_extract_query(NULL, $form, $form_state['values']);
  758. // dsm($form_values);
  759. $ar_values = array();
  760. foreach ($form_values as $key => $value)
  761. {
  762. if (empty($value))
  763. {
  764. continue;
  765. }
  766. $ar_values[$key] = $value;
  767. }
  768. $query = new Qbf_Query($type, $name, $ar_values);
  769. $ret = $query->save();
  770. }
  771. return $ret;
  772. }
  773. /**
  774. * The QBF form builder.
  775. *
  776. * @param array $form_state
  777. * @param string $form_id
  778. * The original form to transform
  779. * @param string $qbf_form_id
  780. * The QBF form itself
  781. * @param strign $save_type
  782. * Name of search type, to use when saving.
  783. */
  784. function qbf_form($form_state, $query_info, $qbf_form_id)
  785. {
  786. $form_id = $query_info['form'];
  787. // dsm(array("QBF_Form" => "Base = [$form_id], QBF ID = [$qbf_form_id]", 'save_type' => $save_type));
  788. // dsm($form_state);
  789. // Fetch the basic form and rename it, passing it the previous values
  790. $node = new stdClass();
  791. $form = $form_id($node, $form_state);
  792. $qbf_form = array();
  793. $qbf_form['#qbf_source_form_id'] = $form_id;
  794. // On the form element itselfn only keep the QBF properties and the children
  795. if (in_array('#qbf', element_properties($form)))
  796. {
  797. $qbf_form += $form['#qbf'];
  798. }
  799. foreach (element_children($form) as $key)
  800. {
  801. // dsm("Transforming $key, type " . $form[$key]['#type']);
  802. $new_element = _qbf_transform_element($key, $form[$key], $form_state);
  803. if (!is_null($new_element))
  804. {
  805. $qbf_form[$key] = $new_element;
  806. }
  807. }
  808. $qbf_form['#id'] = $qbf_form_id;
  809. // $qbf_form['#after_build'][] = 'qbf_after_build';
  810. // dsm($qbf_form);
  811. $qbf_form['qbf'] = array
  812. (
  813. '#type' => 'fieldset',
  814. '#title' => t('Query'),
  815. );
  816. if (isset($form_state['values']) && !empty($form_state['values']))
  817. {
  818. // dsm(array("QBF form: we must restore these values" => $form_state));
  819. if (isset($form_state['qbf_results']))
  820. {
  821. $qbf_form['qbf']['qbf_results'] = array
  822. (
  823. '#type' => 'markup',
  824. '#prefix' => '<p>',
  825. '#value' => $form_state['qbf_results'],
  826. '#suffix' => '</p>',
  827. );
  828. }
  829. }
  830. $qbf_form['qbf']['qbf_save_type'] = array
  831. (
  832. '#type' => 'hidden',
  833. '#value' => $query_info['label'],
  834. );
  835. $qbf_form['qbf']['qbf_query'] = array
  836. (
  837. '#type' => 'hidden',
  838. '#value' => $query_info['callback'],
  839. );
  840. $qbf_form['qbf']['qbf_save_name'] = array
  841. (
  842. '#title' => t('Name of query in your save list'),
  843. '#type' => 'textfield',
  844. '#required' => TRUE,
  845. '#default_value' => substr($form_id, 0, -5) . ' ' . format_date(time(), 'large'),
  846. );
  847. $qbf_form['qbf']['qbf_save'] = array
  848. (
  849. '#submit' => array('qbf_form_save_submit'),
  850. '#validate' => array('qbf_form_save_validate'),
  851. '#type' => 'submit',
  852. '#value' => t('Save query'),
  853. '#weight' => 5,
  854. );
  855. $qbf_form['qbf']['qbf_perform'] = array
  856. (
  857. '#submit' => array('qbf_form_perform_submit'),
  858. // '#validate' => array('qbf_form_perform_validate'),
  859. '#type' => 'submit',
  860. '#value' => t('Perform query'),
  861. '#weight' => 4,
  862. );
  863. return $qbf_form;
  864. }
  865. /**
  866. * Submit handler for qbf_form, Perform search button.
  867. *
  868. * @param array $form
  869. * @param array $form_state
  870. */
  871. function qbf_form_perform_submit($form, &$form_state)
  872. {
  873. // dsm('PERF SUB');
  874. //dsm($form);
  875. // dsm($form_state);
  876. $callback = $form_state['values']['qbf_query'];
  877. if (function_exists(($callback)))
  878. {
  879. $ar_query = _qbf_extract_query(NULL, $form, $form_state['values']);
  880. $form_state['qbf_results'] = $callback($ar_query);
  881. }
  882. $form_state['rebuild'] = TRUE;
  883. }