/** * Import data from a file * * @param array $file * @return array */ public function onImport($file, $scope = NULL, $scope_id = NULL) { //file type $active = 'bib'; //get the file extension $extension = $file->getClientOriginalExtension(); //make sure we have a .bib file if ($active != $extension) { return; } //include bibtex file include_once PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'BibTex.php'; //create bibtex object $bibtex = new Structures_BibTex(); //feed bibtex lib the file $bibtex->loadFile($file->getPathname()); //parse file $bibtex->parse(); //get parsed citations $citations = $bibtex->data; //fix authors for ($i = 0; $i < count($citations); $i++) { $authors = array(); $auths = isset($citations[$i]['author']) ? $citations[$i]['author'] : ''; if ($auths != '') { foreach ($auths as $a) { if (isset($a['jr']) && $a['jr'] != '') { $authors[] = $a['last'] . ' ' . $a['jr'] . ', ' . $a['first']; } else { $authors[] = $a['last'] . ', ' . $a['first']; } } $citations[$i]['author'] = implode('; ', $authors); } //end if } //array to hold final citataions $final = array(); //check for duplicates for ($i = 0; $i < count($citations); $i++) { $duplicate = $this->checkDuplicateCitation($citations[$i], $scope, $scope_id); if ($duplicate) { $citations[$i]['duplicate'] = $duplicate; $final['attention'][] = $citations[$i]; } else { $citations[$i]['duplicate'] = 0; $final['no_attention'][] = $citations[$i]; } } return $final; }
/** * Converts the given string in bibtex format to a string whose format * is defined by the passed template string. * * @access public * @param string bibtex Bibtex code * @param string template template code * @return mixed Result string or PEAR_Error on failure */ function convert($bibtex) { // TODO Eliminate LaTeX syntax $this->_parser->loadString($bibtex); $stat = $this->_parser->parse(); if (!$stat) { return $stat; } return $this->display($this->_parser->data); }
/** * Download a citation for a publication * * @return void */ public function citationTask() { // Incoming $format = Request::getVar('type', 'bibtex'); // Get our model and load publication data $this->model = new Models\Publication($this->_identifier, $this->_version); // Make sure we got a result from the database if (!$this->model->exists() || $this->model->isDeleted()) { App::redirect(Route::url('index.php?option=' . $this->_option), Lang::txt('COM_PUBLICATIONS_RESOURCE_NOT_FOUND'), 'error'); return; } // Get version authors $authors = $this->model->table('Author')->getAuthors($this->model->version->get('id')); // Build publication path $path = $this->model->path('base', true); if (!is_dir($path)) { if (!Filesystem::makeDirectory(PATH_APP . $path, 0755, true, true)) { $this->setError('Error. Unable to create path.'); } } // Build the URL for this resource $sef = Route::url($this->model->link('version')); $url = Request::base() . ltrim($sef, '/'); // Choose the format switch ($format) { case 'endnote': $doc = "%0 " . Lang::txt('COM_PUBLICATIONS_GENERIC') . "\r\n"; $doc .= "%D " . Date::of($this->model->published())->toLocal('Y') . "\r\n"; $doc .= "%T " . trim(stripslashes($this->model->version->get('title'))) . "\r\n"; if ($authors) { foreach ($authors as $author) { $name = $author->name ? $author->name : $author->p_name; $auth = preg_replace('/{{(.*?)}}/s', '', $name); if (!strstr($auth, ',')) { $bits = explode(' ', $auth); $n = array_pop($bits) . ', '; $bits = array_map('trim', $bits); $auth = $n . trim(implode(' ', $bits)); } $doc .= "%A " . trim($auth) . "\r\n"; } } $doc .= "%U " . $url . "\r\n"; if ($this->model->published()) { $doc .= "%8 " . Date::of($this->model->published())->toLocal('M') . "\r\n"; } if ($this->model->version->get('doi')) { $doc .= "%1 " . 'doi:' . $this->model->version->get('doi'); $doc .= "\r\n"; } $file = 'publication' . $this->model->get('id') . '.enw'; $mime = 'application/x-endnote-refer'; break; case 'bibtex': default: include_once PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'BibTex.php'; $bibtex = new \Structures_BibTex(); $addarray = array(); $addarray['type'] = 'misc'; $addarray['cite'] = Config::get('sitename') . $this->model->get('id'); $addarray['title'] = stripslashes($this->model->version->get('title')); if ($authors) { $i = 0; foreach ($authors as $author) { $name = $author->name ? $author->name : $author->p_name; $author_arr = explode(',', $name); $author_arr = array_map('trim', $author_arr); $addarray['author'][$i]['first'] = isset($author_arr[1]) ? $author_arr[1] : ''; $addarray['author'][$i]['last'] = isset($author_arr[0]) ? $author_arr[0] : ''; $i++; } } $addarray['month'] = Date::of($this->model->published())->toLocal('M'); $addarray['url'] = $url; $addarray['year'] = Date::of($this->model->published())->toLocal('Y'); if ($this->model->version->get('doi')) { $addarray['doi'] = 'doi:' . DS . $this->model->version->get('doi'); } $bibtex->addEntry($addarray); $file = 'publication_' . $this->model->get('id') . '.bib'; $mime = 'application/x-bibtex'; $doc = $bibtex->bibTex(); break; } // Write the contents to a file $fp = fopen($path . DS . $file, "w") or die("can't open file"); fwrite($fp, $doc); fclose($fp); $this->_serveup(false, $path, $file, $mime); die; // REQUIRED }
static function __readBibFile($full_filename) { require_once 'Modules/Bibliographic/lib/PEAR_BibTex_1.0.0RC5/Structures/BibTex.php'; $bibtex_reader = new Structures_BibTex(); //Loading and parsing the file example.bib $ret = $bibtex_reader->loadFile($full_filename); $bibtex_reader->setOption("extractAuthors", false); $bibtex_reader->parse(); // Remove library-bug: if there is no cite, the library mixes up the key for the type and the first attribute. // It also shows an empty and therefore unwanted cite in the array. // // The cite is the text coming right after the type. Example: // @book {cite, // author = { "...."}, foreach ($bibtex_reader->data as $key => $entry) { if (empty($entry['cite'])) { unset($bibtex_reader->data[$key]['cite']); foreach ($entry as $attr_key => $attribute) { if (strpos($attr_key, '{') !== false) { unset($bibtex_reader->data[$key][$attr_key]); $attr_key_exploaded = explode('{', $attr_key); $bibtex_reader->data[$key]['entryType'] = trim($attr_key_exploaded[0]); $bibtex_reader->data[$key][trim($attr_key_exploaded[1])] = $attribute; } } } } return $bibtex_reader->data; }
/** * Format the file * * @param object $row Record to format * @return string */ public function format($row) { // get fields to not include for all citations $config = \Component::params('com_citations'); $exclude = $config->get('citation_download_exclude', ''); if (strpos($exclude, ',') !== false) { $exclude = str_replace(',', "\n", $exclude); } $exclude = array_values(array_filter(array_map('trim', explode("\n", $exclude)))); //get fields to not include for specific citation $cparams = new \Hubzero\Config\Registry($row->params); $citation_exclude = $cparams->get('exclude', ''); if (strpos($citation_exclude, ',') !== false) { $citation_exclude = str_replace(',', "\n", $citation_exclude); } $citation_exclude = array_values(array_filter(array_map('trim', explode("\n", $citation_exclude)))); //merge overall exclude and specific exclude $exclude = array_values(array_unique(array_merge($exclude, $citation_exclude))); include_once dirname(__DIR__) . DS . 'helpers' . DS . 'BibTex.php'; $bibtex = new \Structures_BibTex(); $addarray = array(); //get all the citation types $db = \App::get('db'); $ct = new Type($db); $types = $ct->getType(); //find the right title $type = ''; foreach ($types as $t) { if ($t['id'] == $row->type) { $type = $t['type']; } } $type = $type != '' ? $type : 'Generic'; if (!$row->cite) { $au = new \Components\Citations\Tables\Author($db); $authors = $au->getRecords(array('cid' => $row->id, 'start' => 0, 'limit' => 1)); foreach ($authors as $author) { $row->cite .= strtolower($author->surname); } $row->cite .= $row->year; $t = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($row->title)); $row->cite .= strlen($t) > 10 ? substr($t, 0, 10) : $t; } $addarray['type'] = $type; $addarray['cite'] = $row->cite; $addarray['title'] = $row->title; $addarray['address'] = $row->address; $auths = explode(';', $row->author); for ($i = 0, $n = count($auths); $i < $n; $i++) { $author = trim($auths[$i]); $author_arr = explode(',', $author); $author_arr = array_map('trim', $author_arr); $addarray['author'][$i]['first'] = isset($author_arr[1]) ? $author_arr[1] : ''; $addarray['author'][$i]['last'] = isset($author_arr[0]) ? $author_arr[0] : ''; $addarray['author'][$i]['first'] = preg_replace('/\\{\\{\\d+\\}\\}/', '', $addarray['author'][$i]['first']); $addarray['author'][$i]['last'] = preg_replace('/\\{\\{\\d+\\}\\}/', '', $addarray['author'][$i]['last']); } $addarray['booktitle'] = $row->booktitle; $addarray['chapter'] = $row->chapter; $addarray['edition'] = $row->edition; $addarray['editor'] = $row->editor; $addarray['eprint'] = $row->eprint; $addarray['howpublished'] = $row->howpublished; $addarray['institution'] = $row->institution; $addarray['journal'] = $row->journal; $addarray['key'] = $row->key; $addarray['location'] = $row->location; $addarray['month'] = $row->month != 0 || $row->month != '0' ? $row->month : ''; $addarray['note'] = $row->note; $addarray['number'] = $row->number; $addarray['organization'] = $row->organization; $addarray['pages'] = $row->pages != 0 || $row->pages != '0' ? $row->pages : ''; $addarray['publisher'] = $row->publisher; $addarray['series'] = $row->series; $addarray['school'] = $row->school; $addarray['url'] = $row->url; $addarray['volume'] = $row->volume; $addarray['year'] = $row->year; if ($row->journal != '') { $addarray['issn'] = $row->isbn; } else { $addarray['isbn'] = $row->isbn; } $addarray['doi'] = $row->doi; $addarray['language'] = $row->language; $addarray['accession_number'] = $row->accession_number; $addarray['short_title'] = html_entity_decode($row->short_title); $addarray['author_address'] = $row->author_address; $addarray['keywords'] = str_replace("\r\n", ', ', $row->keywords); $addarray['abstract'] = $row->abstract; $addarray['call_number'] = $row->call_number; $addarray['label'] = $row->label; $addarray['research_notes'] = $row->research_notes; foreach ($addarray as $k => $v) { if (in_array($k, $exclude)) { unset($addarray[$k]); } } $bibtex->addEntry($addarray); //$file = 'download_'.$id.'.bib'; //$mime = 'application/x-bibtex'; $doc = $bibtex->bibTex(); return $doc; }
/** * Extracting the data of one content * * The parse function splits the content into its entries. * Then every entry is parsed by this function. * It parses the entry backwards. * First the last '=' is searched and the value extracted from that. * A copy is made of the entry if warnings should be generated. This takes quite * some memory but it is needed to get good warnings. If nor warnings are generated * then you don have to worry about memory. * Then the last ',' is searched and the field extracted from that. * Again the entry is shortened. * Finally after all field=>value pairs the cite and type is extraced and the * authors are splitted. * If there is a problem false is returned. * * @access private * @param string $entry The entry * @return array The representation of the entry or false if there is a problem */ function _parseEntry($entry) { $entrycopy = ''; if ($this->_options['validate']) { $entrycopy = $entry; //We need a copy for printing the warnings } $ret = array('bibtex' => $entry.'}'); if ('@string' == strtolower(substr($entry, 0, 7))) { //String are not yet supported! if ($this->_options['validate']) { $this->_generateWarning('STRING_ENTRY_NOT_YET_SUPPORTED', '', $entry.'}'); } } elseif ('@preamble' == strtolower(substr($entry, 0, 9))) { //Preamble not yet supported! if ($this->_options['validate']) { $this->_generateWarning('PREAMBLE_ENTRY_NOT_YET_SUPPORTED', '', $entry.'}'); } } elseif ('@comment' == strtolower(substr($entry, 0, 8))) { // Just ignores } else { // Look for key $matches = array(); preg_match('/^@\w+\{([\w\d]+),/' ,$entry, $matches); if ( count($matches) > 0 ) { $ret['entrykey'] = $matches[1]; } //Parsing all fields while (strrpos($entry,'=') !== false) { $position = strrpos($entry, '='); //Checking that the equal sign is not quoted or is not inside a equation (For example in an abstract) $proceed = true; if (substr($entry, $position-1, 1) == '\\') { $proceed = false; } if ($proceed) { $proceed = $this->_checkEqualSign($entry, $position); } while (!$proceed) { $substring = substr($entry, 0, $position); $position = strrpos($substring,'='); $proceed = true; if (substr($entry, $position-1, 1) == '\\') { $proceed = false; } if ($proceed) { $proceed = $this->_checkEqualSign($entry, $position); } } $value = trim(substr($entry, $position+1)); $entry = substr($entry, 0, $position); if (',' == substr($value, strlen($value)-1, 1)) { $value = substr($value, 0, -1); } if ($this->_options['validate']) { $this->_validateValue($value, $entrycopy); } if ($this->_options['stripDelimiter']) { $value = $this->_stripDelimiter($value); } if ($this->_options['unwrap']) { $value = $this->_unwrap($value); } if ($this->_options['removeCurlyBraces']) { $value = $this->_removeCurlyBraces($value); } $position = strrpos($entry, ','); $field = strtolower(trim(substr($entry, $position+1))); $ret[$field] = $value; $entry = substr($entry, 0, $position); } //Parsing cite and entry type $arr = explode('{', $entry); $ret['cite'] = trim($arr[1]); $ret['entrytype'] = strtolower(trim($arr[0])); if ('@' == $ret['entrytype']{0}) { $ret['entrytype'] = substr($ret['entrytype'], 1); } if ($this->_options['validate']) { if (!$this->_checkAllowedEntryType($ret['entrytype'])) { $this->_generateWarning('WARNING_NOT_ALLOWED_ENTRY_TYPE', $ret['entrytype'], $entry.'}'); } } // Process accents foreach($ret as $key => &$value) if ($key != "bibtex") Structures_BibTex::process_accents($value); // Handling pages if (in_array('pages', array_keys($ret))) { $matches = array(); if (preg_match("/^\s*(\d+)(?:\s*--?\s*(\d+))?\s*$/", $ret['pages'], $matches)) { $ret['pages'] = new BibtexPages($matches[1], $matches[2]); } } //Handling the authors if (in_array('author', array_keys($ret)) && $this->_options['extractAuthors']) { $ret['author'] = $this->_extractAuthors($ret['author']); } //Handling the editors if (in_array('editor', array_keys($ret)) && $this->_options['extractAuthors']) { $ret['editor'] = $this->_extractAuthors($ret['editor']); } } return $ret; }
<?php error_reporting(E_ALL); require_once 'PEAR.php'; require_once 'Structures/BibTex.php'; $bibtex = new Structures_BibTex(); //Loading and parsing the file example.bib $ret = $bibtex->loadFile('example.bib'); if (PEAR::isError($ret)) { print $ret->getMessage(); die; } $bibtex->parse(); //Creating an entry $addarray = array(); $addarray['entryType'] = 'Article'; $addarray['cite'] = 'art2'; $addarray['title'] = 'Titel2'; $addarray['author'][0]['first'] = 'John'; $addarray['author'][0]['last'] = 'Doe'; $addarray['author'][1]['first'] = 'Jane'; $addarray['author'][1]['last'] = 'Doe'; //Adding the entry $bibtex->addEntry($addarray); //Printing the result echo "Converting This Array:\n\n"; echo "<pre>"; print_r($bibtex->data); echo "\nInto this:\n\n"; echo $bibtex->bibTex(); echo "<hr />";
/** * @param $full_filename * * @return array */ public static function __readBibFile($full_filename) { self::__setCharsetToUtf8($full_filename); require_once 'Modules/Bibliographic/lib/PEAR_BibTex_1.0.0RC5/Structures/BibTex.php'; $bibtex_reader = new Structures_BibTex(); //Loading and parsing the file example.bib $bibtex_reader->loadFile($full_filename); //replace bibtex special chars with the real characters $bibtex_reader->content = self::__convertBibSpecialChars($bibtex_reader->content); $bibtex_reader->setOption('extractAuthor', false); $bibtex_reader->parse(); // Remove library-bug: if there is no cite, the library mixes up the key for the type and the first attribute. // It also shows an empty and therefore unwanted cite in the array. // // The cite is the text coming right after the type. Example: // @book {cite, // author = { "...."}, foreach ($bibtex_reader->data as $key => $entry) { if (empty($entry['cite'])) { unset($bibtex_reader->data[$key]['cite']); foreach ($entry as $attr_key => $attribute) { if (strpos($attr_key, '{') !== false) { unset($bibtex_reader->data[$key][$attr_key]); $attr_key_exploaded = explode('{', $attr_key); $bibtex_reader->data[$key]['entryType'] = trim($attr_key_exploaded[0]); $bibtex_reader->data[$key][trim($attr_key_exploaded[1])] = $attribute; } } } // formating the author to the following type of string // Smith, John / Comte, Gabriel / von Gunten Jr, Thomas foreach ($entry as $attr_key => $attribute) { if ($attr_key == 'author' && is_array($attribute)) { $attribute_string = array(); foreach ($attribute as $author_key => $author) { $lastname = array($author['von'], $author['last'], $author['jr']); $attribute_string[$author_key] = implode(' ', array_filter($lastname)); if (!empty($author['first'])) { $attribute_string[$author_key] .= ', ' . $author['first']; } } $bibtex_reader->data[$key][$attr_key] = implode(' / ', $attribute_string); } } } return $bibtex_reader->data; }
public function _escape_tex($tex) { return parent::_escape_tex($tex); }
/** * Download a citation for a resource * * @return void */ public function citationTask() { $yearFormat = 'Y'; $monthFormat = 'M'; // Get contribtool params $tconfig = Component::params('com_tools'); // Incoming $id = Request::getInt('id', 0); $format = Request::getVar('format', 'bibtex'); // Append DOI handle $revision = Request::getVar('rev', 0); $handle = ''; if ($revision) { $rdoi = new Doi($this->database); $rdoi->loadDoi($id, $revision); if (isset($rdoi->doi) && $rdoi->doi && $tconfig->get('doi_shoulder')) { $handle = 'doi:' . $tconfig->get('doi_shoulder') . DS . strtoupper($rdoi->doi); } else { if ($rdoi->doi_label) { $handle = 'doi:10254/' . $tconfig->get('doi_prefix') . $id . '.' . $rdoi->doi_label; } } } // Load the resource $row = new Resource($this->database); $row->load($id); $thedate = $row->publish_up != '0000-00-00 00:00:00' ? $row->publish_up : $row->created; $helper = new Helper($row->id, $this->database); $helper->getUnlinkedContributors(); $row->author = $helper->ul_contributors; // Build the download path $path = PATH_APP . $this->config->get('cachepath', '/cache/resources'); $date = $row->created; $dir_resid = \Hubzero\Utility\String::pad($row->id); if ($date && preg_match("#([0-9]{4})-([0-9]{2})-([0-9]{2})[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})#", $date, $regs)) { $date = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); } $dir_year = date('Y', $date); $dir_month = date('m', $date); $path .= DS . $dir_year . DS . $dir_month . DS . $dir_resid . DS; if (!is_dir($path)) { if (!\Filesystem::makeDirectory($path)) { $this->setError('Error. Unable to create path.'); } } // Build the URL for this resource $sef = Route::url('index.php?option=' . $this->_option . '&id=' . $row->id); $url = Request::base() . ltrim($sef, '/'); // Choose the format switch ($format) { case 'endnote': $doc = ''; switch ($row->type) { case 'misc': default: $doc .= "%0 " . Lang::txt('COM_RESOURCES_GENERIC') . "\r\n"; break; // generic } $doc .= "%D " . Date::of($thedate)->toLocal($yearFormat) . "\r\n"; $doc .= "%T " . trim(stripslashes($row->title)) . "\r\n"; $author_array = explode(';', $row->author); foreach ($author_array as $auth) { $auth = preg_replace('/{{(.*?)}}/s', '', $auth); if (!strstr($auth, ',')) { $bits = explode(' ', $auth); $n = array_pop($bits) . ', '; $bits = array_map('trim', $bits); $auth = $n . trim(implode(' ', $bits)); } $doc .= "%A " . trim($auth) . "\r\n"; } $doc .= "%U " . $url . "\r\n"; if ($thedate) { $doc .= "%8 " . Date::of($thedate)->toLocal($monthFormat) . "\r\n"; } //$doc .= "\r\n"; if ($handle) { $doc .= "%1 " . 'doi:' . $handle; $doc .= "\r\n"; } $file = 'resource_' . $id . '.enw'; $mime = 'application/x-endnote-refer'; break; case 'bibtex': default: include_once PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'BibTex.php'; $bibtex = new \Structures_BibTex(); $addarray = array(); $addarray['type'] = 'misc'; $addarray['cite'] = $this->_config['sitename'] . $row->id; $addarray['title'] = stripslashes($row->title); $auths = explode(';', $row->author); for ($i = 0, $n = count($auths); $i < $n; $i++) { $author = trim($auths[$i]); $author = preg_replace('/\\{\\{(.+)\\}\\}/i', '', $author); if (strstr($author, ',')) { $author_arr = explode(',', $author); $author_arr = array_map('trim', $author_arr); $addarray['author'][$i]['first'] = isset($author_arr[1]) ? trim($author_arr[1]) : ''; $addarray['author'][$i]['last'] = isset($author_arr[0]) ? trim($author_arr[0]) : ''; } else { $author_arr = explode(' ', $author); $author_arr = array_map('trim', $author_arr); $last = array_pop($author_arr); $addarray['author'][$i]['first'] = count($author_arr) > 0 ? implode(' ', $author_arr) : ''; $addarray['author'][$i]['last'] = $last ? trim($last) : ''; } } $addarray['month'] = Date::of($thedate)->toLocal($monthFormat); $addarray['url'] = $url; $addarray['year'] = Date::of($thedatez)->toLocal($yearFormat); if ($handle) { $addarray['doi'] = $handle; } $bibtex->addEntry($addarray); $file = 'resource_' . $id . '.bib'; $mime = 'application/x-bibtex'; $doc = $bibtex->bibTex(); break; } // Write the contents to a file $fp = fopen($path . $file, "w") or die("can't open file"); fwrite($fp, $doc); fclose($fp); $this->_serveup(false, $path, $file, $mime); die; // REQUIRED }
<?php require_once 'BibTex.php'; $bibtex = new Structures_BibTex(); $bibtex->setOption('extractAuthors', false); $ret = $bibtex->loadFile('publis/Gramfort.bib'); if (PEAR::isError($ret)) { die($ret->getMessage()); } $bibtex->parse(); function clean_bibtex_string($str) { $bad_chars = array('{', '}'); return str_replace($bad_chars, "", $str); } function br2nl($str) { return preg_replace('/<br(\\s*)>/i', '\\n', $str); } function short_name($name) { $l = explode(',', $name); if (count($l) > 1) { $first = trim($l[1]); $last = $l[0]; } else { $l = explode(' ', $name); $first = $l[0]; $last = $l[1]; } $sname = $first[0] . '. ' . $last;