WIKINDX PHP Cross Reference Collaborative Wikis

Source: /core/importexport/IMPORT.php - 848 lines - 30252 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 2013

  19  sirfragalot@users.sourceforge.net

  20  */
  21  /**

  22  * Common functions for importing resources into wikindx

  23  * 

  24  * @version    1

  25  *

  26  *    @package wikindx4\core\importexport

  27  *    @author Mark Grimshaw <sirfragalot@users.sourceforge.net>

  28  *

  29  */
  30  class IMPORT
  31  {
  32  /** object */

  33  private $db;
  34  /** array */

  35  private $vars;
  36  /** object */

  37  private $messages;
  38  /** object */

  39  private $errors;
  40  /** object */

  41  private $session;
  42  /** object */

  43  private $form;
  44  /** object */

  45  private $html;
  46  /** object */

  47  private $table;
  48  /** object */

  49  private $config;
  50  /** object */

  51  private $creator;
  52  /** object */

  53  private $keyword;
  54  /** int */

  55  private $resourceId;
  56  /** object */

  57  private $collection;
  58  /** object */

  59  private $collectionMap;
  60  /** object */

  61  private $publisher;
  62  /** object */

  63  private $publisherMap;
  64  /** object */

  65  private $bibConfig;
  66  /** array */

  67  private $bibtexKeys = array();
  68  
  69  /**

  70  *    IMPORT

  71  */
  72  	public function __construct()
  73      {
  74          $this->db = FACTORY_DB::getInstance();
  75          $this->vars = GLOBALS::getVars();
  76          $this->session = FACTORY_SESSION::getInstance();
  77          $this->messages = FACTORY_MESSAGES::getInstance();
  78          $this->errors = FACTORY_ERRORS::getInstance();
  79          $this->form = FACTORY_FORM::getInstance();
  80          $this->html = FACTORY_HTML::getInstance();
  81          $this->table = FACTORY_TABLE::getInstance();
  82          $this->config = FACTORY_CONFIG::getInstance();
  83          $this->creator = FACTORY_CREATOR::getInstance();
  84          $this->keyword = FACTORY_KEYWORD::getInstance();
  85          $this->collection = FACTORY_COLLECTION::getInstance();
  86          $this->collectionMap = FACTORY_COLLECTIONMAP::getInstance();
  87          $this->publisher = FACTORY_PUBLISHER::getInstance();
  88          $this->publisherMap = FACTORY_PUBLISHERMAP::getInstance();
  89          $this->bibConfig = FACTORY_BIBTEXCONFIG::getInstance();
  90          $this->bibConfig->bibtex();
  91          $bibtexKeys = array();
  92          $recordset = $this->db->select('resource', 'resourceBibtexKey');
  93          while($row = $this->db->fetchRow($recordset))
  94              $this->bibtexKeys[] = $row['resourceBibtexKey'];
  95      }
  96  /**

  97  * Check for duplicate title/resourceType

  98  *

  99  * If the session variable 'import_ImportDuplicates' is TRUE, the function quits immediately.

 100  * NoSort, Title, Subtitle and resource type must match.

 101  * @param string $noSort (A word like 'the', 'a' or translated equivalents that is at the start of the raw title)

 102  * @param string $title

 103  * @param string $subtitle

 104  * @param string $type

 105  * @return boolean TRUE if resource already exists, FALSE if not.

 106  */
 107  	public function checkDuplicates($noSort, $title, $subtitle, $type)
 108      {
 109          if($this->session->getVar('import_ImportDuplicates'))
 110              return FALSE; // i.e. allow duplicates

 111          $title = str_replace('{', '', str_replace('}', '', $title));
 112          if($subtitle)
 113          {
 114              $subtitle = str_replace('{', '', str_replace('}', '', $subtitle));
 115              $this->db->formatConditions($this->db->replace($this->db->replace('resourceSubtitle', '{', ''), '}', '', FALSE) . 
 116                  $this->db->like(FALSE, $subtitle, FALSE));
 117          }
 118          else
 119              $this->db->formatConditions(array('resourceSubtitle' => ' IS NULL'));
 120          if($noSort)
 121          {
 122              $noSort = str_replace('{', '', str_replace('}', '', $noSort));
 123              $this->db->formatConditions($this->db->replace($this->db->replace('resourceNoSort', '{', ''), '}', '', FALSE) . 
 124                  $this->db->like(FALSE, $noSort, FALSE));
 125          }
 126          else
 127              $this->db->formatConditions(array('resourceNoSort' => ' IS NULL'));
 128          $this->db->formatConditions(array('resourceType' => $type));
 129          $this->db->formatConditions($this->db->replace($this->db->replace('resourceTitle', '{', ''), '}', '', FALSE) . 
 130              $this->db->equal . $this->db->tidyInput($title));
 131          $resultset = $this->db->select('resource', 'resourceId');
 132          if($this->db->numRows($resultset))
 133              return TRUE;
 134          return FALSE;
 135      }
 136  /**

 137  * Print a list of discarded resources.

 138  * 

 139  * @author Mark Grimshaw

 140  *

 141  * @param int $numDiscarded Num. resources discarded

 142  * @param array $titlesDiscarded Titles of discarded resources

 143  * @return string.

 144  */
 145  	public function printDuplicates($numDiscarded, $titlesDiscarded)
 146      {
 147          if(($numDiscarded <= 50) && !empty($titlesDiscarded))
 148          {
 149              $reject = $this->messages->text("import", "discarded", " " . $numDiscarded);
 150              foreach($titlesDiscarded as $title)
 151                  $reject .= $this->html->br() . $title;
 152              return $this->html->p($reject);
 153          }
 154          return $this->html->p($this->messages->text("import", "discarded", " " . $numDiscarded));
 155      }
 156  /**

 157  * split title into WIKINDX component parts (noSort, title : subtitle)

 158  *

 159  * title / subtitle split is calculated on the session variable 'import_TitleSubtitleSeparator'.

 160  *

 161  * @author Mark Grimshaw

 162  * @param $title

 163  * @return array (noSort, title, subtitle)

 164  */
 165  	public function splitTitle($title)
 166      {
 167          if(!trim($title))
 168              return array(FALSE, FALSE, FALSE);
 169          $noSort = $subtitle = FALSE;
 170          $split = $this->session->getVar('import_TitleSubtitleSeparator');
 171          if($split) // split title and subtitle
 172          {
 173              switch($split)
 174              {
 175                  case 1: 
 176                      $split = ': ';
 177                      break;
 178                  case 2: 
 179                      $split = '; ';
 180                      break;
 181                  case 3: 
 182                      $split = '[.!?] ';
 183                      break;
 184                  case 4: 
 185                      $split = '--';
 186                      break;
 187                  case 5: 
 188                      $split = '-';
 189                      break;
 190              }
 191              $array = preg_split("/$split/", $title, 2);
 192              if(sizeof($array) > 1)
 193              {
 194                  $title = trim(array_shift($array));
 195                  $subtitle = trim(join('', $array));
 196  // Correct any incomplete braces

 197                  if((strpos($title, '{') !== FALSE) && (strpos($title, '}') === FALSE))
 198                      $title .= '}';
 199                  if((strpos($subtitle, '}') !== FALSE) && (strpos($subtitle, '{') === FALSE))
 200                      $subtitle = '{' . $subtitle;
 201              }
 202              else
 203                  $title = trim($array[0]);
 204          }
 205          foreach($this->config->WIKINDX_NOSORT as $pattern)
 206          {
 207              if(preg_match("/^($pattern)\s(.*)|^\{($pattern)\s(.*)/i", $title, $matches))
 208              {
 209                  if(array_key_exists(3, $matches)) // found second set of matches
 210                  {
 211                      $title = '{' . trim($this->html->removeNl($matches[4]));
 212                      $noSort = trim($this->html->removeNl($matches[3]));
 213                  }
 214                  else
 215                  {
 216                      $title = trim($this->html->removeNl($matches[2]));
 217                      $noSort = trim($this->html->removeNl($matches[1]));
 218                  }
 219                  break;
 220              }
 221          }
 222          return array($noSort, $title, $subtitle);
 223      }
 224  /**

 225  * Select box for specifying keyword separation character in source bibliography

 226  *

 227  * @return string

 228  */
 229  	public function keywordSeparator()
 230      {
 231          $sessVar = $this->session->issetVar('import_KeywordSeparator') ? 
 232              $this->session->getVar('import_KeywordSeparator') : FALSE;
 233          $array = array(
 234              $this->messages->text('misc', 'keywordImport1'),
 235              $this->messages->text('misc', 'keywordImport2'),
 236              $this->messages->text('misc', 'keywordImport3'),
 237              $this->messages->text('misc', 'keywordImport4'),
 238              );
 239          if($sessVar !== FALSE)
 240              $pString = $this->form->selectedBoxValue($this->messages->text('misc', 'keywordImport'), 
 241                  'import_KeywordSeparator', $array, $sessVar, 4);
 242          else
 243              $pString = $this->form->selectFBoxValue($this->messages->text('misc', 'keywordImport'), 
 244                  'import_KeywordSeparator', $array, 4);
 245          $sessVar = $this->session->issetVar('import_KeywordIgnore') ? TRUE : FALSE;
 246          return $pString .= $this->html->p($this->form->checkBox($this->messages->text('misc', 'keywordIgnore'), 
 247              'import_KeywordIgnore', $sessVar));
 248      }
 249  /**

 250  * Select box for specifying title/subtitle separation character in source bibliography

 251  *

 252  * @return string

 253  */
 254  	public function titleSubtitleSeparator()
 255      {
 256          $sessVar = $this->session->getVar('import_TitleSubtitleSeparator');
 257          $array = array(
 258              $this->messages->text('misc', 'titleSubtitleSeparator1'),
 259              $this->messages->text('misc', 'titleSubtitleSeparator2'),
 260              $this->messages->text('misc', 'titleSubtitleSeparator3'),
 261              $this->messages->text('misc', 'titleSubtitleSeparator4'),
 262              $this->messages->text('misc', 'titleSubtitleSeparator5'),
 263              $this->messages->text('misc', 'titleSubtitleSeparator6'),
 264              );
 265          if($sessVar !== FALSE)
 266              return $this->form->selectedBoxValue($this->messages->text('misc', 'titleSubtitleSeparator'), 
 267                  'import_TitleSubtitleSeparator', $array, $sessVar, 6);
 268          else
 269              return $this->form->selectedBoxValue($this->messages->text('misc', 'titleSubtitleSeparator'), 
 270                  'import_TitleSubtitleSeparator', $array, 1, 6);
 271      }
 272  /**

 273  * Selext box for selecting user bibliographies to import into

 274  *

 275  * @return string

 276  */
 277  	public function bibliographySelect()
 278      {
 279  // Get this user's bibliographies

 280          if($this->session->getVar('mywikindx_Bibliographies'))
 281          {
 282              $bibsRaw = unserialize($this->session->getVar("mywikindx_Bibliographies"));
 283              foreach($bibsRaw as $key => $value)
 284                  $bibsU[$key] = $this->html->dbToFormTidy($value);
 285          }
 286  // Get this user's user group bibliographies

 287          if($this->session->getVar('mywikindx_Groupbibliographies'))
 288          {
 289              $bibsRaw = unserialize($this->session->getVar("mywikindx_Groupbibliographies"));
 290              foreach($bibsRaw as $key => $value)
 291                  $bibsUG[$key] = $this->html->dbToFormTidy($value);
 292          }
 293          $bib = FACTORY_BIBLIOGRAPHYCOMMON::getInstance();
 294          $bibsU = $bib->getUserBibs();
 295          $bibsUG = $bib->getGroupBibs();
 296          if(!empty($bibsU))
 297          {
 298              $bibsArray[-1] = $this->messages->text('user', 'userBibs');
 299              foreach($bibsU as $key => $value)
 300                  $bibsArray[$key] = $value;
 301          }
 302          if(!empty($bibsUG))
 303          {
 304              $bibsArray[-2] = $this->messages->text('user', 'userGroupBibs');
 305              foreach($bibsUG as $key => $value)
 306                  $bibsArray[$key] = $value;
 307          }
 308          if(isset($bibsArray))
 309              return $this->form->selectFBoxValueMultiple($this->messages->text("user", 'bib'), "import_BibId", $bibsArray, 5);
 310          return FALSE;
 311      }
 312  /**

 313  * Write the resource table

 314  *

 315  * @param array $fields

 316  * @param array $values

 317  * @return int New resource Id

 318  */
 319  	public function writeResourceTable($fields, $values)
 320      {
 321          $this->db->insert('resource', $fields, $values);
 322          $this->resourceId = $this->db->lastAutoID();
 323          return $this->resourceId;
 324      }
 325  /**

 326  * Write the resource_misc table

 327  *

 328  * @param array $fields

 329  * @param array $values

 330  */
 331  	public function writeResourcemiscTable($fields, $values)
 332      {
 333          $fields[] = 'resourcemiscId';
 334          $values[] = $this->resourceId;
 335          if(($this->session->getVar('setup_Superadmin') != 1) && ($this->session->getVar('setup_Quarantine') == 'Y'))
 336          {
 337              $fields[] = 'resourcemiscQuarantine';
 338              $values[] = 'Y';
 339          }
 340          $this->db->insert('resource_misc', $fields, $values);
 341      }
 342  /**

 343  * Write creator and resource_creator tables

 344  *

 345  * @param array ordered array of creators

 346  */
 347  	public function writeCreatorTables($creators)
 348      {
 349          if(empty($creators)) // need blank row for list operations
 350          {
 351              $this->db->insert('resource_creator', array('resourcecreatorResourceId'), array($this->resourceId));
 352              return;
 353          }
 354          $mainSurname = $mainId = $rowWritten = $deleteCache = FALSE;
 355          foreach($creators as $role => $roleArray)
 356          {
 357              foreach($roleArray as $order => $creatorArray)
 358              {
 359                  $creatorId = FALSE;
 360                  if($creatorArray['surname']) // entry in surname takes precedence
 361                  {
 362                      unset($creatorArray['select']);
 363                      $initials = $this->creator->formatInitials($creatorArray['initials']);
 364                      $creatorId = $this->creator->checkExists($creatorArray['surname'], $creatorArray['firstname'], 
 365                          $initials, $creatorArray['prefix']);
 366                      if(!$creatorId) // new creator
 367                      {
 368                          $writeArray = array();
 369                          $writeArray['creatorSurname'] = trim($creatorArray['surname']);
 370                          if($creatorArray['firstname'])
 371                              $writeArray['creatorFirstname'] = trim($creatorArray['firstname']);
 372                          if($creatorArray['prefix'])
 373                              $writeArray['creatorPrefix'] = trim($creatorArray['prefix']);
 374                          if(trim($initials))
 375                              $writeArray['creatorInitials'] = trim($initials);
 376                          $this->db->insert('creator', array_keys($writeArray), array_values($writeArray));
 377                          $creatorId = $this->db->lastAutoID();
 378                          if(!$mainSurname)
 379                          {
 380                              $mainSurname = trim($creatorArray['surname']);
 381                              $mainId = $creatorId;
 382                          }
 383                          $deleteCache = TRUE;
 384                      }
 385                  }
 386                  else if(array_key_exists('select', $creatorArray) && $creatorArray['select'])
 387                      $creatorId = $creatorArray['select'];
 388                  if($creatorId)
 389                  {
 390                      if(!$mainSurname)
 391                      {
 392                          $this->db->formatConditions(array('creatorId' => $creatorId));
 393                          $mainSurname = $this->db->fetchOne($this->db->select('creator', 'creatorSurname'));
 394                          $mainId = $creatorId;
 395                      }
 396                      $writeArray = array();
 397                      $writeArray['resourcecreatorCreatorId'] = $creatorId;
 398                      $writeArray['resourcecreatorResourceId'] = $this->resourceId;
 399                      $writeArray['resourcecreatorCreatorMain'] = $mainId;
 400                      $writeArray['resourcecreatorCreatorSurname'] = $mainSurname;
 401                      $writeArray['resourcecreatorOrder'] = $order;
 402                      $writeArray['resourcecreatorRole'] = $role;
 403                      $this->db->insert('resource_creator', array_keys($writeArray), array_values($writeArray));
 404                      $rowWritten = TRUE;
 405                  }
 406              }
 407          }
 408      }
 409  /**

 410  * Write the publisher table

 411  *

 412  * @param string $name Publisher name

 413  * @param string $location Publisher location

 414  * @param string $wkType wikindx resource type

 415  * @return int Publisher ID

 416  */
 417  	public function writePublisherTable($name, $location, $wkType)
 418      {
 419          $publisherId = FALSE;
 420          if($name && (!$publisherId = $this->publisher->checkExists($name, $location)))
 421          {
 422              if($name)
 423                  $writeArray['publisherName'] = $name;
 424              if($location)
 425                  $writeArray['publisherLocation'] = $location;
 426              if(array_key_exists($wkType, $this->publisherMap->publisherTypes))
 427                  $writeArray['publisherType'] = $this->publisherMap->publisherTypes[$wkType];
 428              $this->db->insert('publisher', array_keys($writeArray), array_values($writeArray));
 429              $publisherId = $this->db->lastAutoID();
 430          }
 431          return $publisherId;
 432      }
 433  /**

 434  * Write collection table

 435  *

 436  * @param string $title Collection title

 437  * @param string $titleShort Collection short title

 438  * @param string $wkType wikindx resource type

 439  * @return int Collection ID

 440  */
 441  	public function writeCollectionTable($title, $titleShort, $wkType)
 442      {
 443          if($title)
 444              $writeArray['collectionTitle'] = $title;
 445          if($titleShort)
 446              $writeArray['collectionTitleShort'] = $titleShort;
 447          $type = FALSE;
 448          if(array_key_exists($wkType, $this->collectionMap->collectionTypes))
 449              $writeArray['collectionType'] = $type = $this->collectionMap->collectionTypes[$wkType];
 450          if($title && (!$collectionId = $this->collection->checkExists(FALSE, $title, $titleShort, $type)))
 451          {
 452              $this->db->insert('collection', array_keys($writeArray), array_values($writeArray));
 453              $collectionId = $this->db->lastAutoID();
 454          }
 455          return $collectionId;
 456      }
 457  /**

 458  * writeResourceTimestampTable - write timestamp to resource_timestamp table an add blank statistics row

 459  * 

 460  * @author Mark Grimshaw

 461  */
 462  	public function writeResourceTimestampTable()
 463      {
 464          $this->db->insert('resource_timestamp', array('resourcetimestampId', 'resourcetimestampTimestamp', 
 465              'resourcetimestampTimestampAdd'), 
 466              array($this->resourceId, $this->db->formatTimestamp(), $this->db->formatTimestamp()));
 467          $this->db->insert('statistics', array('statisticsResourceId'), array($this->resourceId));
 468      }
 469  /**

 470  * Wite resource_page table

 471  *

 472  * @author Mark Grimshaw

 473  * @param array $fields

 474  * @param array $values

 475  */
 476  	public function writePageTable($fields, $values)
 477      {
 478          $fields[] = 'resourcepageId';
 479          $values[] = $this->resourceId;
 480          $this->db->insert('resource_page', $fields, $values);
 481      }
 482  /**

 483  * Wite resource_year table

 484  *

 485  * @author Mark Grimshaw

 486  * @param array $fields

 487  * @param array $values

 488  */
 489  	public function writeYearTable($fields, $values)
 490      {
 491          $fields[] = 'resourceyearId';
 492          $values[] = $this->resourceId;
 493          $this->db->insert('resource_year', $fields, $values);
 494      }
 495  /**

 496  * Write resource_text table

 497  *

 498  * @param string $notes

 499  * @param string $abstract

 500  * @param string $url Default is FALSE

 501  */
 502  	public function writeResourcetextTable($notes, $abstract, $url = FALSE)
 503      {
 504          $fields[] = 'resourcetextId';
 505          $values[] = $this->resourceId;
 506          if($notes)
 507          {
 508              $fields[] = 'resourcetextNote';
 509              $values[] = $notes;
 510              $fields[] = 'resourcetextAddUserIdNote';
 511              $values[] = $this->session->getVar("setup_UserId");
 512          }
 513          if($abstract)
 514          {
 515              $fields[] = 'resourcetextAbstract';
 516              $values[] = $abstract;
 517              $fields[] = 'resourcetextAddUserIdAbstract';
 518              $values[] = $this->session->getVar("setup_UserId");
 519          }
 520          if($url)
 521          {
 522              if(!is_array($url))
 523                  $url = array($url);
 524              $fields[] = 'resourcetextUrls';
 525              $values[] = base64_encode(serialize($url));
 526          }
 527          $this->db->insert('resource_text', $fields, $values);
 528      }
 529  /**

 530  * Write keyword tables

 531  *

 532  * @param array $keywords

 533  */
 534  	public function writeKeywordTables($keywords)
 535      {
 536          if($this->session->getVar('import_KeywordIgnore'))
 537              return;
 538          foreach($keywords as $kWord)
 539          {
 540              if(!$kId = $this->keyword->checkExists($kWord))
 541              {
 542                  $this->db->insert('keyword', array('keywordKeyword'), array($kWord));
 543                  $kId = $this->db->lastAutoID();
 544              }
 545              $this->db->insert('resource_keyword', array('resourcekeywordResourceId', 'resourcekeywordKeywordId'), 
 546                  array($this->resourceId, $kId));
 547          }
 548      }
 549  /**

 550  * Write resource_category table

 551  *

 552  * @param string $categories Comma-delimited list of category IDs.  At the very least, this must comprise '1' (the 'General' category)

 553  */
 554  	public function writeResourcecategoryTable($categories)
 555      {
 556          foreach(explode(',', $categories) as $cId)
 557              $this->db->insert('resource_category', array('resourcecategoryResourceId', 'resourcecategoryCategoryId'), 
 558              array($this->resourceId, $cId));
 559      }
 560  /**

 561  * Write resource_custom tables

 562  *

 563  * @param string $string

 564  * @param int $customId

 565  */
 566  	public function writeResourcecustomTable($string, $customId)
 567      {
 568          $writeArray = array();
 569          $this->db->formatConditions(array('customId' => $customId));
 570          if($this->db->fetchOne($this->db->select('custom', 'customSize')) == 'S')
 571              $writeArray['resourcecustomShort'] = $string;
 572          else
 573              $writeArray['resourcecustomLong'] = $string;
 574          $writeArray['resourcecustomAddUserIdCustom'] = $this->session->getVar('setup_UserId');
 575          $writeArray['resourcecustomCustomId'] = $customId;
 576          $writeArray['resourcecustomResourceId'] = $this->resourceId;
 577          $this->db->insert('resource_custom', array_keys($writeArray), array_values($writeArray));
 578      }
 579  /**

 580  * writeImportRawTable - write import_raw table

 581  *

 582  * @author Mark Grimshaw

 583  * @param array $rejectedArray Rejected input values for this resource

 584  * @param int $bibtexStringId ID of the BibTeX string in the bibtex_string table. Default is FALSE

 585  * @param string $importType Default is FALSE

 586  */
 587  	public function writeImportrawTable($rejectedArray, $bibtexStringId = FALSE, $importType = FALSE)
 588      {
 589          if(empty($rejectedArray) || !$this->session->getVar("import_Raw"))
 590              return;
 591          if(!$importType)
 592              $importType = 'bibtex';
 593          $rejected = '';
 594          foreach($rejectedArray as $key => $value)
 595              $rejected .= "$key = $value\n";
 596          $fields[] = 'importrawId';
 597          $values[] = $this->resourceId;
 598          if($bibtexStringId)
 599          {
 600              $fields[] = 'importrawStringId';
 601              $values[] = $bibtexStringId;
 602          }
 603          $fields[] = 'importrawText';
 604          $values[] = base64_encode(serialize($rejected));
 605          $fields[] = 'importrawImportType';
 606          $values[] = $importType;
 607          $this->db->insert('import_raw', $fields, $values);
 608      }
 609  /**

 610  * Write user_bibliography_resource table

 611  *

 612  * @param string $bibId Comma-delimited string of user_bibliography ids

 613  */
 614  	public function writeUserbibliographyresourceTable($bibId)
 615      {
 616          if(!$bibId)
 617              return;
 618          foreach(explode(',', $bibId) as $bId)
 619              $this->db->insert('user_bibliography_resource', 
 620              array('userbibliographyresourceResourceId', 'userbibliographyresourceBibliographyId'), 
 621              array($this->resourceId, $bId));
 622      }
 623  /**

 624  * writeTagTable - write import tag to tag table

 625  * 

 626  * @author Mark Grimshaw

 627  * @return int lastAutoId

 628  */
 629  	public function writeTagTable()
 630      {
 631          if($tagId = $this->session->getVar('import_TagId'))
 632              return $tagId;
 633          if(!$tag = $this->session->getVar('import_Tag'))
 634              return FALSE;
 635          $this->db->insert('tag', array('tagTag'), array($this->html->removeNl($tag)));
 636          return $this->db->lastAutoID();
 637      }
 638  /**

 639  * Write the bibtexKey field for a new resource

 640  */
 641  	public function writeBibtexKey()
 642      {
 643          $letters = range('a', 'z');
 644          $sizeof = sizeof($letters);
 645          $this->db->formatConditions(array('resourceyearId' => $this->resourceId));
 646          $recordset = $this->db->select(array('resource_year'), array('resourceyearYear1', 
 647              'resourceyearYear2', 'resourceyearYear3', 'resourceyearYear4'));
 648          $row = $this->db->fetchRow($recordset);
 649          if($row['resourceyearYear1'])
 650              $year = $row['resourceyearYear1'];
 651          else if($row['resourceyearYear2'])
 652              $year = $row['resourceyearYear2'];
 653          else if($row['resourceyearYear3'])
 654              $year = $row['resourceyearYear3'];
 655          else if($row['resourceyearYear4'])
 656              $year = $row['resourceyearYear4'];
 657          else 
 658              $year = FALSE;
 659          $this->db->leftJoin('creator', 'creatorId', 'resourcecreatorCreatorMain');
 660          $this->db->formatConditions(array('resourcecreatorResourceId' => $this->resourceId));
 661          $this->db->formatConditions(array('resourcecreatorOrder' => '1'));
 662          $this->db->ascDesc = $this->db->asc;
 663          $this->db->orderBy('resourcecreatorRole');
 664          $this->db->limit(1, 0); // pick just the first one

 665          $recordset = $this->db->select(array('resource_creator'), array('creatorSurname', 'creatorPrefix'));
 666          $row = $this->db->fetchRow($recordset);
 667          $keyMade = FALSE;
 668          if((!is_array($row) || !array_key_exists('creatorSurname', $row) || !$row['creatorSurname'])) // anonymous
 669              $base = 'anon' . $year;
 670          else
 671          {
 672              $prefix = '';
 673              if($row['creatorPrefix'])
 674              {
 675                  foreach($this->bibConfig->bibtexSpChPlain as $key => $value)
 676                  {
 677                      $char = chr($key);
 678                      $prefix = preg_replace("/$char/", "$value", $row['creatorPrefix']);
 679                  }
 680                  $prefix = preg_replace("/\W/", '', $prefix);
 681              }
 682              foreach($this->bibConfig->bibtexSpChPlain as $key => $value)
 683              {
 684                  $char = chr($key);
 685                  $surname = preg_replace("/$char/", "$value", $row['creatorSurname']);
 686              }
 687              $surname = preg_replace("/\W/", '', $surname);
 688              $base = $prefix . $surname . $year;
 689          }
 690          $bibtexKey = $base;
 691          for($i = 0; $i < $sizeof; $i++)
 692          {
 693              if(array_search($bibtexKey, $this->bibtexKeys) === FALSE)
 694              {
 695                  $keyMade = TRUE;
 696                  break;
 697              }
 698              $bibtexKey = $base . $letters[$i];
 699          }
 700          if(!$keyMade)
 701              $bibtexKey = $base . '.' . $this->resourceId; // last resort

 702          $bibtexKey = str_replace(' ', '', $bibtexKey);
 703          $this->bibtexKeys[] = $bibtexKey;
 704          $this->db->formatConditions(array('resourceId' => $this->resourceId));
 705          $this->db->update('resource', array('resourceBibtexKey' => $bibtexKey));
 706      }
 707  /**

 708  * Tidy up the database by checking for creators etc. that do not have resources.

 709  *

 710  * This should be called just once at the end of multiple inserts.

 711  */
 712  	public function tidyTables()
 713      {
 714          $this->creator->removeHanging();
 715          $this->publisher->removeHanging();
 716          $this->collection->removeHanging();
 717          $this->keyword->removeHanging();
 718      }
 719  /**

 720  * promptFieldNames - print field name mapping to browser as an intermediate stage when invalid field names are found in the input.

 721  *

 722  * This allows users to map them to any existing custom fields.

 723  * @param array $entries

 724  * @param array $inputTypes

 725  * @param array $map

 726  * @param array $invalidFieldNames

 727  * @param mixed $strings array|FALSE. Default is FALSE

 728  * 

 729  * @author Mark Grimshaw

 730  * @return array 1st element is error message or FALSE, 2nd element is string for display

 731  */
 732  	public function promptFieldNames($entries, $inputTypes, $map, $invalidFieldNames, $strings = FALSE)
 733      {
 734  // Do some system management

 735          $file = FACTORY_FILE::getInstance();
 736          $file->tidyFiles();
 737          if(isset($this->config->WIKINDX_FILES_DIR))
 738              $dirName = $this->config->WIKINDX_FILES_DIR;
 739          else
 740              $dirName = "files"; // default

 741  // Write entries as serialised array temporarily to files/

 742          $serArray = base64_encode(serialize($entries));
 743          $fileName = sha1($serArray);
 744          $fullFileName = $dirName . '/' . $fileName;
 745          if(!$fp = fopen("$fullFileName", "w"))
 746              return array($this->errors->text("file", "write", ": $fileName"), FALSE);
 747          if(!fputs($fp, $serArray))
 748              return array($this->errors->text("file", "write", ": $fileName"), FALSE);
 749          fclose($fp);
 750  // Write filename to session

 751          $this->session->setVar("import_FileNameEntries", $fullFileName);
 752  // Write $this->strings as serialised array temporarily to files/

 753          if($strings)
 754          {
 755              $stringArray = base64_encode(serialize($strings));
 756              $fileName = sha1($stringArray);
 757              $fullFileName = $dirName . '/' . $fileName;
 758              if(!$fp = fopen("$fullFileName", "w"))
 759                  return array($this->errors->text("file", "write", ": $fileName"), FALSE);
 760              if(!fputs($fp, $stringArray))
 761                  return array($this->errors->text("file", "write", ": $fileName"), FALSE);
 762              fclose($fp);
 763  // Write filename to session

 764              $this->session->setVar("import_FileNameStrings", $fullFileName);
 765          }
 766  // Write unrecognised fields to session as serialised array

 767          $serArray = base64_encode(serialize($invalidFieldNames));
 768          $this->session->setVar("import_UnrecognisedFields", $serArray);
 769  // Create select boxes of all valid field names in WIKINDX including custom fields

 770          $possibleFields[0] = $this->messages->text('misc', 'ignore');
 771          foreach($map->types as $wkType => $bibtexType)
 772          {
 773              if(array_search($bibtexType, $inputTypes) === FALSE)
 774                  continue;
 775              foreach($map->{$wkType}['possible'] as $field)
 776              {
 777                  if(array_search($field, $map->noMap) === FALSE)
 778                      $possibleFields[] = $field;
 779              }
 780          }
 781          $possibleFields = array_unique($possibleFields);
 782  // Get custom fields

 783          $recordset = $this->db->select('custom', array('customId', 'customLabel'));
 784          while($row = $this->db->fetchRow($recordset))
 785              $possibleFields[] = $row['customId'] . '&nbsp;&nbsp;custom:&nbsp;&nbsp;' . $row['customLabel'];
 786          $pString = $this->html->p($this->messages->text('import', 'invalidField1'));
 787          $pString .= $this->form->formHeader("import_IMPORTBIBTEX_CORE");
 788          $pString .= $this->form->hidden('method', 'stage2Invalid');
 789          if(array_key_exists('type', $this->vars))
 790              $pString .= $this->form->hidden('type', $this->vars['type']);
 791          if(isset($this->vars['import_Tag']) && $this->vars['import_Tag'])
 792              $pString .= $this->form->hidden('import_Tag', $this->vars['import_Tag']);
 793          if(isset($this->vars['import_Categories']) && $this->vars['import_Categories'])
 794              $pString .= $this->form->hidden('import_Categories', trim(implode(',', ($this->vars['import_Categories']))));
 795          if(isset($this->vars['import_KeywordSeparator']))
 796              $pString .= $this->form->hidden('import_KeywordSeparator', $this->vars['import_KeywordSeparator']);
 797          if(isset($this->vars['import_KeywordIgnore']))
 798              $pString .= $this->form->hidden('import_KeywordIgnore', $this->vars['import_KeywordIgnore']);
 799          if(isset($this->vars['import_TitleSubtitleSeparator']))
 800              $pString .= $this->form->hidden('import_TitleSubtitleSeparator', $this->vars['import_TitleSubtitleSeparator']);
 801          if(isset($this->vars['import_Raw']) && $this->vars['import_Raw'])
 802              $pString .= $this->form->hidden('import_Raw', $this->vars['import_Raw']);
 803          if(isset($this->vars['import_ImportDuplicates']) && $this->vars['import_ImportDuplicates'])
 804              $pString .= $this->form->hidden('import_ImportDuplicates', $this->vars['import_ImportDuplicates']);
 805          if(isset($this->vars['import_BibId']) && $this->vars['import_BibId'])
 806              $pString .= $this->form->hidden('import_BibId', trim(implode(',', ($this->vars['import_BibId']))));
 807          foreach($invalidFieldNames as $invalidField)
 808              $pString .= $this->html->p($this->form->selectFBox($this->html->b($invalidField), 
 809                  'import_' . $invalidField, $possibleFields, 5));
 810          $pString .= $this->html->p($this->form->checkbox($this->messages->text('import', 'invalidField2'), 
 811              "import_Precedence"));
 812          $pString .= $this->html->p($this->form->formSubmit());
 813          return array(FALSE, $pString);
 814      }
 815  /**

 816  * getUnrecognised fields

 817  *

 818  * Follows from prompting for field mapping

 819  * 

 820  * @author Mark Grimshaw

 821  * @return array 1st element is error message or FALSE, 2nd element is array of custom fields, 3rd element is array of unrecognized fields

 822  */
 823  	public function getUnrecognisedFields()
 824      {
 825          $unrecognisedFields = 
 826              unserialize(base64_decode($this->session->getVar("import_UnrecognisedFields")));
 827          $mapFields = $customFields = array();
 828          foreach($unrecognisedFields as $key)
 829          {
 830              $importKey = 'import_' . $key;
 831              if(array_key_exists($importKey, $this->vars) && ($this->vars[$importKey] != $this->messages->text('misc', 'ignore')) && 
 832                  (array_search($this->vars[$importKey], $mapFields) !== FALSE))
 833                  return array($this->errors->text("file", "fieldMap"), array(), array());
 834              else if($this->vars[$importKey] != $this->messages->text('misc', 'ignore'))
 835                  $mapFields[] = $this->vars[$importKey];
 836              if(array_key_exists($importKey, $this->vars) && ($this->vars[$importKey] == $this->messages->text('misc', 'ignore')))
 837                  unset($this->vars[$importKey]);
 838              else if(array_key_exists($importKey, $this->vars) && 
 839                  (sizeof($split = explode("custom:", str_replace('&nbsp;&nbsp;', '', $this->vars[$importKey]))) == 2))
 840              {
 841                  $customFields[$key] = $split[0];
 842                  unset($this->vars[$importKey]);
 843              }
 844          }
 845          return array(FALSE, $customFields, $unrecognisedFields);
 846      }
 847  }
 848  ?>

title

Description

title

Description

title

Description

title

title

Body