WIKINDX PHP Cross Reference Collaborative Wikis

Source: /core/modules/import/IMPORTBIBTEX.php - 1349 lines - 51580 bytes - Summary - Text - Print

   1  <?php
   2  /**********************************************************************************

   3  WIKINDX: Bibliographic Management system.

   4  Copyright (C)

   5  

   6  This program is free software; you can redistribute it and/or modify it under the terms

   7  of the GNU General Public License as published by the Free Software Foundation; either

   8  version 2 of the License, or (at your option) any later version.

   9  

  10  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;

  11  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  12  See the GNU General Public License for more details.

  13  

  14  You should have received a copy of the GNU General Public License along with this program;

  15  if not, write to the

  16  Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

  17  

  18  The WIKINDX Team 2012

  19  sirfragalot@users.sourceforge.net

  20  **********************************************************************************/
  21  /*****

  22  *    IMPORTBIBTEX: BibTeX import class

  23  *

  24  *****/
  25  class IMPORTBIBTEX
  26  {
  27  private $db;
  28  private $vars;
  29  private $gatekeep;
  30  private $errors;
  31  private $success;
  32  private $messages;
  33  private $session;
  34  private $import;
  35  private $template;
  36  private $form;
  37  private $html;
  38  private $badInput;
  39  private $bibConfig;
  40  private $resourceAdded = 0;
  41  private $resourceDiscarded = 0;
  42  private $resourceAddedThisRound = 0;
  43  private $resourceDiscardedThisRound = 0;
  44  private $editionNumbers;
  45  private $map;
  46  private $tag;
  47  private $parseCreator;
  48  private $monthObj;
  49  private $pages;
  50  private $parse;
  51  private $config;
  52  private $file;
  53  private $utf8;
  54  public $importFile = FALSE;
  55  private $oldTime;
  56  public $type = FALSE;
  57  private $rejectTitles = array();
  58  private $rejected = array();
  59  private $fileName = FALSE;
  60  private $fileNameStrings = FALSE;
  61  private $entries = array();
  62  private $strings = array();
  63  private $entriesLeft;
  64  private $tagId;
  65  private $keywords;
  66  private $note;
  67  private $abstract;
  68  private $url;
  69  private $month;
  70  private $day;
  71  private $thesisType = FALSE;
  72  private $howPublished;
  73  private $publisherId = FALSE;
  74  private $confPublisherId = FALSE;
  75  private $collectionId = FALSE;
  76  private $bibtexStringId = FALSE;
  77  private $customFields;
  78  private $unrecognisedFields;
  79  private $invalidFieldNames = array();
  80  private $startMonth;
  81  private $startDay;
  82  private $endMonth;
  83  private $endDay;
  84  private $resourceId;
  85  private $deleteCacheCreators = FALSE;
  86  private $deleteCachePublishers = FALSE;
  87  private $deleteCacheCollections = FALSE;
  88  private $deleteCacheKeywords = FALSE;
  89  private $badClass;
  90  private $badFunction;
  91  private $dirName;
  92  private $garbageFiles = array();
  93  private $errorMessage;
  94  private $rIds = array();
  95  
  96  // Constructor

  97  	public function __construct()
  98      {
  99          $this->db = FACTORY_DB::getInstance();
 100          $this->vars = GLOBALS::getVars();
 101          $this->gatekeep = FACTORY_GATEKEEP::getInstance();
 102          $this->session = FACTORY_SESSION::getInstance();
 103          $this->import = FACTORY_IMPORT::getInstance();
 104          $this->messages = FACTORY_MESSAGES::getInstance();
 105          $this->errors = FACTORY_ERRORS::getInstance();
 106          $this->success = FACTORY_SUCCESS::getInstance();
 107          $this->form = FACTORY_FORM::getInstance();
 108          $this->html = FACTORY_HTML::getInstance();
 109          $this->template = FACTORY_TEMPLATE::getInstance();
 110          $this->bibConfig = FACTORY_BIBTEXCONFIG::getInstance();
 111          $this->badInput = FACTORY_BADINPUT::getInstance();
 112          $this->map = FACTORY_BIBTEXMAP::getInstance();
 113  // need to use English constants for BibTeX

 114          include_once ("languages/en/CONSTANTS.php");
 115          $constants = new CONSTANTS_en();
 116          include_once ("core/miscellaneous/TAG.php");
 117          $this->tag = new TAG();
 118          $this->parseCreator = FACTORY_BIBTEXCREATORPARSE::getInstance();
 119          $this->monthObj = FACTORY_BIBTEXMONTHPARSE::getInstance();
 120          $this->pages = FACTORY_BIBTEXPAGEPARSE::getInstance();
 121          $this->parse = FACTORY_BIBTEXPARSE::getInstance();
 122          $this->config = FACTORY_CONFIG::getInstance();
 123          $this->file = FACTORY_FILE::getInstance();
 124          $this->utf8 = FACTORY_UTF8::getInstance();
 125          $constants->convertNumbers();
 126          $this->editionNumbers = array_flip($constants->cardinalToOrdinalWord());
 127          $this->parseCreator->separateInitials = TRUE;
 128          $this->db->escapeString = TRUE;
 129  // Load bibConfig arrays

 130          $this->bibConfig->bibtex();
 131  // For an import from a plug-in like ImportPubMed, this variable will be a file path

 132          $this->importFile = FALSE;
 133          $this->oldTime = time();
 134          if(isset($this->config->WIKINDX_FILES_DIR))
 135              $this->dirName = $this->config->WIKINDX_FILES_DIR;
 136          else
 137              $this->dirName = "files"; // default

 138          if(array_key_exists('type', $this->vars) && ($this->vars['type'] == 'paste'))
 139          {
 140              $this->type = 'paste';
 141              include_once ("core/modules/import/PASTEBIBTEX.php");
 142              $this->badClass = new PASTEBIBTEX();
 143              $this->badFunction = 'display';
 144          }
 145          else if(array_key_exists('type', $this->vars) && ($this->vars['type'] == 'file'))
 146          {
 147              $this->type = 'file';
 148              include_once ("core/modules/import/BIBTEXFILE.php");
 149              $this->badClass = new BIBTEXFILE();
 150              $this->badFunction = 'display';
 151          }
 152          GLOBALS::setOutputHeading($this->messages->text("heading", "bibtexImport"));
 153      }
 154  /**

 155  * stage1 - start the process

 156  * 

 157  * @author Mark Grimshaw

 158  */
 159  	public function stage1($returnPstring = FALSE)
 160      {
 161          if(!$this->importFile)
 162              $this->gatekeep->init();
 163  // if session variable 'importLock' is TRUE, user is simply reloading this form

 164          if($this->session->getVar('importLock'))
 165              $this->badInput->close($this->errors->text("done", "fileImport"), $this->badClass, $this->badFunction);
 166          $this->fileName = $this->gatherStage1();
 167          $this->parse->expandMacro = TRUE; // substitute @string values

 168          $this->parse->openBib($this->fileName);
 169          $this->parse->extractEntries();
 170          $this->parse->closeBib();
 171          list($null, $this->strings, $entries, $null2) = $this->parse->returnArrays(); // don't need preamble

 172          if(empty($entries))
 173          {
 174              $this->session->setVar('importLock', TRUE);
 175              $this->badInput->close($this->errors->text("import", "empty"), $this->badClass, $this->badFunction);
 176          }
 177          if($fields = $this->findInvalidFields($entries))
 178          {
 179              @unlink($this->fileName); // remove garbage - ignore errors

 180              GLOBALS::buildOutputString($fields);
 181              return;
 182          }
 183  // NB - we need to write data to database as UTF-8 and parse all bibTeX values for laTeX code

 184          $this->entriesLeft = $this->entries = $this->convertEntries($entries);
 185          $finalInput = $this->writeDb();
 186          $pString = $this->cleanUp($finalInput);
 187          if($returnPstring)
 188              return $pString;
 189          GLOBALS::buildOutputString($pString);
 190      }
 191  /**

 192  * stage2Invalid - following on from invalid fields having been found

 193  * 

 194  * @author Mark Grimshaw

 195  * @param string $message - optional error message

 196  */
 197  	public function stage2Invalid($message = FALSE)
 198      {
 199          $this->gatekeep->init();
 200  // if session variable 'importLock' is TRUE, user is simply reloading this form

 201          if($this->session->getVar('importLock'))
 202              $this->badInput->close($this->errors->text("done", "fileImport"), $this->badClass, $this->badFunction);
 203          if(!is_file($this->session->getVar('import_FileNameEntries')))
 204              $this->badInput->close($this->errors->text("file", "read", $this->dirName . '/' . 
 205              $this->session->getVar('import_FileNameEntries')), $this->badClass, $this->badFunction);
 206          $this->fileName = fopen($this->session->getVar('import_FileNameEntries'), 'r');
 207          $this->garbageFiles[$this->session->getVar('import_FileNameEntries')] = FALSE;
 208          if(!feof($this->fileName))
 209              $this->entries = $this->convertEntries(unserialize(base64_decode(trim(fgets($this->fileName)))));
 210          fclose($this->fileName);
 211          if($this->session->getVar('import_FileNameStrings'))
 212          {
 213              if(!is_file($this->session->getVar('import_FileNameStrings')))
 214                  $this->badInput->close($this->errors->text("file", "read", $this->session->getVar('import_FileNameStrings')), 
 215                  $this->badClass, $this->badFunction);
 216              $this->fileNameStrings = fopen($this->session->getVar('import_FileNameStrings'),'r');
 217              $this->garbageFiles[$this->session->getVar('import_FileNameStrings')] = FALSE;
 218              if(!feof($this->fileNameStrings))
 219                  $this->strings = $this->convertEntries(unserialize(base64_decode(trim(fgets($this->fileNameStrings)))));
 220              fclose($this->fileNameStrings);
 221          }
 222          if(empty($this->entries))
 223          {
 224              $this->session->setVar('importLock', TRUE);
 225              $this->badInput->close($this->errors->text("import", "empty"), $this->badClass, $this->badFunction);
 226          }
 227          list($error, $this->customFields, $this->unrecognisedFields) = $this->import->getUnrecognisedFields($this);
 228          if($error)
 229              $this->badInput->close($error, $this->badClass, $this->badFunction);
 230  // NB - we need to write data to database as UTF-8 and parse all bibTeX values for laTeX code

 231          $this->entriesLeft = $this->entries;
 232          $finalInput = $this->writeDb();
 233          $pString = $this->errorMessage ? $this->errorMessage : '';
 234          $pString .= $this->cleanUp($finalInput);
 235          GLOBALS::buildOutputString($pString);
 236      }
 237  /**

 238  * Continue an import

 239  *

 240  */
 241  	public function continueImport()
 242      {
 243  // Restore session

 244          if($this->session->issetVar("import_RejectTitles"))
 245              $this->rejectTitles = unserialize(base64_decode($this->session->getVar("import_RejectTitles")));
 246          else
 247              $this->rejectTitles = array();
 248          if($this->session->issetVar("import_ResourceIds"))
 249              $this->rIds = unserialize(base64_decode($this->session->getVar("import_ResourceIds")));
 250          else
 251              $this->rIds = array();
 252  // Number added so far

 253          $this->resourceAdded = $this->session->getVar("import_ResourceAdded");
 254  // Number discarded so far

 255          $this->resourceDiscarded = $this->session->getVar("import_ResourceDiscarded");
 256  // tag ID

 257          if($this->session->issetVar("import_TagID"))
 258              $this->tagId = $this->session->getVar("import_TagID");
 259  // bibtexString ID

 260          if($this->session->issetVar("import_BibtexStringID"))
 261              $this->bibtexStringId = $this->session->getVar("import_BibtexStringID");
 262          $this->entriesLeft = $this->entries = 
 263              unserialize(base64_decode($this->session->getVar("import_Entries")));
 264          $this->garbageFiles = unserialize(base64_decode($this->session->getVar("import_GarbageFiles")));
 265          if($this->session->issetVar("import_UnrecognisedFields"))
 266          {
 267              $this->unrecognisedFields = 
 268                  unserialize(base64_decode($this->session->getVar("import_UnrecognisedFields")));
 269              $this->customFields = unserialize(base64_decode($this->session->getVar("import_CustomFields")));
 270              $this->vars = unserialize(base64_decode($this->session->getVar("import_ThisVars")));
 271          }
 272          $finalInput = $this->writeDb(TRUE);
 273          $pString = $this->errorMessage ? $this->errorMessage : '';
 274          $pString .= $this->cleanUp($finalInput);
 275          GLOBALS::buildOutputString($pString);
 276      }
 277  /**

 278  * Garbage clean up and intermediate session saving when importing in chunks

 279  *

 280  */
 281  	private function cleanUp($finalInput)
 282      {
 283  // update total no. resources in summary table

 284          $recordset = $this->db->select('database_summary', 'databasesummaryTotalResources');
 285          $totalResources = $this->db->fetchOne($recordset) + $this->resourceAddedThisRound;
 286          $this->db->update('database_summary', array('databasesummaryTotalResources' => $totalResources));
 287          if($finalInput)
 288          {
 289              $rCommon = FACTORY_RESOURCECOMMON::getInstance();
 290              $listCommon = FACTORY_LISTCOMMON::getInstance();
 291              $this->deleteCaches();
 292              $this->import->tidyTables();
 293              foreach($this->garbageFiles as $fileName => $null)
 294                  unlink($fileName); // remove garbage - ignore errors

 295              $pString = $this->html->p($this->success->text("bibtexImport"));
 296              $pString .= $this->html->p($this->messages->text("import", "added", " " . $this->resourceAdded));
 297              $pString .= $this->import->printDuplicates($this->resourceDiscarded, $this->rejectTitles);
 298              $pString .= $this->html->hr();
 299              if(!empty($this->rIds) && (sizeof($this->rIds) <= 50))
 300              {
 301                  $sql = $rCommon->getResource($this->rIds, FALSE, FALSE, FALSE, FALSE, TRUE);
 302                  $listCommon->display($sql, 'list');
 303              }
 304              $this->session->delVar('sql_LastMulti');
 305              $this->session->setVar('importLock', TRUE);
 306              if($this->resourceAdded)
 307              {
 308                  include_once ("core/modules/email/EMAIL.php");
 309                  $email = new EMAIL();
 310                  $email->notify(FALSE, TRUE);
 311              }
 312          }
 313          else
 314          {
 315  // Store temporary session variables

 316  // Number added

 317              $this->session->setVar("import_ResourceAdded", $this->resourceAdded);
 318  // Number of rejects

 319              $this->session->setVar("import_ResourceDiscarded", $this->resourceDiscarded);
 320  // tag ID

 321              if(isset($this->tagId))
 322                  $this->session->setVar("import_TagID", $this->tagId);
 323  // bibtexString ID

 324              if(isset($this->bibtexStringId))
 325                  $this->session->setVar("import_BibtexStringID", $this->bibtexStringId);
 326  // Resource IDs

 327              $this->session->setVar("import_ResourceIds", base64_encode(serialize($this->rIds)));
 328  // Remaining entries

 329              $this->session->setVar("import_Entries", base64_encode(serialize($this->entriesLeft)));
 330  // Rejected titles

 331              if(!empty($this->rejectTitles))
 332                  $this->session->setVar("import_RejectTitles", base64_encode(serialize($this->rejectTitles)));
 333  // garbage files

 334              $this->session->setVar("import_GarbageFiles", base64_encode(serialize($this->garbageFiles)));
 335  // Unrecognised field mapping

 336              if(isset($this->unrecognisedFields))
 337              {
 338                  $this->session->setVar("import_UnrecognisedFields", 
 339                      base64_encode(serialize($this->unrecognisedFields)));
 340  // Custom field mapping

 341                  if(isset($this->customFields))
 342                      $this->session->setVar("import_CustomFields", base64_encode(serialize($this->customFields)));
 343  // $this->vars

 344                  $this->session->setVar("import_ThisVars", base64_encode(serialize($this->vars)));
 345              }
 346              $remainder = sizeof($this->entriesLeft);
 347              $pString = $this->html->p($this->messages->text("import", "executionTimeExceeded", 
 348                  ini_get("max_execution_time")));
 349              $pString .= $this->html->p($this->messages->text("import", "addedChunk", " " . 
 350                  $this->resourceAddedThisRound));
 351              $pString .= $this->html->p("$remainder entries remaining.");
 352              $pString .= $this->form->formHeader("import_IMPORTBIBTEX_CORE");
 353              $pString .= $this->form->hidden('method', 'continueImport');
 354              $pString .= $this->html->p($this->form->formSubmit("Continue"));
 355              $pString .= $this->form->formEnd();
 356          }
 357          return $pString;
 358      }
 359  /**

 360  * find unrecognised field names

 361  * 

 362  * @author Mark Grimshaw

 363  */
 364  	private function findInvalidFields($entries)
 365      {
 366          $inputTypes = array();
 367          $this->day = $this->month = FALSE;
 368          foreach($entries as $entry)
 369          {
 370              list($this->url, $null) = $this->grabHowPublished($entry);
 371              $type = $this->getType($entry);
 372              foreach($entry as $field => $value)
 373              {
 374                  if($field == 'bibtexEntryType')
 375                  {
 376                      $inputTypes[] = $value;
 377                      continue;
 378                  }
 379                  if($field == 'bibtexCitation')
 380                      continue;
 381                  if(($field == 'annote') && !array_key_exists('note', $entry))
 382                      continue;
 383                  if((array_search($field, $this->map->validFields) === FALSE) && 
 384                      (array_search($field, $this->invalidFieldNames) === FALSE))
 385                      $this->invalidFieldNames[] = $field;
 386              }
 387          }
 388          if(!empty($this->invalidFieldNames)) // prompt to map field names
 389          {
 390              list($error, $string) = $this->import->promptFieldNames($entries, $inputTypes, $this->map, 
 391                  $this->invalidFieldNames, $this->strings, $this);
 392              if($error)
 393                  $this->badInput->close($error, $this->badClass, $this->badFunction);
 394              else
 395                  return $string;
 396          }
 397          return FALSE; // continue with import.

 398      }
 399  /*

 400  * writeDb - write input to the database.

 401  * 

 402  * @author Mark Grimshaw

 403  */
 404  	private function writeDb($continue = FALSE)
 405      {
 406          $tagWritten = $stringWritten = FALSE;
 407          if(!$continue)
 408              $this->tagId = FALSE;
 409          if($this->session->getVar("setup_Superadmin") || $this->session->getVar("setup_ImportBib"))
 410              $pasteLimit = FALSE;
 411          else
 412              $pasteLimit = TRUE;
 413          $finalInput = TRUE;
 414          foreach($this->entries as $key => $entry)
 415          {
 416              unset($this->entriesLeft[$key]);
 417              $authors = $editors = array();
 418  // For a user cut 'n' pasting. Admin is unlimited.

 419              if($pasteLimit && ($this->resourceAdded >= $this->session->getVar("setup_MaxPaste")))
 420                  break;
 421              $this->keywords = $this->note = $this->abstract = $this->url = $this->month = $this->day = FALSE;
 422              $wkType = $this->getType($entry);
 423              $noSort = $title = $subtitle = FALSE;
 424  // inbook type with a chapter field that is numeric, bibtex field 'chapter' is wikindx's title, bibtex field 'title' is wikindx collectionTitle

 425              if(($wkType == 'book_chapter') && trim($entry['chapter']))
 426                  $title = trim($entry['chapter']);
 427  // This was originally bibtex @inbook, because the bibtex field chapter was nonnumeric, it's been converted to wikindx book_article.

 428  // bibtex field 'chapter' is wikindx's title, bibtex field 'title' is wikindx collectionTitle

 429              else if(($wkType == 'book_article') && array_key_exists('chapter', $entry) && trim($entry['chapter']))
 430                  list($noSort, $title, $subtitle) = $this->import->splitTitle($entry['chapter']);
 431              else if(array_key_exists('title', $entry) && trim($entry['title']))
 432                  list($noSort, $title, $subtitle) = $this->import->splitTitle($entry['title']);
 433  // ignore wikindx resource type book_chapter when checking duplicates

 434              if(!$title || (($wkType != 'book_chapter') && $this->import->checkDuplicates($noSort, $title, $subtitle, $wkType)))
 435              {
 436                  $rejectTitle = $title ? $title . "." : $title;
 437                  if(array_key_exists('author', $entry) && $entry['author'])
 438                      $rejectTitle = $entry['bibtexEntryType'] . ': ' . trim($entry['author']) . " " . $rejectTitle;
 439                  $this->rejectTitles[] = $rejectTitle;
 440                  $this->resourceDiscarded++;
 441                  $this->resourceDiscardedThisRound++;
 442                  continue;
 443              }
 444              if((array_search('author', $this->map->{$wkType}['resource_creator'])) && 
 445                  array_key_exists('author', $entry) && $entry['author'])
 446                  $authors = $this->parseCreator->parse($entry['author']);
 447              if((array_search('editor', $this->map->{$wkType}['resource_creator'])) && 
 448                  array_key_exists('editor', $entry) && $entry['editor'])
 449                  $editors = $this->parseCreator->parse($entry['editor']);
 450  // bibTeX's 'article' type can be wikindx's journal_article, magazine_article or newspaper_article.  If there is no 'month' field, 

 451  // we assume the first, if there's 'month' but no day part of that field, we assume the second and, if there's a day part, assume 

 452  // the third. So, before we can write the resource table and its `type` field, we need to query any month field in the import.

 453              list($this->startMonth, $this->startDay, $this->endMonth, $this->endDay) = $this->grabMonth($entry);
 454  // A bibtex type with a howpublished field containing a URL is mapped to wikindx's web_article type.

 455              list($this->url, $this->howPublished) = $this->grabHowPublished($entry);
 456              list($this->rejected, $entry, $custom) = $this->reject($entry, $wkType);
 457              $this->resourceId = $this->writeResourceTable($noSort, $title, $subtitle, $entry, $wkType);
 458              $this->rIds[] = $addedResourceIds[] = $this->resourceId;
 459  // add any import tag and get tag auto ID.  We write it here after the resource table in case we forbid duplicates and all 

 460  // bibtex entries are duplicates - we don't want an empty tag in the WKX_tag table.  tag auto ID is written to resource_misc

 461              if(!$continue)
 462              {
 463                  if(!$tagWritten)
 464                  {
 465                      $this->tagId = $this->import->writeTagTable();
 466                      $tagWritten = TRUE;
 467                  }
 468                  if(!$stringWritten)
 469                  {
 470                      $this->writeBibtexStringTable();
 471                      $stringWritten = TRUE;
 472                  }
 473              }
 474              $this->writeCreatorTable($authors, $editors, $wkType);
 475              $this->writePublisherTable($entry, $wkType);
 476              $this->writeCollectionTable($entry, $wkType);
 477              $this->writeResourceMiscTable($entry, $wkType);
 478              $this->writeResourceYearTable($entry, $wkType);
 479              $this->writeResourcePageTable($entry, $wkType);
 480              $this->writeResourcetextTable($entry);
 481              $this->writeResourceKeywordTable($entry);
 482              $this->writeResourceCustomTable($custom);
 483              $this->import->writeResourcecategoryTable($this->session->getVar('import_Categories'));
 484              $this->import->writeResourceTimestampTable();
 485              $this->import->writeImportrawTable($this->rejected, $this->bibtexStringId);
 486              $this->import->writeUserbibliographyresourceTable($this->session->getVar('import_BibId'));
 487              $this->import->writeBibtexKey();
 488              $this->resourceAdded++;
 489              $this->resourceAddedThisRound++;
 490  // Check we have more than 4 seconds buffer before max_execution_time times out.

 491              if((time() - $this->oldTime) >= (ini_get("max_execution_time") - 4))
 492              {
 493                  $finalInput = FALSE;
 494                  break;
 495              }
 496          }
 497          return $finalInput;
 498      }
 499  /**

 500  * Delete caches if required.  Must be deleted if various creators, publishers etc. have been added with this import

 501  */
 502  	private function deleteCaches()
 503      {
 504          if($this->deleteCacheCreators)
 505          {
 506  // remove cache files for creators

 507              $this->db->deleteCache('cacheResourceCreators');
 508              $this->db->deleteCache('cacheMetadataCreators');
 509          }
 510          if($this->deleteCachePublishers)
 511          {
 512  // remove cache files for publishers

 513              $this->db->deleteCache('cacheResourcePublishers');
 514              $this->db->deleteCache('cacheMetadataPublishers');
 515              $this->db->deleteCache('cacheConferenceOrganisers');
 516          }
 517          if($this->deleteCacheCollections)
 518          {
 519  // remove cache files for collections

 520              $this->db->deleteCache('cacheResourceCollections');
 521              $this->db->deleteCache('cacheMetadataCollections');
 522              $this->db->deleteCache('cacheResourceCollectionTitles');
 523              $this->db->deleteCache('cacheResourceCollectionShorts');
 524          }
 525          if($this->deleteCacheKeywords)
 526          {
 527  // remove cache files for keywords

 528              $this->db->deleteCache('cacheResourceKeywords');
 529              $this->db->deleteCache('cacheMetadataKeywords');
 530              $this->db->deleteCache('cacheQuoteKeywords');
 531              $this->db->deleteCache('cacheParaphraseKeywords');
 532              $this->db->deleteCache('cacheMusingKeywords');
 533              $this->db->deleteCache('cacheKeywords');
 534          }
 535      }
 536  /**

 537  * reject -- gather rejected fields that wikindx does not recognise for that type and remove from $entry

 538  * @author Mark Grimshaw

 539  *

 540  * @param $entry - assoc array of one entry for import.

 541  * @return $wkType - the WIKINDX resource type for this bibtex entry

 542  * @return $rejected - array of rejected field and their values (with bibTeX delimiters added back in)

 543  * @return $newEntry - $entry with $rejected elements removed

 544  */
 545  	private function reject($entry, $wkType)
 546      {
 547          $rejectedEntry = FALSE;
 548          $index = 0;
 549          $custom = array();
 550          foreach($entry as $key => $value)
 551          {
 552              if(($key == 'bibtexEntryType') || 
 553              ($key == 'howpublished') || ($key == 'abstract') || ($key == 'keywords'))
 554              {
 555                  $newEntry[$key] = $value;
 556                  continue;
 557              }
 558              if($key == 'bibtexCitation')
 559              {
 560                  $rejected['citation'] = trim($value);
 561                  $rejectedEntry = TRUE;
 562                  continue;
 563              }
 564              if($key == 'note') // Use 'note' in preference to 'annote'
 565              {
 566                  $newEntry[$key] = $value;
 567                  continue;
 568              }
 569              if(($key == 'annote') && !array_key_exists('note', $entry)) // Use 'note' in preference to 'annote'
 570              {
 571                  $newEntry[$key] = $value;
 572                  continue;
 573              }
 574              if(($key == 'month') && $this->url && ($wkType == 'web_article'))
 575                  continue;
 576              if(array_search($key, $this->map->{$wkType}['possible']) !== FALSE)
 577              {
 578                  if(!array_key_exists($key, $newEntry) || !array_key_exists('import_Precedence', $this->vars))
 579                      $newEntry[$key] = $value;
 580              }
 581  // Do we map unrecognised fields?

 582              if(!empty($this->unrecognisedFields) && array_search($key, $this->unrecognisedFields) !== FALSE)
 583              {
 584                  $importKey = 'import_' . $key;
 585                  if(array_key_exists($importKey, $this->vars) && 
 586                      array_search($this->vars[$importKey], $this->map->{$wkType}['possible']) !== FALSE)
 587                  {
 588  // Do unrecognised fields take precedence?

 589                      if(array_key_exists('import_Precedence', $this->vars))
 590                      {
 591                          $newEntry[$this->vars[$importKey]] = $value;
 592                          continue;
 593                      }
 594                      if(!array_key_exists($this->vars[$importKey], $newEntry))
 595                      {
 596                          $newEntry[$this->vars[$importKey]] = $value;
 597                          continue;
 598                      }
 599                  }
 600              }
 601              if(array_key_exists($key, $newEntry))
 602                  continue;
 603              if(!empty($this->customFields) && array_key_exists($key, $this->customFields))
 604              {
 605                  $custom[$key] = $value;
 606                  continue;
 607              }
 608  // If we get here, we have a bibtex field and value that are not recognised by wikindx. If this is not to be mapped, we 

 609  // need to store this in case user has requested that unused fields are also stored in the database.

 610  // Return any @STRING substitution in $value back to original state

 611              $rejectedEntry = TRUE;
 612  // Do @string substitutions

 613              if(!empty($this->strings) && ($strKey = array_search($value, $this->strings)))
 614                  $rejected[$key] = $strKey;
 615  // No substitution so return quoted

 616              else
 617                  $rejected[$key] = "\"" . $value . "\"";
 618          }
 619          if(!$rejectedEntry)
 620              return array(FALSE, $newEntry, $custom);
 621          return array($rejected, $newEntry, $custom);
 622      }
 623  /*

 624  * getType - figure out what wikindx type this entry is

 625  * @author Mark Grimshaw

 626  *

 627  * @param $entry - assoc array of one entry for import.

 628  * @return $wkType - the WIKINDX resource type for this bibtex entry

 629  */
 630  	function getType($entry)
 631      {
 632          if($entry['bibtexEntryType'] == 'article')
 633          {
 634              if($this->day)
 635                  $wkType = 'newspaper_article';
 636              else if($this->month)
 637                  $wkType = 'magazine_article';
 638              else // no day or month
 639                  $wkType = 'journal_article';
 640          }
 641          else if(($entry['bibtexEntryType'] == 'misc') && $this->url)
 642              $wkType = 'web_article';
 643          else if($entry['bibtexEntryType'] == 'misc')
 644              $wkType = 'miscellaneous';
 645          else if($entry['bibtexEntryType'] == 'book')
 646              $wkType = 'book';
 647          else if($entry['bibtexEntryType'] == 'techreport')
 648              $wkType = 'report';
 649          else if($entry['bibtexEntryType'] == 'patent')
 650              $wkType = 'patent';
 651          else if($entry['bibtexEntryType'] == 'unpublished')
 652              $wkType = 'unpublished';
 653          else if($entry['bibtexEntryType'] == 'mastersthesis')
 654          {
 655              $wkType = 'thesis';
 656              $this->thesisType = "master's";
 657          }
 658          else if($entry['bibtexEntryType'] == 'phdthesis')
 659          {
 660              $wkType = 'thesis';
 661              $this->thesisType = "PhD";
 662          }
 663          else if(($entry['bibtexEntryType'] == 'conference') ||
 664              ($entry['bibtexEntryType'] == 'inproceedings'))
 665              $wkType = 'proceedings_article';
 666  // inbook type with a chapter field that is numeric, bibtex field 'chapter' is wikindx's title, bibtex field 'title' is wikindx collectionTitle

 667          else if(($entry['bibtexEntryType'] == 'inbook') && array_key_exists('chapter', $entry) &&
 668              is_numeric($entry['chapter']))
 669              $wkType = 'book_chapter';
 670  // incorrect bibtex but we allow it anyhow making it a wikindx book_article type

 671          else if(($entry['bibtexEntryType'] == 'inbook') && array_key_exists('chapter', $entry))
 672              $wkType = 'book_article';
 673          else if(($entry['bibtexEntryType'] == 'incollection') || 
 674              ($entry['bibtexEntryType'] == 'inbook'))
 675              $wkType = 'book_article';
 676          else if(($entry['bibtexEntryType'] == 'collection') ||
 677              ($entry['bibtexEntryType'] == 'proceedings'))
 678              $wkType = 'proceedings';
 679          else if(!$wkType = array_search($entry['bibtexEntryType'], $this->map->types))
 680              $wkType = 'miscellaneous'; // everything else

 681          return $wkType;
 682      }
 683  /*

 684  * writeResourceTable - write WKX_resource table and get lastAutoId

 685  * @author Mark Grimshaw

 686  *

 687  * @param $entry - assoc array of one entry for import.

 688  * @param $wkType - the WIKINDX resource type for this bibtex entry

 689  * @return autoId

 690  */
 691  	private function writeResourceTable($noSort, $title, $subtitle, $entry, $wkType)
 692      {
 693  // bibTeX has no way of saying whether a thesis is a thesis or a dissertation so here we force it to 'thesis'.

 694          if($wkType == 'thesis')
 695          {
 696              $fields[] = 'resourceField2';
 697              $values[] = 'thesis';
 698          }
 699          $fields[] = 'resourceType';
 700          $values[] = $wkType;
 701          $fields[] = 'resourceTitle';
 702          $values[] = $title;
 703          $titleSort = $title;
 704          if($noSort)
 705          {
 706              $fields[] = 'resourceNoSort';
 707              $values[] = $noSort;
 708          }
 709          if($subtitle)
 710          {
 711              $fields[] = 'resourceSubtitle';
 712              $values[] = $subtitle;
 713              $titleSort .= ' ' . $subtitle;
 714          }
 715          $fields[] = 'resourceTitleSort';
 716          $values[] = str_replace('{', '', str_replace('}', '', $titleSort));
 717          if($this->thesisType)
 718          {
 719              $fields[] = 'resourceField1';
 720              $values[] = $this->thesisType;
 721              $this->thesisType = FALSE;
 722          }
 723          if(($wkType == 'miscellaneous') && $this->howPublished)
 724          {
 725              $fields[] = $this->map->miscellaneous['howpublished'];
 726              $values[] = $this->howPublished;
 727          }
 728          foreach($entry as $bibField => $bibValue)
 729          {
 730  // ISBN, ISSN and URL are uppercase in BIBTEXMAP but everything in $entry is lowercase

 731              if(($bibField == 'isbn') || ($bibField == 'issn') || ($bibField == 'doi'))
 732                  $bibField = strtoupper($bibField);
 733              if($wkField = array_search($bibField, $this->map->{$wkType}['resource']))
 734              {
 735                  $fields[] = $wkField;
 736                  $values[] = $bibValue;
 737              }
 738          }
 739          return $this->import->writeResourceTable($fields, $values);
 740      }
 741  /*

 742  * writeCreatorTable - write creator table and get lastAutoId

 743  * @author Mark Grimshaw

 744  *

 745  * @param $creators - assoc array of creators for one entry

 746  * @return comma-separated list of creator IDs ready for insertion into WKX_resource_creator table.

 747  */
 748  	private function writeCreatorTable($authors, $editors, $wkType)
 749      {
 750          $index = 1;
 751          $creatorArray = array();
 752          foreach($authors as $array)
 753          {
 754              if($cField = array_search('author', $this->map->{$wkType}['resource_creator']))
 755              {
 756                  $creatorArray[$cField][$index]['prefix'] = $array[4];
 757                  $creatorArray[$cField][$index]['surname'] = $array[2] . ' ' . $array[3];
 758                  $creatorArray[$cField][$index]['firstname'] = $array[0];
 759                  $creatorArray[$cField][$index]['initials'] = $array[1];
 760                  ++$index;
 761              }
 762          }
 763          $index = 1;
 764          foreach($editors as $array)
 765          {
 766              if($cField = array_search('editor', $this->map->{$wkType}['resource_creator']))
 767              {
 768                  $creatorArray[$cField][$index]['prefix'] = $array[4];
 769                  $creatorArray[$cField][$index]['surname'] = $array[2] . ' ' . $array[3];
 770                  $creatorArray[$cField][$index]['firstname'] = $array[0];
 771                  $creatorArray[$cField][$index]['initials'] = $array[1];
 772                  ++$index;
 773              }
 774          }
 775          if(!empty($creatorArray))
 776              $this->deleteCacheCreators = TRUE;
 777  // NB, even if array is empty, we need to write empty row to resource_creator

 778          $this->import->writeCreatorTables($creatorArray);
 779      }
 780  /**

 781  * writeCollectionTable - write WKX_collection table

 782  * @author Mark Grimshaw

 783  *

 784  * The only input from bibtex that can be a wikindx 'collection' is the 'journal' field or, for @inbook, 

 785  * the 'booktitle' field.

 786  *

 787  * @param $entry - assoc array of one entry for import.

 788  * @param $wkType - the WIKINDX resource type for this bibtex entry

 789  */
 790  	private function writeCollectionTable($entry, $wkType)
 791      {
 792          $title = $short = FALSE;
 793  // inbook type with a chapter field that is numeric, bibtex field 'chapter' is wikindx's title, bibtex field 'title' is wikindx collectionTitle

 794          if($wkType == 'book_chapter')
 795              $title = trim($entry['title']);
 796  // This was originally bibtex @inbook, because the bibtex field chapter was nonnumeric, it's been converted to wikindx book_article.

 797  // bibtex field 'chapter' is wikindx's title, bibtex field 'title' is wikindx collectionTitle

 798          else if(($wkType == 'book_article') && array_key_exists('chapter', $entry))
 799              $title = trim($entry['title']);
 800          else if(($wkType == 'book_article') && !array_key_exists('booktitle', $entry))
 801              return;
 802          else if(array_key_exists('booktitle', $entry))
 803              $title = trim($entry['booktitle']);
 804          if(!$title && !array_key_exists('journal', $entry))
 805              return;
 806          else if(!$title && array_key_exists('journal', $entry))
 807              $title = trim($entry['journal']);
 808          if(!$title)
 809              return;
 810          if(!empty($this->strings))
 811              $short = array_search($title, $this->strings);
 812          $this->collectionId = $this->import->writeCollectionTable($title, $short, $wkType);
 813          $this->deleteCacheCollections = TRUE;
 814      }
 815  /**

 816  * writePublisherTable - write WKX_publisher table

 817  * @author Mark Grimshaw

 818  *

 819  * @param $entry - assoc array of one entry for import.

 820  * @param $wkType - the WIKINDX resource type for this bibtex entry

 821  */
 822  	private function writePublisherTable($entry, $wkType)
 823      {
 824          $organization = $publisherName = $publisherLocation = $conferenceLocation = FALSE;
 825          if(array_key_exists('publisher', $entry))
 826              $publisherName = trim($entry['publisher']);
 827          if(array_key_exists('organization', $entry) && ($wkType != 'proceedings_article'))
 828              $publisherName = trim($entry['organization']);
 829          else if(array_key_exists('organization', $entry))
 830              $organization = trim($entry['organization']);
 831          else if(array_key_exists('school', $entry))
 832              $publisherName = trim($entry['school']);
 833          else if(array_key_exists('institution', $entry))
 834              $publisherName = trim($entry['institution']);
 835          if(!$organization && !$publisherName)
 836              return;
 837          if(array_key_exists('address', $entry) && ($wkType != 'proceedings_article'))
 838              $publisherLocation = trim($entry['address']);
 839          else if(array_key_exists('address', $entry))
 840              $conferenceLocation = trim($entry['address']);
 841          if(array_key_exists('location', $entry))
 842          {
 843              if($wkType == 'proceedings_article')
 844                  $conferenceLocation = trim($entry['location']);
 845              else
 846                  $publisherLocation = trim($entry['location']);
 847          }
 848          if($wkType == 'proceedings_article')
 849          {
 850              $this->publisherId = $this->import->writePublisherTable($organization, $conferenceLocation, $wkType);
 851              $this->confPublisherId = $this->import->writePublisherTable($publisherName, $publisherLocation, $wkType);
 852          }
 853          else
 854              $this->publisherId = $this->import->writePublisherTable($publisherName, $publisherLocation, $wkType);
 855          $this->deleteCachePublishers = TRUE;
 856      }
 857  /*

 858  * writeResourceMiscTable - write WKX_resource_misc table

 859  * @author Mark Grimshaw

 860  *

 861  * @param $entry - assoc array of one entry for import.

 862  * @param $wkType - the WIKINDX resource type for this bibtex entry

 863  */
 864  	function writeResourceMiscTable($entry, $wkType)
 865      {
 866          foreach($entry as $bibField => $bibValue)
 867          {
 868              if($wkField = array_search($bibField, $this->map->{$wkType}['resource_misc']))
 869              {
 870                  $fields[] = $wkField;
 871                  $values[] = $bibValue;
 872              }
 873          }
 874          if($this->collectionId)
 875          {
 876              $fields[] = 'resourcemiscCollection';
 877              $values[] = $this->collectionId;
 878              $this->collectionId = FALSE;
 879          }
 880          if($this->publisherId)
 881          {
 882              $fields[] = 'resourcemiscPublisher';
 883              $values[] = $this->publisherId;
 884              $this->publisherId = FALSE;
 885          }
 886          if($this->confPublisherId)
 887          {
 888              $fields[] = "resourcemiscField1";
 889              $values[] = $this->confPublisherId;
 890              $this->confPublisherId = FALSE;
 891          }
 892          if($this->tagId)
 893          {
 894              $fields[] = 'resourcemiscTag';
 895              $values[] = $this->tagId;
 896          }
 897          if(($wkType == 'newspaper_article') || ($wkType == 'magazine_article') || 
 898              ($wkType == 'proceedings_article') || ($wkType == 'proceedings') || 
 899              ($wkType == 'journal_article') || ($this->url && ($wkType == 'web_article')))
 900          {
 901              if($this->startMonth)
 902              {
 903                  $fields[] = 'resourcemiscField3';
 904                  $values[] = $this->startMonth;
 905              }
 906              if($this->startDay)
 907              {
 908                  $fields[] = 'resourcemiscField2';
 909                  $values[] = $this->startDay;
 910              }
 911          }
 912          if(($wkType == 'proceedings_article') || ($wkType == 'proceedings') || ($wkType == 'magazine_article'))
 913          {
 914              if($this->endMonth)
 915              {
 916                  $fields[] = 'resourcemiscField6';
 917                  $values[] = $this->endMonth;
 918              }
 919              if($this->endDay)
 920              {
 921                  $fields[] = 'resourcemiscField5';
 922                  $values[] = $this->endDay;
 923              }
 924          }
 925          if((($wkType == 'book') || ($wkType == 'thesis')) && ($bibField == 'pages') && is_int($bibValue))
 926          {
 927              $fields[] = 'resourcemiscField6';
 928              $values[] = $bibValue;
 929          }
 930          $fields[] = 'resourcemiscAddUserIdResource';
 931          $values[] = $this->session->getVar("setup_UserId");
 932          $this->import->writeResourcemiscTable($fields, $values);
 933      }
 934  /*

 935  * writeResourceYearTable - write WKX_resource_year table

 936  * @author Mark Grimshaw

 937  *

 938  * @param $entry - assoc array of one entry for import.

 939  * @param $wkType - the WIKINDX resource type for this bibtex entry

 940  */
 941  	private function writeResourceYearTable($entry, $wkType)
 942      {
 943          foreach($entry as $bibField => $bibValue)
 944          {
 945              if($wkField = array_search($bibField, $this->map->{$wkType}['resource_year']))
 946              {
 947                  $fields[] = $wkField;
 948                  $values[] = $bibValue;
 949              }
 950          }
 951          if(!isset($fields))
 952              return;
 953          $this->import->writeYearTable($fields, $values);
 954      }
 955  /*

 956  * writeResourcePageTable - write WKX_resource_page table

 957  * @author Mark Grimshaw

 958  *

 959  * @param $entry - assoc array of one entry for import.

 960  */
 961  	private function writeResourcePageTable($entry, $wkType)
 962      {
 963          if(($wkType == 'book') || ($wkType == 'thesis'))
 964              return; // numPages written in miscellaneous table.

 965          if(!array_key_exists('pages', $entry))
 966              return;
 967          list($pageStart, $pageEnd) = $this->pages->init($entry['pages']);
 968          if($pageStart)
 969          {
 970              $fields[] = 'resourcepagePageStart';
 971              $values[] = $pageStart;
 972          }
 973          if($pageEnd)
 974          {
 975              $fields[] = 'resourcepagePageEnd';
 976              $values[] = $pageEnd;
 977          }
 978          if(!isset($fields))
 979              return;
 980          $this->import->writePageTable($fields, $values);
 981      }
 982  /*

 983  * writeResourceNoteTable - write WKX_resource_note table

 984  * @author Mark Grimshaw

 985  *

 986  * @param $entry - assoc array of one entry for import.

 987  */
 988  	private function writeResourcetextTable($entry)
 989      {
 990          $notes = $abstract = FALSE;
 991          if(array_key_exists('note', $entry))
 992              $notes = $entry['note'];
 993          else if(array_key_exists('annote', $entry))
 994              $notes = $entry['annote'];
 995          if(array_key_exists('abstract', $entry))
 996              $abstract = $entry['abstract'];
 997          if(!$notes && !$abstract && !$this->url)
 998              return;
 999          $this->import->writeResourcetextTable($notes, $abstract, $this->url);
1000      }
1001  /*

1002  * writeResourceKeywordTable - write WKX_resource_keyword table

1003  * @author Mark Grimshaw

1004  *

1005  * @param $entry - assoc array of one entry for import.

1006  */
1007  	private function writeResourceKeywordTable($entry)
1008      {
1009          if(!array_key_exists('keywords', $entry))
1010              return;
1011          if(!array_key_exists('import_KeywordSeparator', $this->vars))
1012              $separator = '1'; // default semicolon

1013          else
1014              $separator = $this->vars['import_KeywordSeparator'];
1015          if($separator == 0)
1016              $keywords = preg_split("/,/", trim($entry['keywords']));
1017          else if($separator == 1)
1018              $keywords = preg_split("/;/", trim($entry['keywords']));
1019          else if($separator == 2)
1020              $keywords = preg_split("/;|,/", trim($entry['keywords']));
1021          else
1022              $keywords = preg_split("/ /", trim($entry['keywords']));
1023          foreach($keywords as $keyword)
1024          {
1025              $keyword = trim($keyword);
1026              if(!$keyword)
1027                  continue;
1028              $tempK[] = $keyword;
1029          }
1030          if(!isset($tempK))
1031              return;
1032          $keywords = array_unique($tempK);
1033          if(array_key_exists('keywords', $entry) && trim($entry['keywords']))
1034          {
1035              $this->import->writeKeywordTables($keywords);
1036              $this->deleteCacheKeywords = TRUE;
1037          }
1038      }
1039  /*

1040  * writeResourceCustomTable - write WKX_resource_custom table

1041  * @author Mark Grimshaw

1042  *

1043  * @param $entry - assoc array of one entry for import.

1044  */
1045  	function writeResourceCustomTable($custom)
1046      {
1047          if(empty($this->customFields))
1048              return;
1049          foreach($this->customFields as $importKey => $id)
1050          {
1051              if(!array_key_exists($importKey, $custom))
1052                  continue;
1053              $this->import->writeResourcecustomTable($custom[$importKey], $id);
1054          }
1055      }
1056  /**

1057  * writeBibtexStringTable - write $this->strings to bibtex_string table

1058  * 

1059  * @author Mark Grimshaw

1060  */
1061  	private function writeBibtexStringTable()
1062      {
1063          if(!empty($this->strings) && $this->session->getVar("import_Raw"))
1064          {
1065              $fields[] = 'bibtexstringText';
1066              foreach($this->strings as $key => $value)
1067                  $raw[] = '@STRING{' . $key . '=' . $value . '}';
1068              $values[] = base64_encode(serialize(join("\n", $raw)));
1069              $this->db->insert('bibtex_string', $fields, $values);
1070              $this->bibtexStringId = $this->db->lastAutoId();
1071          }
1072      }
1073  /**

1074  * grabHowPublished - check for type of howpublished field in bibtex misc entry

1075  * 

1076  * @author Mark Grimshaw

1077  * @param $entry - assoc array of one entry for import.

1078  * @return array(URL, howPublished)

1079  */
1080  	private function grabHowPublished($entry)
1081      {
1082          $url = $howPublished = FALSE;
1083          if(($entry['bibtexEntryType'] == 'misc') && array_key_exists('howpublished', $entry))
1084          {
1085              if(preg_match("#^\\\url{(.*://.*)}#", $entry['howpublished'], $match))

1086                  $url = $match[1];
1087              else
1088                  $howPublished = $entry['howpublished'];
1089          }
1090          else if(array_key_exists('url', $entry))
1091          {
1092              if(preg_match("#^\\\url{(.*://.*)}#", $entry['url'], $match))

1093                  $url = $match[1];
1094              else
1095                  $url = $entry['url'];
1096          }
1097          return array($url, $howPublished);
1098      }
1099  /**

1100  * grabMonth - check for any month field and split into component day/month fields

1101  * 

1102  * @author Mark Grimshaw

1103  * @param $entry - assoc array of one entry for import.

1104  * @return array(startMonth, startDay, endMonth, endDay)

1105  */
1106  	private function grabMonth($entry)
1107      {
1108          $startMonth = $startDay = $endMonth = $endDay = FALSE;
1109          if(array_key_exists('month', $entry))
1110              list($startMonth, $startDay, $endMonth, $endDay) = $this->monthObj->init($entry['month']);
1111          return array($startMonth, $startDay, $endMonth, $endDay);
1112      }
1113  // Write the bibtexKey field

1114  	function writeBibtexKey()
1115      {
1116          $recordset = $this->db->select(array('WKX_resource'), 'bibtexKey');
1117          while($row = $this->db->loopRecordSet($recordset))
1118              $bibtexKeys[] = $row['bibtexKey'];
1119          $letters = range('a', 'z');
1120          $sizeof = sizeof($letters);
1121          $recordset = $this->db->select(array('WKX_resource_misc'), 
1122              array(array('WKX_resource_misc.id' => 'resourceId'), 'creator1', 'creator2', 'year1'), 
1123              " LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . ' ON ' . 
1124              $this->db->formatField('WKX_resource_misc.id') . '=' . 
1125              $this->db->formatField('WKX_resource_creator.id') . 
1126              " LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . ' ON ' . 
1127              $this->db->formatField('WKX_resource_misc.id') . '=' . 
1128              $this->db->formatField('WKX_resource_year.id') . 
1129              ' WHERE ' . $this->db->formatField('WKX_resource_misc.id') . "=" . $this->resourceId);
1130          $row = $this->db->fetchRow($recordset);
1131          $year = $row['year1'];
1132          if(!$row['creator1'] && $row['creator2']) // use editor
1133              $creatorId = array_shift(split(',', $row['creator2']));
1134          else
1135              $creatorId = array_shift(split(',', $row['creator1']));
1136          $recordset2 = $this->db->select(array('WKX_creator'), array('prefix', 'surname'), 
1137              ' WHERE ' . $this->db->formatField('WKX_creator.id') . '=' . 
1138              $this->db->tidyInput($creatorId));
1139          $keyMade = FALSE;
1140          if(!$this->db->numRows($recordset2)) // anonymous
1141              $base = 'anon' . $year;
1142          else
1143          {
1144              $creator = $this->db->fetchRow($recordset2);
1145              $prefix = '';
1146              if($creator['prefix'])
1147              {
1148                  $prefix = utf8_decode($creator['prefix']);
1149                  foreach($this->bibConfig->bibtexSpChPlain as $key => $value)
1150                  {
1151                      $char = chr($key);
1152                      $prefix = preg_replace("/$char/", "$value", $prefix);
1153                  }
1154                  $prefix = preg_replace("/\W/", '', $prefix);
1155              }
1156              $surname = utf8_decode($creator['surname']);
1157              foreach($this->bibConfig->bibtexSpChPlain as $key => $value)
1158              {
1159                  $char = chr($key);
1160                  $surname = preg_replace("/$char/", "$value", $surname);
1161              }
1162              $surname = preg_replace("/\W/", '', $surname);
1163              $base = $prefix . $surname . $year;
1164          }
1165          $bibtexKey = $base;
1166          for($i = 0; $i < $sizeof; $i++)
1167          {
1168              if(array_search($bibtexKey, $bibtexKeys) === FALSE)
1169              {
1170                  $keyMade = TRUE;
1171                  break;
1172              }
1173              $bibtexKey = $base . $letters[$i];
1174          }
1175          if(!$keyMade)
1176              $bibtexKey = $base . '.' . $this->resourceId; // last resort

1177          $bibtexKey = str_replace(' ', '', $bibtexKey);
1178          $this->db->updateSingle('WKX_resource', 
1179              $this->db->formatField('bibtexKey') .  "=" . $this->db->tidyInput($bibtexKey),
1180              " WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
1181      }
1182  /**

1183  * gatherStage1 - gather input from stage 1 and return a fullpath filename for parsing.

1184  * If $this->type == 'paste', this is a user cut 'n' pasting bibtex entries in a textarea box. We write the input to a 

1185  * temporary file.

1186  * 

1187  * @author Mark Grimshaw

1188  * @return string

1189  */
1190  	private function gatherStage1()
1191      {
1192  // a multiple select box so handle as array

1193          if(isset($this->vars['import_Categories']) && $this->vars['import_Categories'])
1194          {
1195              if($this->session->getVar("import_UnrecognisedFields"))
1196                  $this->vars['import_Categories'] = explode(',', $this->vars['import_Categories']);
1197              if(!$this->session->setVar('import_Categories', trim(join(',', $this->vars['import_Categories']))))
1198                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1199          }
1200  // a multiple select box so handle as array

1201          if(isset($this->vars['import_BibId']) && $this->vars['import_BibId'])
1202          {
1203              if($this->session->getVar("import_unrecognisedFields"))
1204                  $this->vars['import_BibId'] = explode(',', $this->vars['import_BibId']);
1205              if(!$this->session->setVar('import_BibId', trim(join(',', $this->vars['import_BibId']))))
1206                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1207          }
1208          if(isset($this->vars['import_Raw']) && $this->vars['import_Raw'])
1209          {
1210              if(!$this->session->setVar('import_Raw', 1))
1211                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1212          }
1213          if(!$this->session->setVar('import_KeywordSeparator', $this->vars['import_KeywordSeparator']))
1214              $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1215          if(array_key_exists('import_KeywordIgnore', $this->vars))
1216          { 
1217              if(!$this->session->setVar('import_KeywordIgnore', $this->vars['import_KeywordIgnore']))
1218                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1219          }
1220          else
1221              $this->session->delVar('import_KeywordIgnore');
1222          if(!$this->session->setVar('import_TitleSubtitleSeparator', $this->vars['import_TitleSubtitleSeparator']))
1223              $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1224          if(isset($this->vars['import_ImportDuplicates']) && $this->vars['import_ImportDuplicates'])
1225          {
1226              if(!$this->session->setVar('import_ImportDuplicates', 1))
1227                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1228          }
1229  // Force to 1 => 'General' category

1230          if(!$this->session->getVar('import_Categories'))
1231          {
1232              if(!$this->session->setVar('import_Categories', 1))
1233                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1234          }
1235          if(($this->type == 'file') && !$this->session->getVar("import_UnrecognisedFields"))
1236          {
1237              if(!$this->importFile)
1238              {
1239                  if(!isset($_FILES['import_File']))
1240                  {
1241                      if($file = $this->session->getVar('import_File'))
1242                          return $this->dirName . '/' . $file;
1243                      else
1244                          $this->badInput->close($this->errors->text("file", "upload"), $this->badClass, $this->badFunction);
1245                  }
1246  // Check for file input

1247                  $fileName = sha1(session_id() . $_FILES['import_File']['name']);
1248                  if(!move_uploaded_file($_FILES['import_File']['tmp_name'], $this->dirName . '/' . $fileName))
1249                          $this->badInput->close($this->errors->text("file", "upload"), $this->badClass, $this->badFunction);
1250              }
1251              else // An import from a plug-in like ImportPubMed
1252                  $fileName = $this->importFile;
1253              if(!$this->session->setVar('import_File', $fileName))
1254                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1255              if($this->vars['import_Tag'])
1256              {
1257                  if(!$tagId = $this->tag->checkExists($this->vars['import_Tag']))
1258                  {
1259                      if(!$this->session->setVar('import_Tag', $this->vars['import_Tag']))
1260                          $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1261                  }
1262                  else
1263                  {
1264                      if(!$this->session->setVar('import_TagId', $tagId))
1265                          $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1266                  }
1267              }
1268              else if(isset($this->vars['import_TagId']) && $this->vars['import_TagId'])
1269              {
1270                  if(!$this->session->setVar('import_TagId', $this->vars['import_TagId']))
1271                      $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1272              }
1273              $this->garbageFiles[$this->dirName . '/' . $fileName] = FALSE;
1274              return $this->dirName . '/' . $fileName;
1275          }
1276          else if($this->type == 'paste')
1277          {
1278              if(!trim($this->vars['import_Paste']))
1279                  $this->badInput->close($this->errors->text("inputError", "missing"), $this->badClass, $this->badFunction);
1280              $paste = stripslashes(trim($this->vars['import_Paste']));
1281              if(!$this->session->setVar('import_Paste', base64_encode(serialize($paste))))
1282                  $this->badInput->close($this->errors->text("sessionError", "write"), $this->badClass, $this->badFunction);
1283              list($fileName, $fullFileName) = $this->file->createFileName($this->dirName, $paste, '.bib');
1284              if(!$fullFileName)
1285                  $this->badInput->close($this->errors->text("file", "write", ": $fileName"), $this->badClass, $this->badFunction);
1286              if(!$fp = fopen("$fullFileName", "w"))
1287                  $this->badInput->close($this->errors->text("file", "write", ": $fileName"), $this->badClass, $this->badFunction);
1288              if(!fputs($fp, $paste))
1289                  $this->badInput->close($this->errors->text("file", "write", ": $fileName"), $this->badClass, $this->badFunction);
1290              fclose($fp);
1291              $this->garbageFiles[$fullFileName] = FALSE;
1292              return $fullFileName;
1293          }
1294      }
1295  /*

1296  * convertEntries - convert any laTeX code and convert to UTF-8 ready for storing in the database

1297  * 

1298  * @author Mark Grimshaw

1299  * @param string $entries - multidimensional array of entries

1300  * @return multidimensional array of converted entries.

1301  */
1302  	private function convertEntries($entries)
1303      {
1304          foreach($this->bibConfig->bibtexSpCh as $key => $value)
1305          {
1306              $replaceBibtex[] = chr($key);
1307              $matchBibtex[] = preg_quote("/$value/");
1308          }
1309          foreach($this->bibConfig->bibtexSpChOld as $key => $value)
1310          {
1311              $replaceBibtex[] = chr($key);
1312              $matchBibtex[] = preg_quote("/$value/");
1313          }
1314          foreach($this->bibConfig->bibtexSpChOld2 as $key => $value)
1315          {
1316              $replaceBibtex[] = chr($key);
1317              $matchBibtex[] = preg_quote("/$value/");
1318          }
1319          foreach($this->bibConfig->bibtexSpChLatex as $key => $value)
1320          {
1321              $replaceBibtex[] = chr($key);
1322              $matchBibtex[] = preg_quote("/$value/");
1323          }
1324          foreach($this->bibConfig->bibtexWordsTranslate as $key => $value) // NB reverse key--value
1325          {
1326              $replaceBibtex[] = $value;
1327              $matchBibtex[] = preg_quote("/$key/");
1328          }
1329          foreach($this->bibConfig->bibtexCodesDelete as $key => $value) // NB reverse key--value
1330          {
1331              $replaceBibtex[] = $value;
1332              $matchBibtex[] = preg_quote("/$key/");
1333          }
1334          $index = 0;
1335          foreach($entries as $eKey => $array)
1336          {
1337              if(!is_array($array)) // e.g. strings array
1338              {
1339                  $temp[$eKey] = $this->utf8->smartUtf8_encode(preg_replace($matchBibtex, $replaceBibtex, $array));
1340                  continue;
1341              }
1342              foreach($array as $key => $value)
1343                  $temp[$index][$key] = $this->utf8->smartUtf8_encode(preg_replace($matchBibtex, $replaceBibtex, $value));
1344              $index++;
1345          }
1346          return $temp;
1347      }
1348  }
1349  ?>

title

Description

title

Description

title

Description

title

title

Body