qbf.module 30 KB

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