/[drupal]/contributions/modules/biblio/biblio.import.export.inc
ViewVC logotype

Contents of /contributions/modules/biblio/biblio.import.export.inc

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.44 - (show annotations) (download) (as text)
Fri Oct 23 20:19:37 2009 UTC (5 weeks ago) by rjerome
Branch: MAIN
CVS Tags: HEAD
Branch point for: DRUPAL-7--1
Changes since 1.43: +72 -68 lines
File MIME type: text/x-php
merged changes from DRUPAL-6--1 branch
1 <?PHP
2
3 // $Id: biblio.import.export.inc,v 1.7.2.70 2009/10/09 20:19:12 rjerome Exp $
4 /**
5 * @file
6 * Functions that are used to import and export biblio data.
7 *
8 */
9 /* biblio.import.export.inc
10 *
11 * Copyright (C) 2006-2008 Ron Jerome
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 */
28 /**
29 * Return a form select box populated with all the users of the site.
30 *
31 * @param $my_uid
32 * The user id of the person accessing the form so the select box defaults
33 * to their userid
34 * @return
35 * An array which will be used by the form builder to add a select box to a form
36 */
37 function _biblio_admin_build_user_select($my_uid) {
38 $sql = 'SELECT DISTINCT u.uid, u.name, u.status, u.mail FROM {users} u WHERE u.uid != 0 ';
39 $result = db_query($sql);
40 while ($user = db_fetch_object($result)) {
41 $users[$user->uid] = $user->name ." ($user->mail)";
42 }
43 asort($users);
44 $select = array (
45 '#type' => 'select',
46 '#title' => t("Set user ID of entries in this file to"),
47 '#options' => $users,
48 '#default_value' => $my_uid,
49 '#disabled' => (user_access('administer biblio')) ? FALSE : TRUE
50 );
51 return $select;
52 }
53 /**
54 * Return a form used to import files into biblio.
55 *
56 * @return
57 * An array which will be used by the form builder to build the import form
58 */
59 function biblio_import_form() {
60 global $user;
61 if (biblio_access('import')) { // && !user_access('administer nodes')) {
62 $form['#attributes']['enctype'] = 'multipart/form-data';
63 $form['biblio_import_file'] = array (
64 '#type' => 'file',
65 '#title' => t('Import file'),
66 '#default_value' => '',
67 '#size' => 60
68 );
69 $form['filetype'] = array (
70 '#type' => 'select',
71 '#title' => t('File Type'),
72 '#default_value' => 0,
73 '#options' => array (
74 'none' => t('Select type'),
75 'bib' => t('BibTex'),
76 'tagged' => t('EndNote Tagged'),
77 'xml' => t('EndNote 7 XML (and previous versions)'),
78 'xml8' => t('EndNote 8 XML (and newer versions)'),
79 'marc' => t('MARC'),
80 'ris' => t('RIS'),
81 )
82 );
83 $form['batch_process'] = array (
84 '#type' => 'checkbox',
85 '#title' => t('Batch Process'),
86 '#default_value' => 1,
87 '#description' => t('You should use batch processing if your import file contains more than about 20 records, or if you are experiencing script timeouts during import'),
88 );
89 $form ['userid'] = _biblio_admin_build_user_select($user->uid);
90 // Get the vocabularies attached to the biblio node type ...
91 $vocabularies = module_invoke('taxonomy', 'get_vocabularies', 'biblio');
92 // ... and print a form to select the terms in each of them
93 $form['import_taxonomy'] = array (
94 '#type' => 'fieldset',
95 '#collapsible' => TRUE,
96 '#collapsed' => TRUE,
97 '#title' => t('Taxonomy Settings'),
98 '#description' => t('Typically you don\'t have to do anything here, however if you wish, you may select terms to be assigned to imported records. This effectively adds a keyword to all entries being imported.'));
99 if (count($vocabularies)) {
100 if (variable_get('biblio_keyword_freetagging', 0)) {
101 $freetag_vocab = $vocabularies[variable_get('biblio_keyword_vocabulary', 0)];
102 unset($vocabularies[variable_get('biblio_keyword_vocabulary', 0)]);
103 $msg = t('<b>NOTE:</b> Keyword "free tagging" is turned on, consequently all incomming keywords will be added to the <b>@name</b> vocabulary as specified in the "Keyword" section of the !url page.', array ('@name' => $freetag_vocab->name, '!url' => l(t('admin/settings/biblio'), 'admin/settings/biblio')));
104 } else {
105 $msg = t('<b>NOTE:</b> Keyword "free tagging" is turned off, consequently keywords will <b>NOT</b> be added to the vocabulary as specified in the Taxonomy section of the !url page.', array ('!url' => l(t('admin/settings/biblio'), 'admin/settings/biblio')));
106 }
107 $i = 0;
108 foreach ($vocabularies as $vocabulary) {
109 $form['import_taxonomy']['vocabulary'. $i] = module_invoke('taxonomy', 'form', $vocabulary->vid, 0);
110 $form['import_taxonomy']['vocabulary'. $i]['#weight'] = $vocabulary->weight;
111 $form['import_taxonomy']['vocabulary'. $i++]['#description'] = t("Select taxonomy term to be assigned to imported entries");
112 }
113 $form['import_taxonomy']['copy_to_biblio'] = array(
114 '#type' => 'checkbox',
115 '#title' => t('Copy these terms to the biblio keyword database'),
116 '#return_value' => 1,
117 '#default_value' => variable_get('biblio_copy_taxo_terms_to_keywords', 0),
118 '#description' => t('If this option is selected, the selected taxonomy terms will be copied to the '.variable_get('biblio_base_title', 'Biblio').' keyword database and be displayed as keywords (as well as taxonomy terms) for this entry.')
119 );
120
121 } else {
122 if (module_exists('taxonomy')){
123 $vocab_msg = t('There are currently no vocabularies assigned to the biblio node type, please go the the !url page to fix this', array ('!url' => l(t('admin/content/taxonomy'), 'admin/content/taxonomy')));
124 }else{
125 $vocab_msg = '<div class="admin-dependencies">'. t('Depends on') .': '. t('Taxonomy') .' (<span class="admin-disabled">'. t('disabled') .'</span>)</div>';
126
127 }
128 $form['import_taxonomy']['vocabulary_message'] = array (
129 '#value' => '<p><div>'. $vocab_msg .'</div></p>'
130 );
131 }
132 $form['import_taxonomy']['freetagging_information'] = array (
133 '#value' => '<p><div>'. $msg .'</div></p>'
134 );
135 $form['button'] = array ('#type' => 'submit', '#value' => t('Import'));
136 return $form;
137 } else {
138 drupal_set_message("You are not authorized to access the biblio import page", 'error');
139 print theme('page', '');
140 }
141 }
142
143 /**
144 * Implementation of hook_validate() for the biblio_import_form.
145 */
146 function biblio_import_form_validate($form, & $form_state) {
147 $op = $form_state['values']['op'];
148 $filetype = $form_state['values']['filetype'];
149 if ($error = $_FILES['files']['error']['biblio_import_file']) {
150 switch ($error){
151 case 1: form_set_error('biblio_import_form', t("The uploaded file exceeds the upload_max_filesize directive in php.ini."));
152 break;
153 case 2: form_set_error('biblio_import_form', t("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form."));
154 break;
155 case 3: form_set_error('biblio_import_form', t("The uploaded file was only partially uploaded."));
156 break;
157 case 4: form_set_error('biblio_import_form', t("No file was uploaded."));
158 break;
159 case 6: form_set_error('biblio_import_form', t("Missing a temporary folder."));
160 break;
161 case 7: form_set_error('biblio_import_form', t("Failed to write file to disk."));
162 break;
163 case 8: form_set_error('biblio_import_form', t("File upload stopped by extension."));
164 }
165 }
166
167 if ($op == t('Import') && $filetype == "none") {
168 form_set_error('biblio_import_form', t("Error: You must select a file type"));
169 }
170 }
171 /**
172 * Implementation of hook_submit() for the biblio_import_form.
173 */
174 function biblio_import_form_submit($form, & $form_state) {
175 global $batch_proc;
176 global $session_id;
177 if ($form_state['values']['op'] == t('Import') && isset ($form_state['values']['filetype'])) {
178 if ($import_file = file_save_upload('biblio_import_file')) {
179 if($form_state['values']['batch_process'] == 1) $batch_proc = 1; // we will use batch import for larger files.
180
181 drupal_set_message(t("The file <i><b>@file</b></i> was successfully uploaded.", array ('@file' => $import_file->filename)), 'status');
182 // Concatenate all the terms of the different vocabularies
183 // in a single array to be sent to biblio_import
184 $terms = array ();
185 foreach (array_keys($form_state['values']) as $key) {
186 if (preg_match('/(vocabulary[0-9]+)/', $key)) {
187 if (!empty($form_state['values'][$key])){
188 if (is_array($form_state['values'][$key])) {
189 $terms[] = $form_state['values'][$key];
190 }
191 else {
192 $terms[] = array($form_state['values'][$key]);
193 }
194 }
195 }
196 if ($key == 'copy_to_biblio') $terms['copy_to_biblio'] = $form_state['values'][$key];
197 }
198
199 // Added the $terms argument
200 // the array of terms to be attached to the node(s)
201 $userid = (isset ($form_state['values']['userid'])) ? $form_state['values']['userid'] : 1;
202 $filetype = $form_state['values']['filetype'];
203 if ($batch_proc) {
204 $session_id = microtime();
205 $batch_op = array(
206 'title' => t('Importing '.$import_file->filename),
207 'operations' => array(
208 array('biblio_import', array($import_file, $filetype, $userid, $terms, $batch_proc, $session_id)),
209 array('biblio_import_batch_operations', array($session_id, $userid, $terms)),
210 ),
211 'progressive' => TRUE,
212 'finished' => 'biblio_import_batch_finished',
213 'init_message' => t('Parsing file...'),
214 'progress_message' => t('Saving nodes...'),
215 'file' => './'. drupal_get_path('module', 'biblio') .'/biblio.import.export.inc'
216 );
217 batch_set($batch_op);
218
219 $base = variable_get('biblio_base', 'biblio');
220 batch_process("$base/import");
221
222 }else{ //not batch processing the file
223 $session_id = microtime();
224 $dummy = array();
225 $content = biblio_import($import_file, $filetype, $userid, $terms, $batch_proc, $session_id, $dummy);
226 }
227 file_delete($import_file->filepath);
228 } else {
229 drupal_set_message(t("File was NOT successfully uploaded"), 'error');
230 }
231 }
232 }
233 function biblio_import_batch_operations($session_id, $userid, $terms, &$context) {
234 if (empty($context['sandbox'])) {
235 // Initiate multistep processing.
236 $context['results']['session_id'] = $session_id;
237 $context['results']['userid'] = $userid;
238 $context['results']['terms'] = $terms;
239 $context['sandbox']['progress'] = 0;
240 $context['sandbox']['current_id'] = 0;
241 $context['results']['nids'] = array();
242 $context['sandbox']['max'] = db_result(db_query("SELECT COUNT(DISTINCT(id)) FROM {biblio_import_cache} WHERE session_id = '%s'", $session_id));
243 }
244
245 // Process the next 20 nodes.
246 $limit = 5;
247 $result = db_query_range("SELECT id, data FROM {biblio_import_cache} WHERE id > %d AND session_id = '%s' ORDER BY id ASC", $context['sandbox']['current_id'], $session_id, 0, $limit);
248 while ($row = db_fetch_array($result)) {
249 $node = unserialize($row['data']);
250 node_save($node);
251 $context['results']['nids'][] = $node->nid;
252 $context['sandbox']['progress']++;
253 $context['sandbox']['current_id'] = $row['id'];
254 }
255
256 // Multistep processing : report progress.
257 if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
258 $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
259 }
260 }
261 function biblio_import_batch_finished($success, $results, $operations) {
262 if ($success && count($results['nids'])) {
263 $message = format_plural(count($results['nids']), 'One node saved.', '@count nodes saved.');
264 $type = 'status';
265 }
266 else {
267 $message = t('Import finished with an error! '). format_plural(count($results['nids']), 'One node saved.', '@count nodes saved.');
268 $type = 'error';
269 }
270 drupal_set_message($message, $type);
271 foreach ($results['nids'] as $node_id) {
272 if (count($results['terms'])) module_invoke('taxonomy', 'node_save', $node_id, $results['terms']);
273 db_query('UPDATE {node} SET uid = %d WHERE nid = %d', $results['userid'], $node_id);
274 db_query('UPDATE {node_revisions} SET uid = %d WHERE nid = %d', $results['userid'], $node_id);
275 }
276 //clean up import cache...
277 db_query("DELETE FROM {biblio_import_cache} WHERE session_id = '%s'",$results['session_id']);
278
279 }
280
281 function biblio_import_from_url($URL) {
282 $handle = fopen($URL, "r"); // fetch data from URL in read mode
283 $data = "";
284 if ($handle)
285 {
286 while (!feof($handle))
287 {
288 $data .= fread($handle, 4096); // read data in chunks
289 }
290 fclose($handle);
291 }
292 else
293 {
294 $errorMessage = t("Error occurred: Failed to open ") . $URL; // network error
295 drupal_set_message($errorMessage, 'error');
296 }
297
298 return $data;
299 }
300
301 function biblio_export_form() {
302 $form['pot'] = array (
303 '#type' => 'fieldset',
304 '#collapsible' => TRUE,
305 '#collapsed' => TRUE,
306 '#title' => t('POT Export'),
307 '#description' => t('Here you may export a ".pot" file which contains the titles and hints from the database which are not normally captured by translation extractors)')
308 );
309 $form['pot']['button'] = array (
310 '#type' => 'submit',
311 '#value' => t('Export translation data')
312 );
313
314 return $form;
315 }
316 function biblio_export_form_submit($form, & $form_state) {
317 if ($form_state['values']['op'] == t('Export translation data')) {
318 biblio_dump_db_data_for_pot();
319 }
320
321 }
322
323 /**
324 * Import data from a file and return the node ids created.
325 *
326 * @param $userid
327 * The user id of that will be assigned to each node imported
328 * @param $filename
329 * The name of the file containing the data to import
330 * @param $type
331 * The format of the file to be imported (tagged, XML, RIS, bibTEX)
332 * @param $terms
333 * the vocabulary that the imported nodes will be associated with
334 * @return
335 * An array the node id's of the items imported
336 */
337 function biblio_import($import_file, $type, $userid = 1, $terms = NULL, $batch = FALSE, $id = NULL, &$context ) {
338
339 global $user, $batch_proc, $session_id, $biblio_uid;
340 $batch_proc = $batch;
341 $session_id = $id;
342 $biblio_uid = $userid;
343 $parsed = 0;
344 if(isset($context['message'])) $context['message'] = t('Parsing file');
345 switch ($type) {
346 case 'tagged' : // EndNote Tagged
347 module_load_include('inc', 'biblio', 'tagged_parser');
348 $node_ids = _endnote_tagged_import($import_file, $terms, $batch_proc, $session_id);
349 break;
350 case 'ris' : // RIS
351 module_load_include('inc', 'biblio', 'ris_parser');
352 $node_ids = _ris_tagged_import($import_file, $terms, $batch_proc, $session_id);
353 break;
354 case 'xml' : // EndNote 7 XML
355 $node_ids = biblio_endnote_XML_import($import_file, $terms, $batch_proc, $session_id, 7);
356 break;
357 case 'xml8' : // EndNote 8+ XML
358 $node_ids = biblio_endnote_XML_import($import_file, $terms, $batch_proc, $session_id, 8);
359 break;
360 case 'bib' : // BibTex
361 $node_ids = biblio_bibtex_import($import_file, $terms, $batch_proc, $session_id);
362 break;
363 case 'marc' : // MARC
364 $node_ids = biblio_marc_import($import_file, $terms, $batch_proc, $session_id);
365 break;
366 case 'csv' : // comma separated variable file
367 // $file_content = @ file_get_contents($import_file->filepath);
368 // $parsed = biblio_csv_import($file_content, $node_template, $node_array);
369 break;
370 case 'biblio_backup' : // a complete backup of all biblio information
371 $file_content = @ file_get_contents($import_file->filepath);
372 $parsed = biblio_restore($file_content, $node_template, $node_array);
373 break;
374 }
375 if (!empty($node_ids) && !$batch ) {
376 if (count($node_ids)) {
377 db_query('UPDATE {node} SET uid = %d WHERE nid IN(%s)', $userid, implode(',', $node_ids));
378 db_query('UPDATE {node_revisions} SET uid = %d WHERE nid IN(%s)', $userid, implode(',', $node_ids));
379 drupal_set_message(t("<i><b>%count</b></i> nodes were successfully imported.", array('%count' => count($node_ids))), 'status');
380 }
381
382 return $node_ids;
383 }
384 elseif ($parsed && !$save) {
385 return $node;
386 }
387
388
389 }
390 /**
391 * Export nodes in a given file format.
392 *
393 * @param $format
394 * The file format to export the nodes in (tagged, XML, bibTEX)
395 * @param $nid
396 * If not NULL, then export only the given nodeid, else we will
397 * use the session variable which holds the most recent query. If neither
398 * $nid or the session variable are set, then nothing is exported
399 * @param $version
400 * The version of EndNote XML to use. There is one format for ver. 1-7 and
401 * a different format for versions 8 and greater.
402 * @return
403 * none
404 */
405 function biblio_export($format = "tagged", $nid = null, $popup = false, $version = 8) {
406 module_load_include('inc', 'biblio', 'endnote8_export');
407 module_load_include('inc', 'biblio', 'biblio.contributors');
408 module_load_include('inc', 'biblio', 'biblio.keywords');
409 $params = array ();
410 if ($nid === null && isset ($_SESSION['last_biblio_query']) && !empty ($_SESSION['last_biblio_query'])) {
411 $query = $_SESSION['last_biblio_query'];
412 $params = $_SESSION['last_biblio_query_terms'];
413 }
414 elseif (!empty ($nid)) {
415 $query = db_rewrite_sql("SELECT DISTINCT(n.nid) FROM {node} n WHERE n.nid=%d ");
416 $params[] = $nid;
417 } else {
418 return;
419 }
420 $result = db_query($query, $params);
421 $count = 0;
422 while ($node = db_fetch_object($result)) {
423 $node = node_load($node->nid, FALSE, TRUE);
424 // $node->biblio_contributors = biblio_load_contributors($node->vid);
425 // $node->biblio_keywords = biblio_load_keywords($node->vid);
426 // if (module_exists("upload")) $node->files = upload_load($node);
427 $count++;
428 set_time_limit(30);
429 switch ($format) {
430 case "tagged" :
431 if (!$popup && $count == 1) {
432 drupal_set_header('Content-type: application/x-endnote-refer');
433 drupal_set_header('Content-Disposition: filename="Drupal-Biblio.enw"');
434 }
435 if (!$popup) {
436 print biblio_endnote_tagged_export($node);
437 }
438 else {
439 $popup_data .= biblio_endnote_tagged_export($node);
440 }
441 break;
442 case "xml" :
443 if ($count == 1) {
444 drupal_set_header('Content-type: application/xml; charset=utf-8');
445 drupal_set_header('Content-Disposition: attachment; filename="Biblio-EndNote'. $version .'.xml"');
446 print _endnote8_XML_export('', 'begin');
447 }
448 print _endnote8_XML_export($node);
449 break;
450 case "bibtex" :
451 if (!$popup && $count == 1) {
452 drupal_set_header('Content-type: application/text; charset=utf-8');
453 drupal_set_header('Content-Disposition: filename="Biblio-Bibtex.bib"');
454 }
455 if (!$popup) {
456 print biblio_bibtex_export($node);
457 }
458 else{
459 $popup_data .= biblio_bibtex_export($node);
460 }
461 break;
462 case "csv" :
463 drupal_set_header('Content-Type: application/text; charset=utf-8');
464 drupal_set_header('Content-Disposition: attachment; filename=Biblio-export.csv');
465 print biblio_csv_export($node);
466 break;
467 }
468 }
469
470 if ($format == 'xml' && $count > 0) print _endnote8_XML_export('', 'end');
471 if ($popup && !empty($popup_data)) return '<pre>' . $popup_data . '</pre>';
472
473 }
474 /**
475 * Import bibtex data.
476 *
477 * @param $data
478 * the contents of a bibtex file passed as one big string
479 * @param $node
480 * an array (populated in biblio_import() ), containing the boiler plate
481 * information common to all nodes
482 * @return
483 * an array of node ids
484 */
485 function biblio_bibtex_import($file, $terms = array(), $batch = FALSE, $session_id = NULL, $save = TRUE, $string = FALSE) {
486 $nids = array();
487 module_load_include('php', 'biblio', 'bibtexParse/PARSEENTRIES');
488 $bibtex = new PARSEENTRIES();
489 if ($string) {
490 $bibtex->loadBibtexString($file);
491 }
492 else {
493 $bibtex->openBib($file->filepath);
494 }
495 $bibtex->extractEntries();
496 if ($bibtex->count) {
497 $nids = $bibtex->bib2node($terms, $batch, $session_id, $save);
498 }
499 return $nids;
500 }
501 function biblio_marc_import($file, $terms, $batch, $session_id) {
502 $nids = array();
503 module_load_include('php', 'biblio', 'marcParse/php-marc');
504 $marcfile = new File($file->filepath);
505 while ($record = $marcfile->next() ) {
506 $node=array();
507 foreach($record->fields() as $fields) {
508 foreach ($fields as $field){
509 switch ($field->tagno) {
510 case '008':
511 $data = $field->data();
512 $node['biblio_year'] = substr($data,7,4);
513 $node['biblio_lang'] = substr($data,35,3);
514 break;
515 case '020':
516 $node['biblio_isbn'] = $field->subfield('a');
517 break;
518 case '022':
519 $node['biblio_issn'] = $field->subfield('a');
520 break;
521 case '024':
522 $node['biblio_other_number'] = $field->subfield('a');
523 break;
524 case '050': //LIBRARY OF CONGRESS CALL NUMBER
525 case '055': //CLASSIFICATION NUMBERS ASSIGNED IN CANADA
526 case '060': //NATIONAL LIBRARY OF MEDICINE CALL NUMBER
527 $node['biblio_call_number'] = $field->subfield('a');
528 break;
529 case '130':
530 $node['title'] = str_replace(' /', '', $field->subfield('a'));
531 break;
532 case '210':
533 $node['biblio_short_title'] = str_replace(' /', '', $field->subfield('a'));
534 break;
535 case '245':
536 $node['title'] = str_replace(' /', '', $field->subfield('a')).' '.$field->subfield('b');
537 break;
538 case '250':
539 $node['biblio_edition'] = $field->subfield('a');
540 break;
541 case '260':
542 $node['biblio_place_published'] = str_replace(' :', '', $field->subfield('a'));
543 $node['biblio_publisher'] = $field->subfield('b');
544 $node['biblio_date'] = $field->subfield('c');
545 break;
546 case '300':
547 $node['biblio_pages'] = $field->subfield('a');
548 break;
549 case '490':
550 $node['biblio_volumne'] = $field->subfield('v');
551 break;
552 case '100':
553 case '700':
554 $node['biblio_contributors'][1][] = array(
555 'name' => $field->subfield('a'),
556 'auth_type' => 1
557 );
558 break;
559 case '110':
560 case '710':
561 $node['biblio_contributors'][5][] = array(
562 'name' => $field->subfield('a'),
563 'auth_type' => 5
564 );
565 break;
566 }
567 }
568 }
569 if (!empty($node)) {
570 if (!empty($terms)) {
571 if (!isset($node['taxonomy'])) $node['taxonomy'] = array();
572 $node['taxonomy'] = array_merge($terms,$node['taxonomy']);
573 }
574 $nids[] = biblio_save_node($node, $batch, $session_id);
575 }
576
577 }
578 return $nids;
579 }
580 /**
581 * Export data in bibtex format.
582 *
583 * @param $result
584 * a database result set pointer
585 * @return
586 * none
587 */
588 function biblio_bibtex_export($node) {
589 $bibtex = '';
590 $type = "article";
591 $journal = $series = $booktitle = $school = $organization = $institution = null;
592 $type = _bibtex_type_map($node->biblio_type);
593 switch ($node->biblio_type) {
594 case 100 :
595 $series = $node->biblio_secondary_title;
596 $organization = $node->biblio_publisher;
597 break;
598 case 101 :
599 case 103 :
600 $booktitle = $node->biblio_secondary_title;
601 $organization = $node->biblio_publisher;
602 $series = $node->biblio_tertiary_title;
603 break;
604 case 108 :
605 $school = $node->biblio_publisher;
606 $node->biblio_publisher = null;
607 if (stripos($node->biblio_type_of_work, 'masters')) {
608 $type = "mastersthesis";
609 }
610 break;
611 case 109 :
612 $institution = $node->biblio_publisher;
613 $node->biblio_publisher = null;
614 break;
615 case 102 :
616 default:
617 $journal = $node->biblio_secondary_title;
618 break;
619 }
620 $bibtex .= '@'. $type .' {';
621 $bibtex .= ($node->biblio_citekey) ? $node->biblio_citekey : "";
622 $bibtex .= _bibtex_format_entry('title', $node->title);
623 $bibtex .= _bibtex_format_entry('journal', $journal);
624 $bibtex .= _bibtex_format_entry('booktitle', $booktitle);
625 $bibtex .= _bibtex_format_entry('series', $series);
626 $bibtex .= _bibtex_format_entry('volume', $node->biblio_volume);
627 $bibtex .= _bibtex_format_entry('number', $node->biblio_number);
628 $bibtex .= _bibtex_format_entry('year', $node->biblio_year);
629 $bibtex .= _bibtex_format_entry('note', $node->biblio_notes);
630 $bibtex .= _bibtex_format_entry('month', $node->biblio_date);
631 $bibtex .= _bibtex_format_entry('pages', $node->biblio_pages);
632 $bibtex .= _bibtex_format_entry('publisher', $node->biblio_publisher);
633 $bibtex .= _bibtex_format_entry('school', $school);
634 $bibtex .= _bibtex_format_entry('organization', $organization);
635 $bibtex .= _bibtex_format_entry('institution', $institution);
636 $bibtex .= _bibtex_format_entry('type', $node->biblio_type_of_work);
637 $bibtex .= _bibtex_format_entry('edition', $node->biblio_edition);
638 $bibtex .= _bibtex_format_entry('chapter', $node->biblio_section);
639 $bibtex .= _bibtex_format_entry('address', $node->biblio_place_published);
640 $bibtex .= _bibtex_format_entry('abstract', $node->biblio_abst_e);
641
642 $kw_array = array();
643 if (!empty($node->terms)){
644 foreach($node->terms as $term){
645 $kw_array[] = $term->name;
646 }
647 }
648 if (!empty($node->biblio_keywords)) {
649 foreach($node->biblio_keywords as $term){
650 $kw_array[] = $term;
651 }
652 }
653 if (!empty($kw_array)){
654 $kw_array = array_unique($kw_array);
655 $bibtex .= _bibtex_format_entry('keywords', implode(', ', $kw_array));
656 }
657 $bibtex .= _bibtex_format_entry('isbn', $node->biblio_isbn);
658 $bibtex .= _bibtex_format_entry('issn', $node->biblio_issn);
659 $bibtex .= _bibtex_format_entry('doi', $node->biblio_doi);
660 $bibtex .= _bibtex_format_entry('url', $node->biblio_url);
661 if (!empty ($node->files) && count($node->files) && user_access('view uploaded files')) {
662 foreach($node->files as $file) {
663 $attachments[] = file_create_url($file->filepath);
664 }
665 $bibtex .= _bibtex_format_entry('attachments', implode(' , ', $attachments));
666 }
667
668 $a = $e = array();
669 foreach ((array)$node->biblio_contributors[1] as $auth) $a[] = trim($auth['name']);
670 foreach ((array)$node->biblio_contributors[2] as $auth) $e[] = trim($auth['name']);
671 $a = implode(' and ', $a);
672 $e = implode(' and ', $e);
673 if (!empty ($a)) $bibtex .= _bibtex_format_entry('author', $a);
674 if (!empty ($e)) $bibtex .= _bibtex_format_entry('editor', $e);
675 $bibtex .= "\n}\n";
676
677
678 //now convert any special characters to the latex equivelents...
679 module_load_include('php', 'biblio', 'bibtexParse/PARSEENTRIES');
680 include(drupal_get_path('module', 'biblio') . '/bibtexParse/transtab_unicode_bibtex.inc.php');
681 $converter = new PARSEENTRIES();
682 $bibtex = $converter->searchReplaceText($transtab_unicode_bibtex, $bibtex, false);
683
684 return $bibtex;
685 }
686 function _bibtex_format_entry($key, $value) {
687 return !empty($value) ? ",\n\t$key = {".$value."}" : '';
688 }
689
690 function _bibtex_type_map($bibliotype) {
691 static $map = array();
692 if (empty($map)) {
693 module_load_include('inc', 'biblio', 'biblio.type.mapper');
694 $map = biblio_get_type_map('bibtex');
695 }
696 return ($type = array_search($bibliotype, $map)) ? $type : 'article';
697 }
698
699 /**
700 * Save node imported from a file.
701 *
702 * @param $node_array
703 * a 2 dimensional array containing all the node information
704 * @return
705 * The node ids of the saved nodes
706 */
707 function biblio_save_imported_nodes(& $node_array) {
708 $dup_count = 0;
709 if (function_exists('node_save')) {
710 foreach ($node_array as $imp_node) {
711 $node_ids[] = biblio_save_node($imp_node);
712 }
713 }
714 /* if ($dup_count)
715 drupal_set_message(t("Detected @dupcount duplicate node(s) when importing", array ('@dupcount' => $dup_count)), 'error');
716
717 drupal_set_message(t("Succesfully imported @count entries.", array ('@count' => count($node_ids))), 'status');
718 */
719 return $node_ids;
720 }
721 function biblio_save_node($node, $batch = FALSE, $session_id = NULL, $save_node = TRUE) {
722 $options = variable_get('node_options_biblio', array ('status'));
723 if (module_exists('i18n') && variable_get('i18n_node_biblio', 0) && variable_get('language_content_type_biblio', 0) ){
724 $node['language'] = module_invoke('i18n', 'default_language');
725 }
726 $node_template = array (
727 'type' => 'biblio',
728 'comment' => variable_get('comment_biblio', 0),
729 'promote' => in_array('promote', $options),
730 'moderate' => in_array('moderate', $options),
731 'sticky' => in_array('sticky', $options),
732 'format' => 0,
733 'status' => in_array('status', $options),
734 );
735
736 $node = (object) array_merge($node, $node_template);
737 if(!isset($node->biblio_type)) $node->biblio_type = 129; // default to misc if not set.
738 if ($batch && $session_id){ // we are batch processing some import data
739 $node = serialize($node);
740 db_query("INSERT INTO {biblio_import_cache} (session_id, data) VALUES ('%s', %b)", $session_id, $node);
741 return;
742 }
743 elseif ($save_node) { // $save_node = TRUE, the normal save path
744 node_save($node);
745 return (isset($node->nid)) ? $node->nid : 0;
746 }
747 else { // $save_node = FALSE, primarily used to parse data and return it to the input form
748 return (array)$node;
749 }
750 }
751
752 function biblio_crossref_xml_import($doi, $terms = array(), $batch = FALSE, $session_id = NULL, $save = FALSE) {
753 global $user, $node, $save_node, $nids;
754 if (!isset($user->biblio_crossref_pid) || empty($user->biblio_crossref_pid) ) return FALSE;
755 $save_node = $save;
756 $nids = array();
757 $url = 'http://www.crossref.org/openurl/?pid='. $user->biblio_crossref_pid .'&noredirect=true&format=unixref&id=doi%3A'. $doi;
758 if (!($fp = fopen($url, "r"))) {
759 drupal_set_message(t('Could not open crossref.org for XML input'),'error');
760 return;
761 }
762 $xml = fread($fp, 2048);
763 $xml_parser = drupal_xml_parser_create($xml);
764 // use case-folding so we are sure to find the tag in
765 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
766 xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, true);
767
768 module_load_include('inc', 'biblio', 'crossref_unixref_parser');
769 xml_set_element_handler($xml_parser, 'unixref_startElement', 'unixref_endElement');
770 xml_set_character_data_handler($xml_parser, 'unixref_characterData');
771
772 xml_parse($xml_parser, $xml);
773 while ($xml = fread($fp, 2048)){
774 set_time_limit(30);
775 if(!xml_parse($xml_parser, $xml, feof($fp))){
776 drupal_set_message(sprintf("XML error: %s at line %d",
777 xml_error_string(xml_get_error_code($xml_parser)),
778 xml_get_current_line_number($xml_parser)),'error');
779 }
780 }
781 xml_parser_free($xml_parser);
782 fclose($fp);
783 return (!empty($nids)) ? $nids : array();
784
785 }
786
787
788 /**
789 * Import EndNote XML data.
790 *
791 * @param $data
792 * the contents of an EndNote XML file passed as one big string
793 * @param $node
794 * boiler plate information common to all nodes
795 * @param $version
796 * the EndNote version of the XML file. EndNote uses one format up to version
797 * 7 then change to another format in version 8 and greater.
798 * @return
799 * The node ids of the saved nodes
800 */
801 function biblio_endnote_XML_import($xml_file, $taxo_terms = array(), $batch_proc = FALSE, $session_id = NULL, $ver = 8) {
802 global $user, $records, $rec_count, $node, $terms, $batch_proc, $nids, $session_id;
803 $terms = $taxo_terms;
804 $nids = array();
805 if (!($fp = fopen($xml_file->filepath, "r"))) {
806 drupal_set_message("could not open XML input",'error');
807 return;
808 }
809 $data = fread($fp, 2048);
810 $xml_parser = drupal_xml_parser_create($data);
811 // use case-folding so we are sure to find the tag in
812 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
813 xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, true);
814
815 module_load_include('inc', 'biblio', 'endnote'.$ver.'_parser');
816 xml_set_element_handler($xml_parser, 'en'.$ver.'_startElement', 'en'.$ver.'_endElement');
817 xml_set_character_data_handler($xml_parser, 'en'.$ver.'_characterData');
818
819 xml_parse($xml_parser, $data, feof($fp));
820 while ($data = fread($fp, 2048)){
821 // $data = fread($fp, 2048);
822 set_time_limit(30);
823 if(!xml_parse($xml_parser, $data, feof($fp))){
824 drupal_set_message(sprintf("XML error: %s at line %d",
825 xml_error_string(xml_get_error_code($xml_parser)),
826 xml_get_current_line_number($xml_parser)),'error');
827
828 }
829 }
830 xml_parser_free($xml_parser);
831 fclose($fp);
832 return (!empty($nids)) ? $nids : array();
833 }
834 /**
835 * Export data in EndNote XML format.
836 *
837 * @param $result
838 * a database pointer to a result set
839 * @param $version
840 * the EndNote version of the XML file. EndNote uses one format up to version
841 * 7 then change to another format in version 8 and greater.
842 * @return
843 * none
844 */
845 function biblio_endnote_XML_export($result, $version = 7) {
846 if ($version == 8) {
847 module_load_include('inc', 'biblio', 'endnote8_export');
848 $xml = _endnote8_XML_export($result);
849 }
850 elseif ($version == 7) {
851 module_load_include('inc', 'biblio', 'endnote7_export');
852 $xml = _endnote7_XML_export($result);
853 }
854 return $xml;
855 }
856 /**
857 * Export data in EndNote tagged format.
858 *
859 * @param $result
860 * a database pointer to a result set
861 * @return
862 * none
863 */
864 function biblio_endnote_tagged_export($node) {
865
866 $tagged = "";
867 $tagged .= "%0 ". _endnote_tagged_type_map($node->biblio_type) ."\r\n";
868 switch ($node->biblio_type) {
869 case 100 :
870 case 101 :
871 case 103 :
872 case 104 :
873 case 105 :
874 case 108 :
875 case 119 :
876 if (!empty($node->biblio_secondary_title))
877 $tagged .= "%B ". trim($node->biblio_secondary_title) ."\r\n";
878 break;
879 case 102 :
880 if (!empty($node->biblio_secondary_title))
881 $tagged .= "%J ". trim($node->biblio_secondary_title) ."\r\n";
882 break; // journal
883 }
884 if (isset($node->biblio_year) && $node->biblio_year < 9998)
885 $tagged .= "%D ". trim($node->biblio_year) ."\r\n";
886 if (!empty($node->title))
887 $tagged .= "%T ". trim($node->title) ."\r\n";
888
889 foreach ((array)$node->biblio_contributors[1] as $auth) {
890 $tagged .= "%A " . trim($auth['name']) ."\r\n";
891 }
892 foreach ((array)$node->biblio_contributors[2] as $auth) {
893 $tagged .= "%E " . trim($auth['name']) ."\r\n";
894 }
895 foreach ((array)$node->biblio_contributors[3] as $auth) {
896 $tagged .= "%Y " . trim($auth['name']) ."\r\n";
897 }
898
899 if (!empty($node->biblio_place_published))
900 $tagged .= "%C ". trim($node->biblio_place_published) ."\r\n";
901 if (!empty($node->biblio_publisher)) { $tagged .= "%I ". trim($node->biblio_publisher) ."\r\n"; }
902
903 $kw_array = array();
904 if (!empty($node->terms)){
905 foreach($node->terms as $term){
906 $kw_array[] = $term->name;
907 }
908 }
909 if (!empty($node->biblio_keywords)) {
910 foreach($node->biblio_keywords as $term){
911 $kw_array[] = $term;
912 }
913 }
914 if (!empty($kw_array)){
915 $kw_array = array_unique($kw_array);
916 foreach($kw_array as $term){
917 $tagged .= "%K ". trim($term) ."\r\n";
918 }
919 }
920 if (!empty($node->biblio_call_number))
921 $tagged .= "%L ". trim($node->biblio_call_number) ."\r\n";
922 if (!empty($node->biblio_accession_number))
923 $tagged .= "%M ". trim($node->biblio_accession_number) ."\r\n";
924 if (!empty($node->biblio_issue))
925 $tagged .= "%N ". trim($node->biblio_issue) ."\r\n";
926 if (!empty($node->biblio_pages))
927 $tagged .= "%P ". trim($node->biblio_pages) ."\r\n";
928 if (!empty($node->biblio_doi))
929 $tagged .= "%R ". trim($node->biblio_doi) ."\r\n";
930 if (!empty($node->biblio_tertiary_title))
931 $tagged .= "%S ". trim($node->biblio_tertiary_title) ."\r\n";
932 if (!empty($node->biblio_url))
933 $tagged .= "%U ". trim($node->biblio_url) ."\r\n";
934 if (!empty($node->biblio_volume))
935 $tagged .= "%V ". trim($node->biblio_volume) ."\r\n";
936 $abst = "";
937 if (!empty($node->biblio_abst_e))
938 $abst .= trim($node->biblio_abst_e);
939 if (!empty($node->biblio_abst_f))
940 $abst .= trim($node->biblio_abst_f);
941 if ($abst) {
942 $search = array("/\r/", "/\n/");
943 $replace = " ";
944 $abst = preg_replace($search, $replace, $abst);
945 $tagged .= "%X ". $abst ."\r\n";
946 }
947 if (!empty($node->biblio_notes))
948 $tagged .= "%Z ". trim($node->biblio_notes) ."\r\n";
949 if (!empty($node->biblio_edition))
950 $tagged .= "%7 ". trim($node->biblio_edition) ."\r\n";
951 if (!empty($node->biblio_date))
952 $tagged .= "%8 ". trim($node->biblio_date) ."\r\n";
953 if (!empty($node->biblio_type_of_work))
954 $tagged .= "%9 ". trim($node->biblio_type_of_work) ."\r\n";
955 if (!empty($node->biblio_isbn))
956 $tagged .= "%@ ". trim($node->biblio_isbn) ."\r\n";
957 if (!empty ($node->files) && count($node->files) && user_access('view uploaded files')) {
958 foreach($node->files as $file) {
959 $tagged .= "%> ". file_create_url($file->filepath) . "\r\n"; // insert file here.
960 }
961 }
962 $tagged .= "\r\n";
963 return $tagged;
964 }
965 function _endnote_tagged_type_map($bibliotype) {
966 static $map = array();
967 if (empty($map)) {
968 module_load_include('inc', 'biblio', 'biblio.type.mapper');
969 $map = biblio_get_type_map('tagged');
970 }
971 return ($type = array_search($bibliotype, $map)) ? $type : 'Generic'; //return the biblio type or 129 (Misc) if type not found
972 }
973 function biblio_csv_export_2($result, $bfields) {
974 // $query_biblio_fields = 'SELECT name, title FROM {biblio_fields}';
975 // $res_biblio_fields = db_query($query_biblio_fields);
976 // while ($rec = db_fetch_object($res_biblio_fields)){
977 // $bfields[$rec->name] = $rec->title;
978 // }
979 $bfields = biblio_get_db_fields('all');
980 $query_biblio_types = 'SELECT tid, name FROM {biblio_types}';
981 $res_biblio_types = db_query($query_biblio_types);
982 while ($rec = db_fetch_object($res_biblio_types)) {
983 $btypes[$rec->tid] = $rec->name;
984 }
985 switch (variable_get('biblio_csv_field_sep', 'tab')) {
986 case 'tab' :
987 $filedsep = "\t";
988 break;
989 case 'comma' :
990 $filedsep = ',';
991 break;
992 }
993 switch (variable_get('biblio_csv_text_sep', 'dquote')) {
994 case 'dquote' :
995 $textsep = '"';
996 break;
997 case 'quote' :
998 $textsep = '\'';
999 break;
1000 }
1001 $label = (variable_get('biblio_csv_col_head', 'label') == 'label' ? 1 : 0); // or 'col_name'
1002 $linebreak = variable_get('biblio_linebreak_exp', 1);
1003 while ($rec = db_fetch_object($result)) {
1004 $node_id = $rec->nid;
1005 $node_array[$node_id]['type'] = $btypes[$rec->biblio_type]; // there is no "label" for "type"
1006 $col_array['type'] = 'Type';
1007 foreach (array_keys($bfields) as $fieldname) {
1008 if (!empty ($rec-> $fieldname) && !in_array($fieldname, array (
1009 'biblio_citekey',
1010 'biblio_coins'
1011 ))) {
1012 $col_array[$fieldname] = $bfields[$fieldname]; // mark field as in use
1013 $text = strtr($rec-> $fieldname,