qbf.module 29 KB

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