Example #1
0
function citeRecord($row, $citeStyle, $citeType, $markupPatternsArray, $encodeHTML)
{
    global $defaultTextCitationFormat;
    // defined in 'ini.inc.php'
    global $userOptionsArray;
    // '$userOptionsArray' is made globally available by function 'generateCitations()' in 'search.php'
    // output records suitable for citation within a text, e.g., like: "Ambrose 1991 {3735}", "Ambrose & Renaud 1995 {3243}" or "Ambrose et al. 2001 {4774}"
    if (!empty($userOptionsArray) and $userOptionsArray['use_custom_text_citation_format'] == "yes") {
        // if the user wants to use a custom text citation format
        $textCitationFormat = $userOptionsArray['text_citation_format'];
    } else {
        // use the default text citation format that was specified by the admin in 'ini.inc.php'
        $textCitationFormat = $defaultTextCitationFormat;
    }
    // this is a stupid hack that maps the names of the '$row' array keys to those used
    // by the '$formVars' array (which is required by function 'parsePlaceholderString()')
    // (eventually, the '$formVars' array should use the MySQL field names as names for its array keys)
    $formVars = buildFormVarsArray($row);
    // function 'buildFormVarsArray()' is defined in 'include.inc.php'
    if (preg_match("/RTF|LaTeX/i", $citeType)) {
        $textCitationFormat = preg_replace("/([{}])/i", "\\\\1", $textCitationFormat);
        // in case of RTF or LaTeX output we need to escape braces in placeholder strings
        $fallbackPlaceholderString = "<:authors[2| & | et al.]:>< :year:>< \\{:recordIdentifier:\\}>";
    } else {
        $fallbackPlaceholderString = "<:authors[2| & | et al.]:>< :year:>< {:recordIdentifier:}>";
    }
    // generate a text citation according to the given naming scheme:
    $record = parsePlaceholderString($formVars, $textCitationFormat, $fallbackPlaceholderString);
    // function 'parsePlaceholderString()' is defined in 'include.inc.php'
    // Perform search & replace actions on the text:
    $searchReplaceActionsArray["(et +al\\.)"] = $markupPatternsArray["italic-prefix"] . "\\1" . $markupPatternsArray["italic-suffix"];
    // print 'et al.' in italic
    $record = searchReplaceText($searchReplaceActionsArray, $record, false);
    // function 'searchReplaceText()' is defined in 'include.inc.php'
    return $record;
}
Example #2
0
function printLinks($showLinkTypes, $row, $showQuery, $showLinks, $wrapResults, $userID, $viewType, $orderBy)
{
    global $databaseBaseURL;
    // these variables are defined in 'ini.inc.php'
    global $filesBaseURL;
    global $fileVisibility;
    global $fileVisibilityException;
    global $openURLResolver;
    global $isbnURLFormat;
    global $tableRefs, $tableUserData;
    // defined in 'db.inc.php'
    global $loc;
    // '$loc' is made globally available in 'core.php'
    global $client;
    // Note: for proper placement of links within the Links column we don't use the 'mergeLinks()' function here (as is done for Details view),
    //       since spacing before links is handled individually for each link type
    $links = "";
    // make sure that our buffer variable is empty
    // count the number of available link elements:
    $linkElementCounterLoggedOut = 0;
    // if the 'user_permissions' session variable contains 'allow_details_view'...
    if (in_array("details", $showLinkTypes) and isset($_SESSION['user_permissions']) and preg_match("/allow_details_view/", $_SESSION['user_permissions'])) {
        $linkElementCounterLoggedOut = $linkElementCounterLoggedOut + 1;
    }
    // if the 'user_permissions' session variable contains 'allow_edit'...
    if (in_array("edit", $showLinkTypes) and isset($_SESSION['user_permissions']) and preg_match("/allow_edit/", $_SESSION['user_permissions'])) {
        $linkElementCounterLoggedOut = $linkElementCounterLoggedOut + 1;
    }
    // if either the URL or the DOI field contain something
    if (in_array("url", $showLinkTypes) and !empty($row["url"]) or in_array("doi", $showLinkTypes) and !empty($row["doi"])) {
        $linkElementCounterLoggedOut = $linkElementCounterLoggedOut + 1;
    } elseif (in_array("isbn", $showLinkTypes) and !empty($isbnURLFormat) and !empty($row["isbn"])) {
        // provide a link to an ISBN resolver
        $linkElementCounterLoggedOut = $linkElementCounterLoggedOut + 1;
    } elseif (in_array("xref", $showLinkTypes) and !empty($openURLResolver)) {
        $linkElementCounterLoggedOut = $linkElementCounterLoggedOut + 1;
    }
    $linkElementCounterLoggedIn = $linkElementCounterLoggedOut;
    // if a user is logged in and a FILE is associated with the current record
    if (in_array("file", $showLinkTypes) and ($fileVisibility == "everyone" or $fileVisibility == "login" and isset($_SESSION['loginEmail']) or $fileVisibility == "user-specific" and (isset($_SESSION['user_permissions']) and preg_match("/allow_download/", $_SESSION['user_permissions'])) or !empty($fileVisibilityException) and preg_match($fileVisibilityException[1], $row[$fileVisibilityException[0]]))) {
        if (!empty($row["file"])) {
            // if the 'file' field is NOT empty
            $linkElementCounterLoggedIn = $linkElementCounterLoggedIn + 1;
        }
    }
    if (preg_match("/^inc/i", $client)) {
        // we open links in a new browser window if refbase data are included somewhere else:
        $target = " target=\"_blank\"";
    } else {
        $target = "";
    }
    if (preg_match("/^(cli|inc)/i", $client) or $wrapResults == "0") {
        // we use absolute links for CLI clients, for include mechanisms, or when returning only a partial document structure
        $baseURL = $databaseBaseURL;
    } else {
        $baseURL = "";
    }
    if (in_array("details", $showLinkTypes) and isset($_SESSION['user_permissions']) and preg_match("/allow_details_view/", $_SESSION['user_permissions'])) {
        // display a link that opens the Details view for this record:
        // NOTE: we use a 'show.php' URL here since it is much shorter and easier to bookmark as a permanent link; however,
        //       this means one additional redirect; the old code that directly generates a 'search.php' URL is commented out below
        // TODO: verify that the time lag introduced by the redirect action is generally acceptable!
        $queryParametersArray = array("record" => $row["serial"]);
        // we only add further parameters to the 'show.php' URL if their current value differs from the defaults used by 'show.php' or 'search.php':
        if (!empty($viewType) and !preg_match("/^Web\$/i", $viewType)) {
            $queryParametersArray["viewType"] = $viewType;
        }
        if ($showQuery == "1") {
            $queryParametersArray["showQuery"] = $showQuery;
        }
        if ($showLinks == "0") {
            // this is kinda superfluous since, for '$showLinks=0', the link isn't shown in the first place
            $queryParametersArray["showLinks"] = $showLinks;
        }
        $links .= "\n\t\t<a href=\"" . $baseURL . generateURL("show.php", "html", $queryParametersArray, true) . "\"" . $target . ">" . "<i class=\"fa fa-search\"></i></a>";
        // Old code that directly generates a 'search.php' URL which points to Details view for this record:
        //			// Construct the SQL query:
        //			// TODO: build the complete SQL query first (using functions 'buildFROMclause()' and 'buildORDERclause()'), then rawurlencode and add to link
        //			$showDetailsQuery = buildSELECTclause("Display", $showLinks, "", false, false); // function 'buildSELECTclause()' is defined in 'include.inc.php'
        //
        //			// ... display a link that opens the Details view for this record:
        //			if (isset($_SESSION['loginEmail'])) // if a user is logged in, show user specific fields:
        //				$links .= "\n\t\t<a href=\"" . $baseURL . "search.php"
        //				        . "?sqlQuery=" . rawurlencode($showDetailsQuery) . "%20FROM%20" . $tableRefs . "%20LEFT%20JOIN%20" . $tableUserData . "%20ON%20serial%20%3D%20record_id%20AND%20user_id%20%3D%20" . $userID . "%20";
        //			else // if NO user logged in, don't display any user specific fields and hide the 'location' field:
        //				$links .= "\n\t\t<a href=\"" . $baseURL . "search.php"
        //				        . "?sqlQuery=" . rawurlencode($showDetailsQuery) . "%20FROM%20" . $tableRefs . "%20";
        //
        //			$links .= "WHERE%20serial%20RLIKE%20%22%5E%28" . $row["serial"]
        //			        . "%29%24%22%20ORDER%20BY%20" . rawurlencode($orderBy)
        //			        . "&amp;formType=sqlSearch"
        //			        . "&amp;showQuery=" . $showQuery
        //			        . "&amp;showLinks=" . $showLinks
        //			        . "&amp;submit=Display"
        //			        . "&amp;viewType=" . $viewType
        //			        . "\"" . $target . ">"
        //			        . "<img src=\"" . $baseURL . "img/details.gif\" alt=\"" . $loc["details"] . "\" title=\"" . $loc["LinkTitle_ShowDetails"] . "\" width=\"9\" height=\"17\" hspace=\"0\" border=\"0\"></a>";
    }
    if (($linkElementCounterLoggedOut > 0 or isset($_SESSION['loginEmail']) and $linkElementCounterLoggedIn > 0) and (in_array("details", $showLinkTypes) and isset($_SESSION['user_permissions']) and preg_match("/allow_details_view/", $_SESSION['user_permissions']))) {
        $links .= "&nbsp;&nbsp;";
    }
    if (in_array("edit", $showLinkTypes) and isset($_SESSION['user_permissions']) and preg_match("/allow_edit/", $_SESSION['user_permissions'])) {
        // if the 'user_permissions' session variable contains 'allow_edit'...
        // ... display a link that opens the edit form for this record:
        $links .= "\n\t\t<a href=\"" . $baseURL . "record.php" . "?serialNo=" . $row["serial"] . "&amp;recordAction=edit" . "\"" . $target . ">" . "<i class=\"fa fa-pencil\"></i></a>";
    }
    if (($linkElementCounterLoggedOut > 1 or isset($_SESSION['loginEmail']) and $linkElementCounterLoggedIn > 1) and (in_array("edit", $showLinkTypes) and isset($_SESSION['user_permissions']) and preg_match("/allow_edit/", $_SESSION['user_permissions']))) {
        if (in_array("details", $showLinkTypes) and isset($_SESSION['user_permissions']) and preg_match("/allow_details_view/", $_SESSION['user_permissions'])) {
            $links .= "\n\t\t";
        } else {
            $links .= "&nbsp;&nbsp;";
        }
    }
    // show a link to any corresponding file if one of the following conditions is met:
    // - the variable '$fileVisibility' (defined in 'ini.inc.php') is set to 'everyone'
    // - the variable '$fileVisibility' is set to 'login' AND the user is logged in
    // - the variable '$fileVisibility' is set to 'user-specific' AND the 'user_permissions' session variable contains 'allow_download'
    // - the array variable '$fileVisibilityException' (defined in 'ini.inc.php') contains a pattern (in array element 1) that matches the contents of the field given (in array element 0)
    if (in_array("file", $showLinkTypes) and ($fileVisibility == "everyone" or $fileVisibility == "login" and isset($_SESSION['loginEmail']) or $fileVisibility == "user-specific" and (isset($_SESSION['user_permissions']) and preg_match("/allow_download/", $_SESSION['user_permissions'])) or !empty($fileVisibilityException) and preg_match($fileVisibilityException[1], $row[$fileVisibilityException[0]]))) {
        if (!empty($row["file"])) {
            if (preg_match("#^(https?|ftp|file)://#i", $row["file"])) {
                // if the 'file' field contains a full URL (starting with "http://", "https://", "ftp://" or "file://")
                $URLprefix = "";
            } else {
                // use the base URL of the standard files directory as prefix:
                if (preg_match('#^/#', $filesBaseURL)) {
                    if (preg_match("/^(cli|inc)/i", $client) or $wrapResults == "0") {
                        // we use absolute links for CLI clients, for include mechanisms, or when returning only a partial document structure
                        $URLprefix = 'http://' . $_SERVER['HTTP_HOST'] . $filesBaseURL;
                    } else {
                        $URLprefix = $filesBaseURL;
                    }
                } else {
                    // relative path -> file dir is located within refbase root dir
                    $URLprefix = $baseURL . $filesBaseURL;
                }
            }
            if (preg_match("/\\.pdf\$/i", $row["file"])) {
                // if the 'file' field contains a link to a PDF file
                $links .= "\n\t\t<a href=\"" . $URLprefix . $row["file"] . "\"" . $target . "><img src=\"" . $baseURL . "img/file_PDF.gif\" alt=\"" . $loc["pdf"] . "\" title=\"" . $loc["LinkTitle_DownloadPDFFile"] . "\" width=\"17\" height=\"17\" hspace=\"0\" border=\"0\"></a>";
            } else {
                $links .= "\n\t\t<a href=\"" . $URLprefix . $row["file"] . "\"" . $target . "><img src=\"" . $baseURL . "img/file.gif\" alt=\"" . $loc["file"] . "\" title=\"" . $loc["LinkTitle_DownloadFile"] . "\" width=\"11\" height=\"15\" hspace=\"0\" border=\"0\"></a>";
            }
            // display a generic file icon as download link
        }
    }
    // if a DOI number exists for this record, we'll prefer it as link, otherwise we use the URL (if available):
    // (note, that in List view, we'll use the same icon, no matter if the DOI or the URL is used for the link)
    if (in_array("doi", $showLinkTypes) and !empty($row["doi"])) {
        $links .= "\n\t\t<a href=\"http://dx.doi.org/" . rawurlencode($row["doi"]) . "\"" . $target . "><img src=\"" . $baseURL . "img/link.gif\" alt=\"" . $loc["doi"] . "\" title=\"" . $loc["LinkTitle_GotoWebPageViaDOI"] . "\" width=\"11\" height=\"8\" hspace=\"0\" border=\"0\"></a>";
    } elseif (in_array("url", $showLinkTypes) and !empty($row["url"])) {
        // 'htmlentities()' is used to convert any '&' into '&amp;'
        $links .= "\n\t\t<a href=\"" . encodeHTML($row["url"]) . "\"" . $target . "><img src=\"" . $baseURL . "img/link.gif\" alt=\"" . $loc["url"] . "\" title=\"" . $loc["LinkTitle_GotoWebPage"] . "\" width=\"11\" height=\"8\" hspace=\"0\" border=\"0\"></a>";
    } elseif (in_array("isbn", $showLinkTypes) and !empty($isbnURLFormat) and !empty($row["isbn"])) {
        // this is a stupid hack that maps the names of the '$row' array keys to those used
        // by the '$formVars' array (which is required by function 'parsePlaceholderString()')
        // (eventually, the '$formVars' array should use the MySQL field names as names for its array keys)
        $formVars = buildFormVarsArray($row);
        // function 'buildFormVarsArray()' is defined in 'include.inc.php'
        // auto-generate an ISBN link according to the naming scheme given in '$isbnURLFormat' (in 'ini.inc.php'):
        $isbnURL = parsePlaceholderString($formVars, $isbnURLFormat, "");
        // function 'parsePlaceholderString()' is defined in 'include.inc.php'
        $encodedURL = encodeHTML($isbnURL);
        // 'htmlentities()' is used to convert higher ASCII chars into its entities and any '&' into '&amp;'
        $encodedURL = str_replace(" ", "%20", $encodedURL);
        // ensure that any spaces are also properly urlencoded
        if (!empty($isbnURL)) {
            $links .= "\n\t\t<a href=\"" . $encodedURL . "\"" . $target . "><i class=\"fa fa-external-link\"></i></a>";
        }
    } elseif (in_array("xref", $showLinkTypes) and !empty($openURLResolver)) {
        $openURL = openURL($row);
        // function 'openURL()' is defined in 'openurl.inc.php'
        $links .= "\n\t\t<a href=\"" . $openURL . "\"" . " target=\"_blank\"><i class=\"fa fa-external-link\"></i></a>";
    }
    // insert COinS (ContextObjects in Spans):
    $links .= "\n\t\t" . coins($row);
    // function 'coins()' is defined in 'openurl.inc.php'
    return $links;
}
Example #3
0
function citeRecords($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $wrapResults, $citeStyle, $citeOrder, $citeType, $orderBy, $headerMsg, $userID, $viewType)
{
    global $contentTypeCharset;
    // defined in 'ini.inc.php'
    global $client;
    // The array '$transtab_refbase_latex' contains search & replace patterns for conversion from refbase markup to LaTeX markup & entities.
    // Converts refbase fontshape markup (italic, bold) into LaTeX commands of the 'textcomp' package, super- and subscript as well as greek
    // symbols get converted into the respective commands in math mode. You may need to adopt the LaTeX markup to suit your individual needs.
    global $transtab_refbase_latex;
    // defined in 'transtab_refbase_latex.inc.php'
    // The arrays '$transtab_latin1_latex' and '$transtab_unicode_latex' provide translation tables for best-effort conversion of higher ASCII
    // characters from ISO-8859-1 (or Unicode, respectively) to LaTeX entities.
    global $transtab_latin1_latex;
    // defined in 'transtab_latin1_latex.inc.php'
    global $transtab_unicode_latex;
    // defined in 'transtab_unicode_latex.inc.php'
    // --- Begin style-specific settings ----------------------------------
    // NOTE: the given settings are meant to be used with the natbib package;
    //       you'll have to adopt these settings if you'd like to generate a
    //       .bbl file for another style/package
    // 1) Define header with .bst style-specific declarations:
    // NOTE: since this header is normally inserted by BibTeX from the used .bst style, I'm not sure if there's a variant of this header that's
    //       universally accepted by natbib. So, if necessary adopt it to your needs.
    // -- by default, we use this header (as inserted by a .bst style that was generated from 'merlin.mbs' via the docstrip utility):
    $bblHeader = "\\providecommand{\\natexlab}[1]{#1}" . "\n" . "\\providecommand{\\url}[1]{\\texttt{#1}}" . "\n" . "\\providecommand{\\urlprefix}{URL }" . "\n" . "\\providecommand{\\eprint}[2][]{\\url{#2}}" . "\n\n";
    // -- here's another header example (as inserted by 'elsart-harv.bst'):
    //		$bblHeader = "\\expandafter\\ifx\\csname natexlab\\endcsname\\relax\\def\\natexlab#1{#1}\\fi" . "\n"
    //		           . "\\expandafter\\ifx\\csname url\\endcsname\\relax" . "\n"
    //		           . "  \\def\\url#1{\\texttt{#1}}\\fi" . "\n"
    //		           . "\\expandafter\\ifx\\csname urlprefix\\endcsname\\relax\\def\\urlprefix{URL }\\fi" . "\n\n";
    // 2) Define name of \bibitem command:
    $bibItemCommand = "\\bibitem";
    // use "\\harvarditem" for the Harvard family of styles
    // 3) Define variables and placeholder strings which together will form the \bibitem option string:
    // -- variables:
    $betweenShortAuthorsDelim = " & ";
    // used to connect individual author names in the short author list
    $betweenFullAuthorsDelim = ", ";
    // used to connect multiple authors in the full author list
    $betweenLastAuthorsDelim = " & ";
    // used to connect the second-to-last author with the last author in the full author list
    $etalIdentifierString = " et~al.";
    // appended to the first author's last name if the record's number of authors exceeds the number given in '$maxAuthorCountInShortAuthorList'
    $maxAuthorCountInShortAuthorList = 2;
    // maximum number of authors to be used in the short author list
    // -- placeholder strings:
    // (please see the refbase online documentation for more info about placeholders and their syntax: <http://placeholders.refbase.net/>)
    $year = "<:year[4]:>";
    // year format, e.g. "1990"
    $shortAuthorList = "<:authors[" . $maxAuthorCountInShortAuthorList . "|" . $betweenShortAuthorsDelim . "|" . $etalIdentifierString . "]:>";
    // format of the short author list which is used as text citation, e.g. "Jones", "Jones and Baker" or "Jones et al."
    $fullAuthorList = "<:authors[0|_#_§_~_|]:>";
    // format of the full author list, e.g. "Jones, Baker, and Williams"
    // NOTE: in the above placeholder string, we use the string "_#_§_~_" as author delimiter which allows us to uniquely identify that delimiter again below, and replace it with the contents of either '$betweenFullAuthorsDelim' or '$betweenLastAuthorsDelim' (depending on its position)
    // 4) Define \bibitem option format:
    // -- extended natbib 5.3 style:
    $bibItemOptionShort = "[{" . $shortAuthorList . "}(" . $year . ")" . "]";
    // e.g.: \bibitem[{Jones et al.}(1990)]{key}...
    $bibItemOptionFull = "[{" . $shortAuthorList . "}(" . $year . "){" . $fullAuthorList . "}]";
    // e.g.: \bibitem[{Jones et al.}(1990){Jones, Baker, and Williams}]{key}...
    // NOTE: since the author lists may contain parentheses, we need to enclose them in curly brackets to work around a natbib limitation
    // -- native natbib style:
    //		$bibItemOptionShort = "[" . $shortAuthorList . "(" . $year . ")" . "]"; // e.g.: \bibitem[Jones et al.(1990)]{key}...
    //		$bibItemOptionFull = "";
    // -- apalike style:
    //		$bibItemOptionShort = "[" . $shortAuthorList . ", " . $year . "]"; // e.g.: \bibitem[Jones et al., 1990]{key}...
    //		$bibItemOptionFull = "";
    // -- newapa or chicago styles:
    //		$bibItemOptionShort = "[\\protect\\citeauthoryear{" . $fullAuthorList . "}{" . $shortAuthorList . "}{" . $year . "}" . "]"; // this assumes that it's not allowed to omit the full author list, though I dunno)
    //		$bibItemOptionFull = "[\\protect\\citeauthoryear{" . $fullAuthorList . "}{" . $shortAuthorList . "}{" . $year . "}" . "]"; // e.g.: \bibitem[\protect\citeauthoryear{Jones, Baker, and Williams}{Jones et al.}{1990}]{key}...
    // -- named style:
    //		$bibItemOptionShort = "[\\protect\\citeauthoryear{" . $shortAuthorList . "}{" . $year . "}" . "]"; // e.g.: \bibitem[\protect\citeauthoryear{Jones et al.}{1990}]{key}...
    //		$bibItemOptionFull = "";
    // -- astron style:
    //		$bibItemOptionShort = "[\\protect\\astroncite{" . $shortAuthorList . "}{" . $year . "}" . "]"; // e.g.: \bibitem[\protect\astroncite{Jones et al.}{1990}]{key}...
    //		$bibItemOptionFull = "";
    // -- authordate style:
    //		$bibItemOptionShort = "[\\protect\\citename{" . $shortAuthorList . ", }" . $year . "]"; // e.g.: \bibitem[\protect\citename{Jones et al., }1990]{key}...
    //		$bibItemOptionFull = "";
    // -- harvard style:
    //		$bibItemOptionShort = "[" . $shortAuthorList . "]{" . $fullAuthorList . "}{" . $year . "}"; // this assumes that it's not allowed to omit the full author list, though I dunno)
    //		$bibItemOptionFull = "[" . $shortAuthorList . "]{" . $fullAuthorList . "}{" . $year . "}"; // e.g.: \harvarditem[Jones et al.]{Jones, Baker, and Williams}{1990}{key}...
    // 5) Define deduplication prefix and suffix strings:
    //    Identical text citation strings get uniquified by appending letters to the year, e.g. duplicate occurrences
    //    of "Jones et al. 1990" should become "Jones et al. 1990a" and "Jones et al. 1990b" in the final output.
    //    These prefix/suffix strings will be inserted before/after the deduplication letter:
    $dedupPrefix = "{\\natexlab{";
    // these prefix/suffix strings are required by natbib; if any custom command (such as '\natexlab') is used, make sure that the command is also defined above in variable '$bblHeader'
    $dedupSuffix = "}}";
    // --- End style-specific settings ------------------------------------
    // Initialize array variables:
    $yearsArray = array();
    $typeTitlesArray = array();
    $bibItemsArray = array();
    // Define inline text markup to be used by the 'citeRecord()' function:
    $markupPatternsArray = array("bold-prefix" => "\\textbf{", "bold-suffix" => "}", "italic-prefix" => "\\textit{", "italic-suffix" => "}", "underline-prefix" => "\\ul{", "underline-suffix" => "}", "endash" => "--", "emdash" => "---", "ampersand" => "&", "double-quote" => '"', "double-quote-left" => "{\\textquotedblleft}", "double-quote-right" => "{\\textquotedblright}", "single-quote" => "'", "single-quote-left" => "{\\textquoteleft}", "single-quote-right" => "{\\textquoteright}", "less-than" => "<", "greater-than" => ">", "newline" => "\n\n");
    // Defines search & replace 'actions' that will be applied upon LaTeX output to all those refbase fields that are listed
    // in the corresponding 'fields' element:
    $latexSearchReplaceActionsArray = array(array('fields' => array("title", "publication", "abbrev_journal", "address", "keywords", "abstract", "orig_title", "series_title", "abbrev_series_title", "notes"), 'actions' => $transtab_refbase_latex));
    // For CLI queries, we'll allow paging thru the result set, i.e. we honour the values of the CLI options '-S|--start' ('$rowOffset')
    // and '-R|--rows' ('$showRows') ('$rowOffset' and '$showRows' are re-assigned in function 'seekInMySQLResultsToOffset()' in 'include.inc.php')
    if (preg_match("/^cli/i", $client)) {
        // if the query originated from a command line client such as the "refbase" CLI client ("cli-refbase-1.0")
        $showMaxRows = $showRows;
    } else {
        $showMaxRows = $rowsFound;
    }
    // otherwise show all rows
    // Setup the basic .bbl document structure:
    $latexData = "\\begin{thebibliography}{" . $showMaxRows . "}\n\n";
    // Add header with .bst style-specific declarations:
    $latexData .= $bblHeader;
    // LOOP OVER EACH RECORD:
    // Fetch one page of results (or less if on the last page)
    // (i.e., upto the limit specified in $showMaxRows) fetch a row into the $row array and ...
    for ($rowCounter = 0; $rowCounter < $showMaxRows && ($row = @mysql_fetch_array($result)); $rowCounter++) {
        foreach ($row as $rowFieldName => $rowFieldValue) {
            // Apply search & replace 'actions' to all fields that are listed in the 'fields' element of the arrays contained in '$latexSearchReplaceActionsArray':
            foreach ($latexSearchReplaceActionsArray as $fieldActionsArray) {
                if (in_array($rowFieldName, $fieldActionsArray['fields'])) {
                    $row[$rowFieldName] = searchReplaceText($fieldActionsArray['actions'], $row[$rowFieldName], true);
                }
            }
        }
        // function 'searchReplaceText()' is defined in 'include.inc.php'
        // Order attributes according to the chosen output style & record type:
        $record = citeRecord($row, $citeStyle, $citeType, $markupPatternsArray, false);
        // function 'citeRecord()' is defined in the citation style file given in '$citeStyleFile' (which, in turn, must reside in the 'cite' directory of the refbase root directory), see function 'generateCitations()'
        // Print out the current record:
        if (!empty($record)) {
            // This is a stupid hack that maps the names of the '$row' array keys to those used
            // by the '$formVars' array (which is required by function 'generateCiteKey()')
            // (eventually, the '$formVars' array should use the MySQL field names as names for its array keys)
            $formVars = buildFormVarsArray($row);
            // function 'buildFormVarsArray()' is defined in 'include.inc.php'
            // Generate or extract the cite key for this record:
            // NOTE: currently, the following placeholders are not available for citation output:
            //       <:keywords:>, <:issn:>, <:area:>, <:notes:>, <:userKeys:>
            //       if the cite key specification uses one of these placeholders, it will get ignored
            $citeKey = generateCiteKey($formVars);
            // function 'generateCiteKey()' is defined in 'include.inc.php'
            // The '\bibitem' command requires a cite key, which is why we'll include the record's serial number
            // even when the user's export options specify 'export_cite_keys=no' or 'autogenerate_cite_keys=no':
            // NOTE: maybe we should always generate a cite key here, even if 'export_cite_keys=no' or 'autogenerate_cite_keys=no'??
            if (empty($citeKey)) {
                $citeKey = $row['serial'];
            }
            // Generate the \bibitem option string that's used to build the proper text citation:
            $bibItemOptionShortString = parsePlaceholderString($formVars, $bibItemOptionShort, "<:authors[2| and | et~al.]:><(:year:)>");
            // function 'parsePlaceholderString()' is defined in 'include.inc.php'
            if (!empty($bibItemOptionFull) and preg_match("/^[^;]+(;[^;]+){" . $maxAuthorCountInShortAuthorList . "}/", $row['author'])) {
                // include full author list:
                $bibItemOptionString = parsePlaceholderString($formVars, $bibItemOptionFull, "<:authors[2| and | et~al.]:><(:year:)><:authors[0|, |]:>");
                $bibItemOptionString = preg_replace("/_#_§_~_(?!.*?_#_§_~_)/", $betweenLastAuthorsDelim, $bibItemOptionString);
                // replace last occurrence of "_#_§_~_"
                $bibItemOptionString = preg_replace("/_#_§_~_/", $betweenFullAuthorsDelim, $bibItemOptionString);
                // replace all other occurrences of "_#_§_~_"
            } else {
                // only include short author list:
                $bibItemOptionString = $bibItemOptionShortString;
            }
            // In case of duplicate text citation strings, append a letter to the year in the \bibitem option string as well as in the formatted reference:
            // NOTE: - this is not fool proof and currently only works if there are no more than 26 duplicate text citations (letters a-z)
            //       - the below replace actions get triggered on the first four-digit number that happens to be identical to the record's year, but depending on the reference format, this may not be the actual year of the reference but some other number!
            for ($i = 0; isset($bibItemsArray[$bibItemOptionShortString]); $i++) {
                // Update the existing \bibitem entry (that has an identical text citation string) and append an "a" to it's year items:
                if ($i == 0) {
                    $dedupPrefixQuoted = preg_quote($dedupPrefix, "/");
                    // escape meta characters (including '/' that is used as delimiter for the PCRE replace functions below and which gets passed as second argument)
                    $dedupSuffixQuoted = preg_quote($dedupSuffix, "/");
                    $oldBibItemOptionShortString = preg_replace("/^\\[(.+)\\]\$/", "\\1", $bibItemOptionShortString);
                    // remove square brackets from short \bibitem option string (which is required for the subsequent 'str_replace()' action to work with short and full option strings)
                    $newBibItemOptionShortString = preg_replace("/(" . $row['year'] . ")(" . $dedupPrefixQuoted . "[a-z]*" . $dedupSuffixQuoted . ")*/", "\\1" . $dedupPrefix . "a" . $dedupSuffix, $oldBibItemOptionShortString, 1);
                    $bibItemsArray[$bibItemOptionShortString] = str_replace($oldBibItemOptionShortString, $newBibItemOptionShortString, $bibItemsArray[$bibItemOptionShortString]);
                    $bibItemsArray[$bibItemOptionShortString] = preg_replace("/(" . $row['year'] . ")(" . $dedupPrefixQuoted . "[a-z]*" . $dedupSuffixQuoted . ")*(?!.*?" . $row['year'] . ")/", "\\1" . $dedupPrefix . "a" . $dedupSuffix, $bibItemsArray[$bibItemOptionShortString], 1);
                    // note that this will fail if the formatted reference contains a number after the year that is identical to the year!
                }
                // Append a letter to the year items of the current \bibitem entry:
                $bibItemOptionShortString = preg_replace("/(" . $row['year'] . ")(" . $dedupPrefixQuoted . "[a-z]*" . $dedupSuffixQuoted . ")*/e", "'\\1{$dedupPrefix}'.chr(98 + {$i}).'{$dedupSuffix}'", $bibItemOptionShortString, 1);
                // the 'e' modifier allows to execute PHP code within the replacement pattern
                $bibItemOptionString = preg_replace("/(" . $row['year'] . ")(" . $dedupPrefixQuoted . "[a-z]*" . $dedupSuffixQuoted . ")*/e", "'\\1{$dedupPrefix}'.chr(98 + {$i}).'{$dedupSuffix}'", $bibItemOptionString, 1);
                $record = preg_replace("/(" . $row['year'] . ")(" . $dedupPrefixQuoted . "[a-z]*" . $dedupSuffixQuoted . ")*/e", "'\\1{$dedupPrefix}'.chr(98 + {$i}).'{$dedupSuffix}'", $record, 1);
            }
            // Attempt to convert higher ASCII chars (i.e., characters with an ASCII value of >= 128) to their corresponding LaTeX entities:
            if ($contentTypeCharset == "UTF-8") {
                $recordEncoded = searchReplaceText($transtab_unicode_latex, $record, false);
            } else {
                $recordEncoded = searchReplaceText($transtab_latin1_latex, $record, false);
            }
            // We have to make sure that the \bibitem option string also contains proper LaTeX entities:
            if ($contentTypeCharset == "UTF-8") {
                $bibItemOptionStringEncoded = searchReplaceText($transtab_unicode_latex, $bibItemOptionString, false);
            } else {
                $bibItemOptionStringEncoded = searchReplaceText($transtab_latin1_latex, $bibItemOptionString, false);
            }
            // Copy the current \bibitem entry to the array of generated \bibitem entries:
            $bibItemsArray[$bibItemOptionShortString] = $bibItemCommand . $bibItemOptionStringEncoded . "{" . $citeKey . "} " . $recordEncoded;
        }
    }
    $latexData .= implode("\n\n", $bibItemsArray) . "\n\n";
    $latexData .= "\\end{thebibliography}\n\n";
    return $latexData;
}
Example #4
0
function handleFileUploads($uploadFile, $formVars)
{
    global $filesBaseDir;
    // these variables are defined in 'ini.inc.php'
    global $moveFilesIntoSubDirectories;
    global $dirNamingScheme;
    global $renameUploadedFiles;
    global $fileNamingScheme;
    global $handleNonASCIIChars;
    global $allowedFileNameCharacters;
    global $allowedDirNameCharacters;
    global $changeCaseInFileNames;
    global $changeCaseInDirNames;
    $tmpFilePath = $uploadFile["tmp_name"];
    // Generate file name:
    if ($renameUploadedFiles == "yes") {
        if (preg_match("/.+\\.[^.]+\$/i", $uploadFile["name"])) {
            // preserve any existing file name extension
            $fileNameExtension = preg_replace("/.+(\\.[^.]+)\$/i", "\\1", $uploadFile["name"]);
        } else {
            $fileNameExtension = "";
        }
        // auto-generate a file name according to the naming scheme given in '$fileNamingScheme':
        $newFileName = parsePlaceholderString($formVars, $fileNamingScheme, "<:serial:>");
        // function 'parsePlaceholderString()' is defined in 'include.inc.php'
        // handle non-ASCII and unwanted characters:
        $newFileName = handleNonASCIIAndUnwantedCharacters($newFileName, $allowedFileNameCharacters, $handleNonASCIIChars);
        // function 'handleNonASCIIAndUnwantedCharacters()' is defined in 'include.inc.php'
        // add original file name extension:
        $newFileName .= $fileNameExtension;
    } else {
        // take the file name as given by the user:
        $newFileName = $uploadFile["name"];
    }
    // Generate directory structure:
    if ($moveFilesIntoSubDirectories != "never") {
        // remove any slashes (i.e., directory delimiter(s)) from the beginning or end of '$dirNamingScheme':
        $dirNamingScheme = trimTextPattern($dirNamingScheme, "[\\/\\\\]+", true, true);
        // function 'trimTextPattern()' is defined in 'include.inc.php'
        $dirNamingSchemePartsArray = preg_split("#[/\\\\]+#", $dirNamingScheme);
        // split on slashes to separate between multiple sub-directories
        $subDirNamesArray = array();
        // initialize array variable which will hold the generated sub-directory names
        // auto-generate a directory name according to the naming scheme given in '$dirNamingScheme'
        // and handle non-ASCII chars plus unwanted characters:
        foreach ($dirNamingSchemePartsArray as $dirNamingSchemePart) {
            // parse given placeholder string:
            $subDirName = parsePlaceholderString($formVars, $dirNamingSchemePart, "");
            // function 'parsePlaceholderString()' is defined in 'include.inc.php'
            // handle non-ASCII and unwanted characters:
            $subDirName = handleNonASCIIAndUnwantedCharacters($subDirName, $allowedDirNameCharacters, $handleNonASCIIChars);
            // function 'handleNonASCIIAndUnwantedCharacters()' is defined in 'include.inc.php'
            if (!empty($subDirName)) {
                $subDirNamesArray[] = $subDirName;
            }
        }
        if (!empty($subDirNamesArray)) {
            $subDirName = implode("/", $subDirNamesArray) . "/";
        } else {
            $subDirName = "";
        }
    } else {
        $subDirName = "";
    }
    // Perform any case transformations:
    // change case of file name:
    if (preg_match("/^(lower|upper)\$/i", $changeCaseInFileNames)) {
        $newFileName = changeCase($changeCaseInFileNames, $newFileName);
    }
    // function 'changeCase()' is defined in 'include.inc.php'
    // change case of DIR name:
    if (preg_match("/^(lower|upper)\$/i", $changeCaseInDirNames) && !empty($subDirName)) {
        $subDirName = changeCase($changeCaseInDirNames, $subDirName);
    }
    // Generate full destination path:
    // - if '$moveFilesIntoSubDirectories = "existing"' and there's an existing sub-directory (within the default files directory '$filesBaseDir')
    //   whose name equals '$subDirName' we'll copy the new file into that sub-directory
    // - if '$moveFilesIntoSubDirectories = "always"' and '$subDirName' isn't empty, we'll generate an appropriately named sub-directory if it
    //   doesn't exist yet
    // - otherwise we just copy the file to the root-level of '$filesBaseDir':
    if (!empty($subDirName) && ($moveFilesIntoSubDirectories == "existing" and is_dir($filesBaseDir . $subDirName) or $moveFilesIntoSubDirectories == "always")) {
        $destFilePath = $filesBaseDir . $subDirName . $newFileName;
        // new file will be copied into sub-directory within '$filesBaseDir'...
        // copy the new subdir name & file name to the 'file' field variable:
        // Note: if a user uploads a file and there was already a file specified within the 'file' field, the old file will NOT get removed
        //       from the files directory! Automatic file removal is omitted on purpose since it's way more difficult to recover an
        //       inadvertently deleted file than to delete it manually. However, future versions should introduce a smarter way of handling
        //       orphaned files...
        $fileName = $subDirName . $newFileName;
        if ($moveFilesIntoSubDirectories == "always" and !is_dir($filesBaseDir . $subDirName)) {
            // make sure the directory we're moving the file to exists before proceeding:
            recursiveMkdir($filesBaseDir . $subDirName);
        }
    } else {
        $destFilePath = $filesBaseDir . $newFileName;
        // new file will be copied to root-level of '$filesBaseDir'...
        $fileName = $newFileName;
        // copy the new file name to the 'file' field variable (see note above!)
    }
    // Copy uploaded file from temporary location to the default file directory specified in '$filesBaseDir':
    // (for more on PHP file uploads see <http://www.php.net/manual/en/features.file-upload.php>)
    move_uploaded_file($tmpFilePath, $destFilePath);
    return $fileName;
}
Example #5
0
function generateCiteKey($formVars)
{
    global $defaultCiteKeyFormat;
    // defined in 'ini.inc.php'
    global $handleNonASCIICharsInCiteKeysDefault;
    global $userOptionsArray;
    // '$userOptionsArray' is made globally available in file 'import_modify.php' as well as by functions 'generateExport()' and 'generateCitations()' in 'search.php'
    // by default, we use any record-specific cite key that was entered manually by the user:
    if (isset($formVars['citeKeyName'])) {
        $citeKey = $formVars['citeKeyName'];
    } else {
        $citeKey = "";
    }
    // check if the user's options for auto-generation of cite keys command us to replace the manually entered cite key:
    if (!empty($userOptionsArray)) {
        if ($userOptionsArray['export_cite_keys'] == "yes") {
            if ($userOptionsArray['autogenerate_cite_keys'] == "yes") {
                if (empty($citeKey) or $userOptionsArray['prefer_autogenerated_cite_keys'] == "yes") {
                    if ($userOptionsArray['use_custom_cite_key_format'] == "yes") {
                        // if the user wants to use a custom cite key format
                        $citeKeyFormat = $userOptionsArray['cite_key_format'];
                    } else {
                        // use the default cite key format that was specified by the admin in 'ini.inc.php'
                        $citeKeyFormat = $defaultCiteKeyFormat;
                    }
                    // auto-generate a cite key according to the given naming scheme:
                    $citeKey = parsePlaceholderString($formVars, $citeKeyFormat, "<:authors:><:year:>");
                }
            }
        } else {
            $citeKey = "";
        }
        // by omitting a cite key Bibutils will take care of generation of cite keys for its export formats (BibTeX, Endnote, RIS)
    }
    // check how to handle non-ASCII characters:
    if (!empty($userOptionsArray) and !empty($userOptionsArray['nonascii_chars_in_cite_keys'])) {
        // use the user's own setting
        $handleNonASCIIChars = $userOptionsArray['nonascii_chars_in_cite_keys'];
    } else {
        $handleNonASCIIChars = $handleNonASCIICharsInCiteKeysDefault;
    }
    // use the default setting that was specified by the admin in 'ini.inc.php'
    // in addition to the handling of non-ASCII chars (given in '$handleNonASCIIChars') we'll
    // strip additional characters from the generated cite keys: for cite keys, we only allow
    // letters, digits, and the following characters: !$&*+-./:;<>?[]^_`|
    // see e.g. the discussion of cite keys at: <http://search.cpan.org/~gward/btparse-0.34/doc/bt_language.pod>
    if (!empty($citeKey)) {
        $citeKey = handleNonASCIIAndUnwantedCharacters($citeKey, "[:alnum:]" . preg_quote("!\$&*+-./:;<>?[]^_`|", "/"), $handleNonASCIIChars);
    }
    // ensure that each cite key is unique:
    if (!empty($citeKey) and !empty($userOptionsArray) and $userOptionsArray['export_cite_keys'] == "yes" and $userOptionsArray['uniquify_duplicate_cite_keys'] == "yes") {
        // if the generated cite key already exists in the global array of found cite keys
        // ('$citeKeysArray'), we'll uniquify it, otherwise we'll keep it as is:
        $citeKey = ensureUniqueCiteKey($citeKey);
    }
    return $citeKey;
}