Assume external script for ^http and alias for ^/
[mkdru-moved-to-drupal.org.git] / mkdru.module
1 <?php
2 // $Id$
3
4
5
6 // Module metainfo
7 /**
8 * Implements hook_node_info()
9 */
10 function mkdru_node_info() {
11   return array(
12     'mkdru' => array(
13       'name' => t("Pazpar2 metasearch interface"),
14       'module' => 'mkdru',
15       'description' => t("Metasearch interface for Z39.50/SRU and other targets via a Pazpar2/Service Proxy backend"),
16     )
17   );
18 }
19
20 function mkdru_ting_search_tab($keys) {
21   error_log("TING SEARCH TAB invoked");
22    $path = drupal_get_path('module', 'mkdru');
23   // Include client library.
24   // D6 seems not to be able to handle external scripts
25   // assume one if path starts with http:
26   // assume alias if path starts with /
27   if (preg_match('/^http:/') || preg_match('/^\//') {
28      drupal_add_js(variable_get('pz2_js_path', 'pazpar2/js') 
29       . '/pz2.js', 'module', 'footer', TRUE, TRUE, FALSE);  
30   } else {
31     drupal_add_js($path.'/'.variable_get('pz2_js_path', 'pazpar2/js') 
32       . '/pz2.js', 'module', 'footer');
33   }
34   drupal_add_js($path . '/jquery.ba-bbq.js', 'module', 'footer');
35   drupal_add_js($path . '/recipe.js', 'module', 'footer');
36   drupal_add_js($path . '/mkdru.theme.js', 'module', 'footer');
37   drupal_add_js($path . '/mkdru.client.js', 'module', 'footer');
38   $html = theme('mkdru_results');
39   drupal_add_js(array('mkdru' => 
40     array(
41       'settings' => json_encode(variable_get('mkdru_ding', NULL)),
42       'pz2_path' => variable_get('pz2_path', '/pazpar2/search.pz2'),
43       'query' => $keys
44     )
45   ), 'setting');
46   return array("content" => $html, "title" => "Meta Search");
47 }
48
49 /**
50 * Implements hook_perm()
51 */
52 function mkdru_perm() {
53   return array('create metasearch interface', 'edit any metasearch interface', 'edit own metasearch interface');
54 }
55
56 /**
57 * Implements hook_access()
58 */
59 function mkdru_access($op, $node, $account) {
60
61   if ($op == 'create') {
62     // Only users with permission to do so may create this node type.
63     return user_access('create metasearch interface', $account);
64   }
65
66   // Users who create a node may edit or delete it later, assuming they have the
67   // necessary permissions.
68   if ($op == 'update' || $op == 'delete') {
69     if (user_access('edit own metasearch interface', $account) && ($account->uid == $node->uid)) {
70       return TRUE;
71     }
72     elseif (user_access('edit any metasearch interface', $account)) {
73       return TRUE;
74     }
75   }
76 }
77
78 /**
79 * Implements hook_menu()
80 */
81 function mkdru_menu() {
82   // Can't get tabbed menus to work in D6. The children work and the tabs
83   // show up there but the top level's url results in it trying to find
84   // the system module's system.inc in mkdru's directory
85 //   $items['admin/settings/mkdru'] = array(
86 //     'title' => 'Pazpar2 Metasearch Settings',
87 //     'description' => 'Settings for mkdru.',
88 //     'access arguments' => array('administer site configuration'),
89 //   );
90 //   $items['admin/settings/mkdru/settings'] = array(
91 //     'title' => 'Settings',
92 //     'description' => 'Settings for mkdru.',
93 //     'page callback' => 'drupal_get_form',
94 //     'page arguments' => array('mkdru_admin_settings'),
95 //     'type' => MENU_DEFAULT_LOCAL_TASK,
96 //     'file' => 'mkdru.admin.inc',
97 //     'weight' => 0,
98 //   );
99 //   $items['admin/settings/mkdru/ding'] = array(
100 //     'title' => 'Ding Integration',
101 //     'description' => 'Search settings for mkdru instance integrated into Ding.',
102 //     'page callback' => 'drupal_get_form',
103 //     'page arguments' => array('mkdru_ding_settings'),
104 //     'type' => MENU_LOCAL_TASK,
105 //     'weight' => 1,
106 //   );
107   $items['admin/settings/mkdru'] = array(
108     'title' => 'Pazpar2 Metasearch Settings',
109     'description' => 'Settings for mkdru.',
110     'page callback' => 'drupal_get_form',
111     'page arguments' => array('mkdru_admin_settings'),
112     'access arguments' => array('administer site configuration'),
113     'type' => MENU_NORMAL_ITEM,
114     'file' => 'mkdru.admin.inc',
115   );
116   $items['admin/settings/mkdru-ding'] = array(
117     'title' => 'Pazpar2 Metasearch Ding Integration',
118     'description' => 'Search settings for mkdru instance integrated into Ding.',
119     'page callback' => 'drupal_get_form',
120     'page arguments' => array('mkdru_ding_settings'),
121     'access arguments' => array('administer site configuration'),
122     'type' => MENU_NORMAL_ITEM,
123   );
124   $items['ahah-mkdru-facet'] = array(
125     'page callback' => 'mkdru_add_facet_callback',
126     'access arguments' => array('create metasearch interface'),
127     'type' => MENU_CALLBACK,
128   );
129   return $items;
130 }
131
132 /**
133 * Implements hook_init()
134 */
135 function mkdru_init() {
136   // Applies our module specific CSS to all pages. This works best because
137   // all CSS is aggregated and cached so we reduce the number of HTTP 
138   // requests and the size is negligible.
139   drupal_add_css(drupal_get_path('module', 'mkdru') .'/mkdru.css');
140 }
141
142
143 // Config form common to node and settings
144 // function mkdru_settings_form($form, &$form_state) {
145 function mkdru_settings_form(&$form_state) {
146   if (isset($form_state['values']['settings'])) {
147     $settings = $form_state['values']['settings'];
148   }
149   elseif (isset($form_state['build_info']['args']['settings'])) {
150     $settings = $form_state['build_info']['args']['settings'];
151   }
152   else {
153     $settings = variable_get('mkdru_defaults', NULL);
154   }
155
156   $form['#cache'] = TRUE;
157
158   $form['settings'] = array(
159     '#tree' => TRUE,
160   );
161
162   $form['settings']['pz2_path'] = array(
163     '#type' => 'textfield',
164     '#title' => t('Pazpar2/Service Proxy path'),
165     '#description' => t('Path that takes Pazpar2 commands via HTTP'),
166     '#required' => TRUE,
167     '#default_value' => $settings['pz2_path'],
168   );
169   $form['settings']['use_sessions'] = array(
170     '#type' => 'checkbox',
171     '#title' => t('Session handling'),
172     '#description' => t('Disable for use with Service Proxy'),
173     '#default_value' => $settings['use_sessions'],
174   );
175
176   $form['settings']['sp']  = array(
177     '#type' => 'fieldset',
178     '#title' => t('Service Proxy specific settings'),
179     '#collapsible' => TRUE,
180     '#collapsed' => FALSE
181   );
182   $form['settings']['sp']['user'] = array(
183     '#type' => 'textfield',
184     '#title' => t('Service Proxy username'),
185     '#description' => t('Service Proxy username'),
186     '#required' => FALSE,
187     '#default_value' => $settings['sp']['user'],
188   );
189   $form['settings']['sp']['pass'] = array(
190     '#type' => 'textfield',
191     '#title' => t('Service Proxy password'),
192     '#description' => t('Service Proxy password'),
193     '#required' => FALSE,
194     '#default_value' => $settings['sp']['pass'],
195   );
196
197   $form['settings']['facets']  = array(
198     '#type' => 'fieldset',
199     '#title' => t('Facet settings'),
200     // Set up the wrapper so that AJAX will be able to replace the fieldset.
201     '#prefix' => '<div id="mkdru-facets-form-wrapper">', 
202     '#suffix' => '</div>',
203     '#collapsible' => TRUE,
204     '#collapsed' => FALSE
205   );
206
207   foreach (array_keys($settings['facets']) as $facet) {
208     $form['settings']['facets'][$facet]  = array(
209       '#type' => 'fieldset',
210       '#title' => $facet . ' ' . t('facet'),
211       '#collapsible' => TRUE,
212       '#collapsed' => FALSE
213     );
214     $form['settings']['facets'][$facet]['displayName'] = array(
215       '#type' => 'textfield',
216       '#title' => t('Facet name to display in UI'),
217       '#required' => TRUE,
218       '#default_value' => $settings['facets'][$facet]['displayName'],
219     );
220     $form['settings']['facets'][$facet]['pz2Name'] = array(
221       '#type' => 'textfield',
222       '#title' => t('Name of termlist in Pazpar2'),
223       '#required' => TRUE,
224       '#default_value' => $settings['facets'][$facet]['pz2Name'],
225     );
226     $form['settings']['facets'][$facet]['limiter'] = array(
227       '#type' => 'textfield',
228       '#title' => t('Query limiter string'),
229       '#default_value' => $settings['facets'][$facet]['limiter'],
230       '#size' => 5,
231     );
232     $form['settings']['facets'][$facet]['multiLimit'] = array(
233       '#type' => 'checkbox',
234       '#title' => t('Allow multiple limits?'),
235       '#default_value' => $settings['facets'][$facet]['multiLimit'],
236     );
237     $form['settings']['facets'][$facet]['max'] = array(
238       '#type' => 'textfield',
239       '#title' => t('Number of terms to display'),
240       '#required' => TRUE,
241       '#default_value' => $settings['facets'][$facet]['max'],
242       '#size' => 3,
243       '#maxlength' => 3,
244     );
245     $form['settings']['facets'][$facet]['orderWeight'] = array(
246       '#type' => 'textfield',
247       '#title' => t('Facet weight'),
248       '#default_value' => $settings['facets'][$facet]['orderWeight'],
249       '#size' => 3,
250       '#maxlength' => 3,
251     );
252     $form['settings']['facets'][$facet]['remove'] = array(
253       '#type' => 'submit',
254       '#value' => t('Remove ') . $facet . t(' facet'),
255       '#mkdru facet' => $facet,
256       '#submit' => array('mkdru_remove_facet_submit'),
257       '#ahah' => array(
258         'path' => 'ahah-mkdru-facet',
259         'wrapper' => 'mkdru-facets-form-wrapper',
260       ),
261     );
262   }
263   $form['new_facet']  = array(
264     '#type' => 'fieldset',
265     '#title' => t('Add new facet...'),
266     '#tree' => TRUE,
267     '#collapsible' => TRUE,
268     '#collapsed' => FALSE
269   );
270   $form['new_facet']['canonical'] = array(
271     '#type' => 'textfield',
272     '#title' => t('Canonical name of new facet'),
273   );
274   $form['new_facet']['button'] = array(
275     '#type' => 'submit',
276     '#value' => t('Add facet'),
277     '#description' => t('Configure additional facets based on Pazpar2/SP termlists'),
278     '#submit' => array('mkdru_add_facet_submit'),
279     '#ahah' => array(
280       'path' => 'ahah-mkdru-facet',
281       'wrapper' => 'mkdru-facets-form-wrapper',
282     ),
283   );
284   return $form;
285 }
286
287 function mkdru_add_facet_submit($form, &$form_state) {
288   $newfacet = $form_state['values']['new_facet']['canonical'];
289   $form_state['values']['settings']['facets'][$newfacet] = NULL;
290   $form_state['rebuild'] = TRUE;
291   return $form_state['values'];
292 }
293
294 function mkdru_remove_facet_submit($form, &$form_state) {
295   $delfacet = $form_state['clicked_button']['#mkdru facet'];
296   if ($delfacet)
297     unset($form_state['values']['settings']['facets'][$delfacet]);
298 }
299
300 function mkdru_add_facet_callback() {
301   // Necessary to work with hook_form
302   module_load_include('inc', 'node', 'node.pages');
303
304   // Retrieve form from cache
305   $form_state = array('storage' => NULL, 'submitted' => FALSE);
306   $form_build_id = $_POST['form_build_id'];
307   $form = form_get_cache($form_build_id, $form_state);
308
309   // Run drupal_process_form to call submit handler and update $form_state
310   $args = $form['#parameters'];
311   $form_id = array_shift($args);
312   $form_state['post'] = $form['#post'] = $_POST;
313   $form['#programmed'] = $form['#redirect'] = FALSE;
314   drupal_process_form($form_id, $form, $form_state);
315
316   // Regenerate form so we can render the new facet part
317   $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
318
319   // Choose subset of form to redraw.
320   $facet_form = $form['settings']['facets'];
321   // Prevent duplicate wrappers.
322   unset($facet_form['#prefix'], $facet_form['#suffix']);
323   $output = theme('status_messages') . drupal_render($facet_form);
324
325   // Final rendering callback
326   drupal_json(array('status' => TRUE, 'data' => $output));
327 }
328
329
330
331 // Ding config
332 function mkdru_ding_settings(&$form_state) {
333   $form_state['build_info']['args']['settings'] = variable_get('mkdru_ding', NULL);
334   $form = drupal_retrieve_form('mkdru_settings_form', &$form_state);
335   $form['settings']['#title'] = t('Default search settings');
336   $form['submit'] = array(
337     '#type' => 'submit',
338     '#value' => 'Save configuration',
339   );
340   return $form;
341 }
342 function mkdru_ding_settings_submit($form, &$form_state) {
343   variable_set('mkdru_ding', $form_state['values']['settings']);
344   drupal_set_message(t('The configuration options have been saved.'));
345 }
346
347
348
349 // Node config
350 /**
351 * Implements hook_form()
352 */
353 function mkdru_form(&$node, &$form_state) {
354   if (isset($node->settings)) {
355     // Second decode parameter indicates associative array
356     $form_state['build_info']['args']['settings'] = json_decode($node->settings, TRUE);
357   }
358
359   $form = drupal_retrieve_form('mkdru_settings_form', &$form_state);
360   $type = node_get_types('type', $node);
361   $form['title'] = array(
362     '#type' => 'textfield',
363     '#title' => check_plain($type->title_label),
364     '#required' => FALSE,
365     '#default_value' => $node->title,
366     '#weight' => -5
367   );
368   return $form;
369 }
370
371
372 /**
373 * Implements hook_validate()
374 */
375 function mkdru_validate($node) {
376   // TODO: validation
377 }
378
379 /**
380 * Implements hook_insert().
381 */
382 function mkdru_insert($node) {
383   $record['nid'] =  $node->nid;
384   $record['vid'] =  $node->vid;
385   $record['settings'] =  json_encode($node->settings);
386   drupal_write_record('mkdru', &$record);
387 }
388
389 /**
390 * Implements hook_update().
391 */
392 function mkdru_update($node) {
393   if ($node->revision) {
394     // New revision; treat it as a new record.
395     mkdru_insert($node);
396   }
397   else {
398     $record['nid'] =  $node->nid;
399     $record['vid'] =  $node->vid;
400     $record['settings'] =  json_encode($node->settings);
401     drupal_write_record('mkdru', &$record, 'vid');
402   }
403 }
404
405 /**
406  * Implements hook_nodeapi().
407  *
408  * When a node revision is deleted, we need to remove the corresponding record
409  * from our table. The only way to handle revision deletion is by implementing
410  * hook_nodeapi().
411  */
412 function mkdru_nodeapi(&$node, $op, $teaser, $page) {
413   switch ($op) {
414     case 'delete revision':
415       db_query('DELETE FROM {mkdru} WHERE vid = %d', $node->vid);
416       break;
417   }
418 }
419
420 /**
421  * Implements hook_delete().
422  */
423 function mkdru_delete($node) {
424   // Deleting by nid covers all revisions.
425   db_query('DELETE FROM {mkdru} WHERE nid = %d', $node->nid);
426 }
427
428
429
430 // Node rendering
431 /**
432 * Implements hook_load()
433 */
434 function mkdru_load($node) {
435   return db_fetch_object(db_query('SELECT * FROM {mkdru} WHERE vid = %d', $node->vid));
436 }
437
438 /**
439 * Implements hook_theme().
440 */
441 function mkdru_theme() {
442   return array(
443     'mkdru_form' => array(
444       'template' => 'mkdru-form',
445       'arguments' => array(),
446     ),
447     'mkdru_results' => array(
448       'template' => 'mkdru-results',
449       'arguments' => array(),
450     ),
451     'mkdru_js' => array(
452       'arguments' => array('node' => NULL),
453     ),
454     'mkdru_block_search' => array(
455       'template' => 'mkdru-block-search',
456       'arguments' => array('nid' => NULL, 'path' => NULL),
457     ),
458     'mkdru_block_facet' => array(
459       'template' => 'mkdru-block-facet',
460       'arguments' => array('class' => NULL)
461     )
462   );
463 }
464
465 /**
466 * Theme function to include Javascript search client and deps
467 */
468 function theme_mkdru_js($node) {
469   $path = drupal_get_path('module', 'mkdru');
470   // Pazpar2 client library.
471   drupal_add_js(variable_get('pz2_js_path', 'pazpar2/js') . '/pz2.js', 'module', 'footer', TRUE, TRUE, FALSE);
472   // jQuery plugin for query string/history manipulation.
473   drupal_add_js($path . '/jquery.ba-bbq.js', 'module', 'footer', TRUE, TRUE, FALSE);
474   drupal_add_js($path . '/mkdru.theme.js', 'module', 'footer', TRUE, TRUE, FALSE);
475   drupal_add_js($path . '/mkdru.client.js', 'module', 'footer', TRUE, TRUE, FALSE);
476   drupal_add_js(array('mkdru' => $node->mkdru), 'setting');
477   drupal_add_js(array('mkdru' => 
478     array(
479       'settings' => $node->settings,
480     )
481   ), 'setting');
482 }
483
484 /** 
485 * Implements hook_view()
486 */
487 function mkdru_view($node, $teaser = FALSE, $page = FALSE) {
488   $node->content['mkdru_js'] = array(
489     '#value' => theme('mkdru_js', $node), 
490     '#weight' => 0,
491   );
492   $node->content['mkdru_form'] = array(
493     '#value' => theme('mkdru_form'), 
494     '#weight' => 1,
495   );
496   $node->content['mkdru_results'] = array(
497     '#value' => theme('mkdru_results'), 
498     '#weight' => 2,
499   );
500   return $node;
501 }
502
503 /** 
504 * Implements hook_block()
505 */
506 function mkdru_block($op='list', $delta='sources', $edit=array()) {
507   switch ($op) {
508     case 'list':
509       // maybe if I label the tables or something?
510       $result = db_query("SELECT title, {mkdru}.nid as nid, settings FROM {node},{mkdru} WHERE {mkdru}.nid = {node}.nid;");
511       while ($node = db_fetch_object($result)) {
512         // search blocks
513         $blocks['mkdru_search_' . $node->nid]['info'] = 
514            t('mkdru - search box for "' . $node->title . '"');
515         // facet blocks
516         $settings = json_decode($node->settings, TRUE);
517         foreach ($settings['facets'] as $facet_name => $facet) {
518           $key = 'mkdru_facet_' . $facet_name . '_' . $node->nid;
519           $blocks[$key]['info'] = 'mkdru - ' . $facet_name
520             . t(' facet for "') . $node->title . '"';
521           $blocks[$key]['visibility'] = 1;
522           $blocks[$key]['pages'] = 'node/' . $node->nid;
523           $blocks[$key]['cache'] = BLOCK_CACHE_GLOBAL;
524         }
525       };
526       return $blocks;
527
528     case 'view':
529       if (preg_match('/^mkdru_facet_(.*)_(\d+)$/', $delta, $matches) > 0) {
530         $facet = $matches[1];
531         $nid = $matches[2];
532
533         // this is rather spendy just to get the title, should really
534         // be able to set a default title in op=list. will be cached though
535         // so I suppose it's okay?
536         $result = db_query("SELECT settings FROM {mkdru} WHERE nid = %d;", $nid);
537         $settingsjson = db_fetch_object($result)->settings;
538         $settings = json_decode($settingsjson, TRUE);
539         if (isset($settings['facets'][$facet]['displayName'])) {
540           $block['subject'] = $settings['facets'][$facet]['displayName'];
541         }
542         $block['content'] = theme('mkdru_block_facet', 'mkdru-facet-' . $facet);
543       }
544       else if (substr($delta, 0, 13) == 'mkdru_search_') {
545         $nid = substr($delta, 13);
546         $block['content'] = theme('mkdru_block_search', $nid, '/node/' . $nid);
547       }
548     return $block;
549   }
550 }