qbf.module 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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.7 2009-03-21 19:41:34 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, $form_state, $query)
  241. {
  242. // dsm(array('key' => $key, 'element' => $element));
  243. /**
  244. * List default type transformations applied to widget by FAPI.
  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. if (isset($form_state['values'][$key]))
  357. {
  358. $ret['#default_value'] = $form_state['values'][$key];
  359. }
  360. elseif (isset($query->query[$key]))
  361. {
  362. $ret['#default_value'] = $query->query[$key];
  363. }
  364. // Recursively transform children
  365. foreach (element_children($element) as $child_name)
  366. {
  367. $child = _qbf_transform_element($child_name, $element[$child_name], $form_state, $query);
  368. if (is_null($child))
  369. {
  370. unset($ret[$child_name]);
  371. }
  372. else
  373. {
  374. $ret[$child_name] = $child;
  375. }
  376. }
  377. }
  378. }
  379. //dsm(array('key' => $key, 'transformed element' => $ret));
  380. return $ret;
  381. }
  382. /**
  383. * Implement the former hook_settings().
  384. *
  385. * @return array
  386. */
  387. function qbf_admin_settings()
  388. {
  389. $form = array();
  390. $form[QBF_VAR_NOTIFY_DELETE] = array
  391. (
  392. '#type' => 'checkbox',
  393. '#default_value' => variable_get(QBF_VAR_NOTIFY_DELETE, QBF_DEF_NOTIFY_DELETE),
  394. '#title' => t('Notify users when one of their saved searches has been deleted'),
  395. );
  396. return system_settings_form($form);
  397. }
  398. /**
  399. * Submit handler for qbf_form, Save search button.
  400. *
  401. * @param array $form
  402. * @param array $form_state
  403. * @return integer
  404. * The id of the saved query.
  405. */
  406. function qbf_form_save_submit($form, &$form_state)
  407. {
  408. $qid = _qbf_save($form_state['values']['form_id'], $form_state);
  409. drupal_set_message(t('Your query was saved as "@name".',
  410. array('@name' => $form_state['values']['qbf_save_name'])));
  411. global $user;
  412. $form_state['redirect'] = "user/$user->uid/qbf";
  413. return $qid;
  414. }
  415. /**
  416. * Implement hook_forms().
  417. *
  418. * @link http://drupal.org/node/144132#hook-forms @endlink
  419. *
  420. * hook_qbf_register() returns an array of QBF-able node types, indexed by the
  421. * query type, with the following properties:
  422. * - form: the name of the hook_form() implementation (a $form_id)
  423. * - label: the human-readable type name under which the queries are saved by QBF
  424. * - callback: the function QBF must invoke to query the node type. It will
  425. * receive the query type and a filtered version of $form_state['values']
  426. * containing only valid node fields, and must return a themed grid of query
  427. * results, which will be displayed as a #markup FAPI element. In advanced
  428. * uses, a single callback can be used for several query types by using the
  429. * query type parameter to know what the values apply to.
  430. *
  431. * @ingroup forms
  432. * @ingroup hooks
  433. * @param string $form_id
  434. * @param array $args
  435. * @return array
  436. */
  437. function qbf_forms($qbf_form_id, $args)
  438. {
  439. $hook_name = 'qbf_register';
  440. // dsm(array("QBF_forms $qbf_form_id" => $args));
  441. // More efficient than using module_invoke_all: we avoid array-merging + re-looping
  442. foreach (module_implements($hook_name) as $module)
  443. {
  444. $arImplementations = module_invoke($module, $hook_name);
  445. // dsm($arImplementations);
  446. foreach ($arImplementations as $query_type => $query_info)
  447. {
  448. $forms['qbf_' . $query_info['form']] = array
  449. (
  450. 'callback' => 'qbf_form',
  451. 'callback arguments' => array($query_info, $qbf_form_id),
  452. );
  453. }
  454. }
  455. return $forms;
  456. }
  457. /**
  458. * List queries owned by a given user.
  459. *
  460. * @param int $uid > 0
  461. * @return array
  462. */
  463. function qbf_get_queries_by_user($uid = NULL)
  464. {
  465. if (is_null($uid))
  466. {
  467. global $user;
  468. $uid = $user->uid;
  469. }
  470. $sq = 'SELECT qq.qid, qq.uid, qq.name, qq.query, qq.updated '
  471. . 'FROM {%s} qq '
  472. . 'WHERE qq.uid = %d '
  473. . 'ORDER BY qq.name ';
  474. // no db_rewrite_sql: this function is not in a menu callback, so it is up to
  475. // the caller to check access
  476. $q = db_query($sq, QBF_TABLE_NAME, $uid);
  477. $ret = array();
  478. while ($o = db_fetch_object($q))
  479. {
  480. $ret[$o->qid] = $o; // qid is the PK, so it is present and unique
  481. }
  482. return $ret;
  483. }
  484. /**
  485. * Implement hook_menu().
  486. *
  487. * @return array
  488. */
  489. function qbf_menu()
  490. {
  491. $items = array();
  492. $items[QBF_PATH_MAIN . '/demo'] = array
  493. (
  494. 'title' => 'QBF Demo',
  495. 'access arguments' => array(QBF_PERM_QUERY),
  496. 'page callback' => 'qbf_show',
  497. 'type' => MENU_NORMAL_ITEM,
  498. );
  499. $items[QBF_PATH_SETTINGS] = array
  500. (
  501. 'title' => 'Query-By-Form',
  502. 'access arguments' => array(QBF_PERM_ADMIN),
  503. 'page callback' => 'drupal_get_form',
  504. 'page arguments' => array('qbf_admin_settings'),
  505. 'type' => MENU_NORMAL_ITEM,
  506. );
  507. $items[QBF_PATH_MAIN . '/%qbf_query'] = array
  508. (
  509. 'type' => MENU_CALLBACK,
  510. 'access arguments' => array(QBF_PERM_QUERY),
  511. 'page callback' => 'qbf_query_form',
  512. 'page arguments' => array(1),
  513. );
  514. $items[QBF_PATH_MAIN . '/%qbf_query/delete'] = array
  515. (
  516. 'type' => MENU_CALLBACK,
  517. 'access arguments' => array(QBF_PERM_QUERY),
  518. 'page callback' => '_qbf_query_delete',
  519. 'page arguments' => array(1),
  520. );
  521. return $items;
  522. }
  523. /**
  524. * Implement hook_mail().
  525. *
  526. * @param string $key
  527. * @param array $message
  528. * @param array $params
  529. * @return void
  530. */
  531. function qbf_mail($key, &$message, $params)
  532. {
  533. // dsm(array('QBF_mail key' => $key, 'message' => $message, 'params' => $params));
  534. $deletor_tokens = user_mail_tokens($params['deletor'], $params['language']->language);
  535. $tokens = array_merge($deletor_tokens, array
  536. (
  537. '!qname' => $params['query']->name,
  538. '!qid' => $params['query']->qid,
  539. ));
  540. $message['subject'] = t('Effacement d\'une recherche !site enregistrée', $tokens);
  541. $message['body'] = t("!date\n\nVotre recherche !qid: !qname\nsur le site !site vient d'être effacée par !username.", $tokens);
  542. }
  543. /**
  544. * Implement hook_perm().
  545. *
  546. * @todo D7: Format will change
  547. * @see http://drupal.org/node/224333#descriptions-permissions
  548. *
  549. * @ingroup hooks
  550. * @return array
  551. */
  552. function qbf_perm()
  553. {
  554. $ret = array
  555. (
  556. QBF_PERM_ADMIN,
  557. QBF_PERM_QUERY,
  558. );
  559. return $ret;
  560. }
  561. /**
  562. * Load a saved QBF query.
  563. *
  564. * @see qbf_import_values()
  565. * @link http://drupal.org/node/109153#load @endlink
  566. *
  567. * @param int $us_qid
  568. * @return array
  569. * A form_values array
  570. */
  571. function qbf_query_load($us_qid)
  572. {
  573. static $query = NULL;
  574. // Only allow query loading by logged-in users
  575. if (user_is_anonymous())
  576. {
  577. return FALSE;
  578. }
  579. // Filter out visibly invalid values
  580. $qid = (is_numeric($us_qid) && ($us_qid > 0))
  581. ? $us_qid
  582. : 0;
  583. if (is_null($query))
  584. {
  585. $sq = 'SELECT qq.qid, qq.uid, qq.type, qq.name, qq.query '
  586. . 'FROM {%s} qq '
  587. . 'WHERE qq.qid = %d ';
  588. // db_rewrite_sql does not apply here: access control is further down
  589. $q = db_query($sq, QBF_TABLE_NAME, $qid);
  590. $query = db_fetch_object($q); // 0 or 1 row: we are querying on the primary key
  591. // FALSE does not happen: only NULL or a value can be here
  592. if ($query !== NULL)
  593. {
  594. $query->query = unserialize($query->query);
  595. // dsm($query);
  596. }
  597. }
  598. global $user;
  599. $ret = (isset($query) && (($query->uid == $user->uid) || user_access(QBF_PERM_ADMIN)))
  600. ? $query
  601. : FALSE;
  602. return $ret;
  603. }
  604. /**
  605. * Provide an optional automatic mapping mechanism for query building.
  606. *
  607. * This function takes a partly built query map $ar_queryMap, and a defaults
  608. * array to complete it in $ar_defaults, and returns a fully built query array
  609. * ready to be used for querying.
  610. *
  611. * @param array $ar_query_map
  612. * @param array $ar_defaults
  613. * @return array
  614. */
  615. function qbf_query_mapper($ar_query_map = array(), $ar_defaults = array())
  616. {
  617. $ret = array();
  618. foreach ($ar_query_map as $name => $value)
  619. {
  620. // accept NULL, empty strings...
  621. if (!is_array($value))
  622. {
  623. $value = array();
  624. }
  625. $item = $value;
  626. foreach ($ar_defaults as $default_key => $default_value)
  627. {
  628. if (!array_key_exists($default_key, $item))
  629. {
  630. $item[$default_key] = is_null($default_value)
  631. ? $name
  632. : $default_value;
  633. }
  634. // else if is already in $item, so we don't touch it
  635. }
  636. $ret[$name] = $item;
  637. }
  638. return $ret;
  639. }
  640. error_reporting($_qbf_er);
  641. function qbf___________________________________________________(){}
  642. // ======== D6 LIMIT ==================================================================================================
  643. /* TODO Node previews and adding form fields to the node form.
  644. There is a subtle but important difference in the way node previews (and other
  645. such operations) are carried out when adding or editing a node. With the new
  646. Forms API, the node form is handled as a multi-step form. When the node form
  647. is previewed, all the form values are submitted, and the form is rebuilt with
  648. those form values put into $form['#node']. Thus, form elements that are added
  649. to the node form will lose any user input unless they set their '#default_value'
  650. elements using this embedded node object. */
  651. /**
  652. * Transform a form array for QBF.
  653. *
  654. * This function obtains the form array from the hook_form() implementation, and
  655. * transforms it by modifying widgets to other types where needed.
  656. *
  657. * Any additional parameter passed to the function is transmitted to the
  658. * hook_form() implementation.
  659. *
  660. * @ingroup forms
  661. * @param string $form_id
  662. * @param array $form_state
  663. * @return array
  664. */
  665. function qbf_transform_form($form_state, $form_id)
  666. {
  667. // Fetch the basic form and rename it, passing it the caller's arguments
  668. $form = drupal_retrieve_form($form_id, $form_state, NULL, $form_state);
  669. $node = new stdClass();
  670. $form = $form_id($node, $form_state);
  671. $new_form_id = "qbf_$form_id";
  672. // Only keep the children of the form and QBF properties on the form itself
  673. $elements = array();
  674. $new_form = array();
  675. $new_form['#qbf_source_form_id'] = $form_id;
  676. if (in_array('#qbf', element_properties($form)))
  677. {
  678. $new_form += $form['#qbf'];
  679. }
  680. foreach (element_children($form) as $key)
  681. {
  682. // dsm("Transforming $key, type " . $form[$key]['#type']);
  683. $new_element = _qbf_transform_element($key, $form[$key]);
  684. if (!is_null($new_element))
  685. {
  686. $new_form[$key] = $new_element;
  687. }
  688. }
  689. $new_form['#id'] = $new_form_id;
  690. // @todo #multistep -> #rebuild au submit
  691. // $new_form['#multistep'] = TRUE;
  692. // Do not set #redirect, even to FALSE (submit handlers)
  693. // $new_form['#redirect'] = FALSE;
  694. $new_form['#after_build'][] = 'qbf_after_build';
  695. $new_form['#submit'] = array('qbf_submit');
  696. // dsm($new_form);
  697. return $new_form;
  698. }
  699. /**
  700. * Insert the query results at the bottom of the query form.
  701. *
  702. * @ingroup forms
  703. * @param array $form
  704. * @param array $form_values
  705. * @return array
  706. */
  707. function qbf_after_build($form, $form_values) {
  708. if (empty($form['#post'])) {
  709. return $form;
  710. }
  711. // If #post is not empty, we are indeed querying
  712. $ar_query = _qbf_extract_query($form, $form_values);
  713. /* This function is called at the end of the form building process, which
  714. * means that child properties of #qbf have already been upgraded to element
  715. * properties. So we look for $form['#callback'] and not
  716. * $form['#qbf']['#callback']
  717. */
  718. if (isset($form['#callback']) && function_exists($function = $form['#callback'])) {
  719. $results = $function($ar_query);
  720. }
  721. else {
  722. drupal_set_message(t('QBF: incorrect callback function for search'), 'error');
  723. }
  724. $form['qbf_query_results'] = array
  725. (
  726. '#type' => 'markup',
  727. '#value' => $results,
  728. '#weight' => 10,
  729. );
  730. return $form;
  731. }
  732. /**
  733. * Load a form_values array into a form used by QBF.
  734. *
  735. * This is typically useful when loading saved queries using qbf_query_load().
  736. * For other cases, the mechanisms built within FAPI should be used instead.
  737. *
  738. * @see qbf_query_load()
  739. *
  740. * @ingroup forms
  741. * @param array $form
  742. * @param array $form_values
  743. * @return array The modified form
  744. */
  745. function qbf_import_values($element, $form_values) {
  746. foreach (element_children($element) as $child_name) {
  747. if (!empty($form_values[$child_name])) {
  748. $element[$child_name]['#qbf']['#default_value'] = $form_values[$child_name];
  749. }
  750. $element[$child_name] = qbf_import_values($element[$child_name], $form_values);
  751. }
  752. return $element;
  753. }
  754. /**
  755. * Save a query and return its qid.
  756. *
  757. * @ingroup forms
  758. *
  759. * @param $form_id string
  760. * @param $form_state array
  761. * @return int
  762. */
  763. function _qbf_save($form_id, $form_state)
  764. {
  765. if (user_is_anonymous())
  766. {
  767. $warning = t('Attempt by anonymous user to save a QBF query. Should not happen.');
  768. drupal_set_message($warning, 'error');
  769. watchdog('qbf', $warning, NULL, WATCHDOG_WARNING);
  770. $ret = 0;
  771. }
  772. else
  773. {
  774. // @FIXME check whether form_state is now needed. It wasn't in QBF for D5
  775. $form = drupal_retrieve_form($form_id, $form_state);
  776. // dsm($form, "retrieve");
  777. drupal_prepare_form($form_id, $form, $form_state);
  778. // dsm($form, "prepare");
  779. $name = $form_state['values']['qbf_save_name'];
  780. $type = $form_state['values']['qbf_save_type'];
  781. // dsm($form_state);
  782. $form_values = _qbf_extract_query(NULL, $form, $form_state['values']);
  783. // dsm($form_values);
  784. $ar_values = array();
  785. foreach ($form_values as $key => $value)
  786. {
  787. if (empty($value))
  788. {
  789. continue;
  790. }
  791. $ar_values[$key] = $value;
  792. }
  793. $query = new Qbf_Query($type, $name, $ar_values);
  794. $ret = $query->save();
  795. }
  796. return $ret;
  797. }
  798. /**
  799. * The QBF form builder.
  800. *
  801. * @param array $form_state
  802. * @param array $query_info
  803. * The query structure array
  804. * @param string $qbf_form_id
  805. * The name of the QBF form
  806. * @param string $query
  807. * The saved query.
  808. */
  809. function qbf_form(&$form_state, $query_info, $qbf_form_id, $query = NULL)
  810. {
  811. $form_id = $query_info['form'];
  812. dsm(array("QBF_Form" => "Base = [$form_id], QBF ID = [$qbf_form_id]", 'query' => $query));
  813. dsm($form_state);
  814. // Fetch the basic form and rename it, passing it the previous values
  815. $node = new stdClass();
  816. $form = $form_id($node, $form_state);
  817. $qbf_form = array();
  818. $qbf_form['#qbf_source_form_id'] = $form_id;
  819. // On the form element itself, only keep the QBF properties and the children
  820. if (in_array('#qbf', element_properties($form)))
  821. {
  822. $qbf_form += $form['#qbf'];
  823. }
  824. foreach (element_children($form) as $key)
  825. {
  826. $new_element = _qbf_transform_element($key, $form[$key], $form_state, $query);
  827. if (!is_null($new_element))
  828. {
  829. $qbf_form[$key] = $new_element;
  830. }
  831. }
  832. $qbf_form['#id'] = $qbf_form_id;
  833. // $qbf_form['#after_build'][] = 'qbf_after_build';
  834. // dsm($qbf_form);
  835. $qbf_form['qbf'] = array
  836. (
  837. '#type' => 'fieldset',
  838. '#title' => t('Query'),
  839. );
  840. if (isset($form_state['values']) && !empty($form_state['values']))
  841. {
  842. // dsm(array("QBF form: we must restore these values" => $form_state));
  843. if (isset($form_state['qbf_results']))
  844. {
  845. $qbf_form['qbf']['qbf_results'] = array
  846. (
  847. '#type' => 'markup',
  848. '#prefix' => '<p>',
  849. '#value' => $form_state['qbf_results'],
  850. '#suffix' => '</p>',
  851. );
  852. }
  853. }
  854. $qbf_form['qbf']['qbf_save_type'] = array
  855. (
  856. '#type' => 'hidden',
  857. '#value' => $query_info['form'],
  858. );
  859. $qbf_form['qbf']['qbf_query'] = array
  860. (
  861. '#type' => 'hidden',
  862. '#value' => $query_info['callback'],
  863. );
  864. $qbf_form['qbf']['qbf_save_name'] = array
  865. (
  866. '#title' => t('Name of query in your save list'),
  867. '#type' => 'textfield',
  868. '#required' => TRUE,
  869. '#default_value' => empty($query->name)
  870. ? substr($form_id, 0, -5) . ' ' . format_date(time(), 'large')
  871. : $query->name,
  872. );
  873. $qbf_form['qbf']['qbf_save'] = array
  874. (
  875. '#submit' => array('qbf_form_save_submit'),
  876. '#validate' => array('qbf_form_save_validate'),
  877. '#type' => 'submit',
  878. '#value' => t('Save query'),
  879. '#weight' => 5,
  880. );
  881. $qbf_form['qbf']['qbf_perform'] = array
  882. (
  883. '#submit' => array('qbf_form_perform_submit'),
  884. // '#validate' => array('qbf_form_perform_validate'),
  885. '#type' => 'submit',
  886. '#value' => t('Perform query'),
  887. '#weight' => 4,
  888. );
  889. return $qbf_form;
  890. }
  891. /**
  892. * Submit handler for qbf_form, Perform search button.
  893. *
  894. * @param array $form
  895. * @param array $form_state
  896. */
  897. function qbf_form_perform_submit($form, &$form_state)
  898. {
  899. // dsm('PERF SUB');
  900. //dsm($form);
  901. // dsm($form_state);
  902. $callback = $form_state['values']['qbf_query'];
  903. if (function_exists(($callback)))
  904. {
  905. $ar_query = _qbf_extract_query(NULL, $form, $form_state['values']);
  906. $form_state['qbf_results'] = $callback($ar_query);
  907. }
  908. $form_state['rebuild'] = TRUE;
  909. }
  910. function qbf_query_form($query)
  911. {
  912. $qbf_form_id = 'qbf_' . $query->type;
  913. $form = drupal_get_form($qbf_form_id, $query);
  914. return $form;
  915. }