Пример #1
0
 /**
  * Returns an instance of mfcs (singleton pattern)
  *
  * @author David Gersting
  * @param string $configFile The config file to load (Default: config.ini)
  * @return mfcs
  */
 public static function singleton($configFile = NULL)
 {
     if (!isset(self::$instance)) {
         self::$instance = new self($configFile);
     }
     return self::$instance;
 }
Пример #2
0
 function executeTesseract($tifImage, $configFile)
 {
     $outputFile = mfcs::config('mfcstmp') . '/tesseract-ocr-output-' . rand();
     exec("tesseract {$tifImage} {$outputFile} nobatch {$configFile} 2> /dev/null");
     return $outputFile . '.txt';
     //tesseract appends txt extension to output file
 }
Пример #3
0
 public static function buildProjectNavigation($formID)
 {
     if (($form = forms::get($formID)) === FALSE) {
         return FALSE;
     }
     localvars::add("formID", htmlSanitize($formID));
     $output = "";
     $currentGroup = "";
     if (!is_array($form['navigation'])) {
         return $output;
     }
     foreach ($form['navigation'] as $item) {
         // deal with field sets
         if ($item['grouping'] != $currentGroup) {
             if ($currentGroup != "") {
                 $output .= "</ul></li>";
             }
             if (!is_empty($item['grouping'])) {
                 $output .= sprintf('<li><strong>%s</strong><ul>', $item['grouping']);
             }
             $currentGroup = $item['grouping'];
         }
         $output .= "<li>";
         if ($item['type'] == "logout") {
             $output .= sprintf('<a href="%s">%s</a>', htmlSanitize($item['url']), htmlSanitize($item['label']));
         } else {
             if ($item['type'] == "link") {
                 $item['url'] = preg_replace("/{siteRoot}/", mfcs::config("siteRoot"), $item['url']);
                 $output .= sprintf('<a href="%s">%s</a>', htmlSanitize($item['url']), htmlSanitize($item['label']));
             } else {
                 if ($item['type'] == "objectForm" || $item['type'] == "metadataForm") {
                     $form = forms::get($item['formID']);
                     $output .= sprintf('<a href="" data-formID="%s" data-header="%s" data-toggle="modal" class="metadataObjectEditor">%s</a>', htmlSanitize($item['formID']), htmlSanitize($item['label']), htmlSanitize(!empty($form['displayTitle']) ? $form['displayTitle'] : (!empty($form['title']) ? $form['title'] : '[No form title]')));
                 } else {
                     $output .= sprintf('%s', htmlSanitize($item['label']));
                 }
             }
         }
         $output .= "</li>";
     }
     return $output;
 }
Пример #4
0
// Quick and dirty Checks check
// @TODO this needs to be more formalized in a class to easily include other checks as well
if (!isCLI()) {
    $sql_check = sprintf("SELECT `value` FROM `checks` WHERE `name`='uniqueIDCheck'");
    $sqlResult_check = mfcs::$engine->openDB->query($sql_check);
    if (!$sqlResult_check['result']) {
        errorHandle::newError(__METHOD__ . "() - : " . $sqlResult['error'], errorHandle::DEBUG);
        print "<p>Error checking MFCS sanity. Aborting.</p>";
        exit;
    }
    $row_check = mysql_fetch_array($sqlResult_check['result'], MYSQL_ASSOC);
    if ($row_check['value'] == "0") {
        // notify systems via email
        print "<h1>ERROR!</h1>";
        print "<p>MFCS Failed idno sanity check. Please contact systems Immediately.</p>";
        print "<p>Please jot down the steps you took getting to this point. Be as specific as possible.</p>";
        print "<p>Aborting.</p>";
        exit;
    }
}
// End Checks
$mfcsSearch = new mfcsSearch();
// Load the user's current projects
sessionSet('currentProject', users::loadProjects());
recurseInsert("includes/functions.php", "php");
recurseInsert("includes/validator.php", "php");
$engine->eTemplate("load", "distribution");
localVars::add("siteRoot", mfcs::config("siteRoot"));
localVars::add('pageTitle', mfcs::config("pageTitle"));
localVars::add('pageHeader', mfcs::config("pageHeader"));
Пример #5
0
     $files[] = sprintf("%s", $file['name']);
 }
 $files = implode(" ", $files);
 $destinationFile = sys_get_temp_dir() . "/" . time() . "." . $type;
 if ($type == "zip") {
     $cmdLine = sprintf("zip -j %s %s", $destinationFile, $files);
 } else {
     if ($type == "tar") {
         $cmdLine = sprintf("tar -cf %s %s", $destinationFile, $files);
     } else {
         throw new Exception("invalid type.");
     }
 }
 ini_set('memory_limit', -1);
 set_time_limit(0);
 chdir(mfcs::config('archivalPathMFCS') . "/" . $file['path']);
 exec($cmdLine);
 $fi = new finfo(FILEINFO_MIME_TYPE);
 $mimeType = $fi->file($destinationFile);
 header("Pragma: public");
 header("Expires: 0");
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-type: application/zip");
 header("Content-Disposition: attachment; filename=\"" . $object['idno'] . "." . $type . "\"");
 header("Content-Transfer-Encoding: binary");
 header("Content-Length: " . filesize($destinationFile));
 ob_end_clean();
 @readfile($destinationFile);
 // header(sprintf("Content-Disposition: attachment; filename='%s.%s'",
Пример #6
0
 public static function buildEditTable($formID)
 {
     $form = self::get($formID);
     // Get all objects from this form
     $objects = objects::getAllObjectsForForm($formID);
     $objects = objects::sort($objects, $form['objectTitleField']);
     // If the data is too large, setup pagination
     if (sizeof($objects) > mfcs::config("metadataPageCount")) {
         $pagination = new pagination(sizeof($objects));
         $pagination->itemsPerPage = mfcs::config("metadataPageCount");
         $pagination->currentPage = isset(mfcs::$engine->cleanGet['MYSQL'][$pagination->urlVar]) ? mfcs::$engine->cleanGet['MYSQL'][$pagination->urlVar] : 1;
         $startPos = $pagination->itemsPerPage * ($pagination->currentPage - 1);
         $objects = array_slice($objects, $startPos, $pagination->itemsPerPage);
     }
     if (count($objects) > 0) {
         $headers = array();
         $headers[] = "Delete";
         foreach ($form['fields'] as $field) {
             $headers[] = $field['label'];
         }
         if (forms::isMetadataForm($formID) === TRUE) {
             $headers[] = "Search";
             $headers[] = "Move";
         }
         $tableRows = array();
         for ($I = 0; $I < count($objects); $I++) {
             $temp = array();
             $temp[] = sprintf('<input type="checkbox" name="delete[]" value="%s"', $objects[$I]['ID']);
             foreach ($form['fields'] as $field) {
                 $temp[] = sprintf('<input type="%s" style="%s" name="%s_%s" value="%s" />', $field['type'], $field['style'], $field['name'], $objects[$I]['ID'], isset($objects[$I]['data'][$field['name']]) ? htmlSanitize($objects[$I]['data'][$field['name']]) : "");
             }
             if (forms::isMetadataForm($formID) === TRUE) {
                 $temp[] = sprintf('<a href="%sdataView/list.php?listType=metadataObjects&amp;formID=%s&amp;objectID=%s">Find Objects</a>', localvars::get('siteRoot'), htmlSanitize($formID), $objects[$I]['ID']);
                 $temp[] = sprintf('<a href="%sdataEntry/move.php?objectID=%s">Move</a>', localvars::get('siteRoot'), $objects[$I]['ID']);
             }
             $tableRows[] = $temp;
         }
         $table = new tableObject("array");
         $table->summary = "Object Listing";
         $table->class = "tableObject table table-striped table-bordered";
         $table->headers($headers);
         $output = "";
         // Add in pagination bar
         if (isset($pagination)) {
             $output .= $pagination->nav_bar();
         }
         $output .= sprintf('<form action="%s?formID=%s" method="%s" name="updateForm" data-formid="%s">', $_SERVER['PHP_SELF'], htmlSanitize($formID), "post", mfcs::$engine->openDB->escape($formID));
         $output .= sessionInsertCSRF();
         $output .= $table->display($tableRows);
         $output .= '<input type="submit" name="updateEdit" value="Update" class="btn" />';
         $output .= "</form>";
         // Add in pagination bar
         if (isset($pagination)) {
             $output .= $pagination->nav_bar();
         }
         return $output;
     } else {
         return "No data entered for this Metadata Form.";
     }
 }
Пример #7
0
 public static function processObjectFiles($assetsID, $options)
 {
     // Disable PHP's max execution time
     set_time_limit(0);
     $saveBase = mfcs::config('convertedPath');
     $originalsFilepath = self::getSaveDir($assetsID, 'archive');
     $originalFiles = scandir($originalsFilepath);
     // Setup return array
     $return = array('processed' => array(), 'combine' => array(), 'thumbs' => array(), 'ocr' => array());
     // Remove dot files from array
     foreach ($originalFiles as $I => $filename) {
         if ($filename[0] == '.') {
             unset($originalFiles[$I]);
         }
     }
     // Needed to put the files in the right order for processing
     if (natcasesort($originalFiles) === FALSE) {
         return FALSE;
     }
     try {
         // If combine files is checked, read this image and add it to the combined object
         if (isset($options['combine']) && str2bool($options['combine'])) {
             try {
                 $errors = array();
                 $createThumb = TRUE;
                 // Create us some temp working space
                 $tmpDir = mfcs::config('mfcstmp') . DIRECTORY_SEPARATOR . uniqid();
                 mkdir($tmpDir, 0777, TRUE);
                 // Ensure that the HOCR file is created
                 if (!self::createHOCR("{$saveBase}/hocr.cfg")) {
                     return FALSE;
                 }
                 $gsTemp = $tmpDir . DIRECTORY_SEPARATOR . uniqid();
                 touch($gsTemp);
                 foreach ($originalFiles as $filename) {
                     // Figure some stuff out about the file
                     $originalFile = $originalsFilepath . DIRECTORY_SEPARATOR . $filename;
                     $_filename = pathinfo($originalFile);
                     $filename = $_filename['filename'];
                     $baseFilename = $tmpDir . DIRECTORY_SEPARATOR . $filename;
                     // Create a thumbnail of the first image
                     if ($createThumb === TRUE) {
                         if (($return['combine'][] = self::createThumbnail($originalFile, $filename, $options, $assetsID, TRUE)) === FALSE) {
                             throw new Exception("Failed to create thumbnail: " . $filename);
                         }
                         // Prevent making multiple thumbnails
                         $createThumb = FALSE;
                     }
                     // perform hOCR on the original uploaded file which gets stored in combined as an HTML file
                     $_exec = shell_exec(sprintf('tesseract %s %s -l eng %s 2>&1', escapeshellarg($originalFile), escapeshellarg($baseFilename), escapeshellarg("{$saveBase}/hocr.cfg")));
                     // If a new-line char is in the output, assume it's an error
                     // Tesseract failed, let's normalize the image and try again
                     if (strpos(trim($_exec), "\n") !== FALSE) {
                         $errors[] = "Unable to process OCR for " . basename($originalFile) . ". Continuing&hellip;";
                         errorHandle::warningMsg("Unable to process OCR for " . basename($originalFile) . ". Continuing&hellip;");
                         // Ensure HTML file exists
                         touch($baseFilename . ".html");
                     }
                     // Create an OCR'd pdf of the file
                     $_exec = shell_exec(sprintf('hocr2pdf -i %s -s -o %s < %s 2>&1', escapeshellarg($originalFile), escapeshellarg($baseFilename . ".pdf"), escapeshellarg($baseFilename . ".html")));
                     if (trim($_exec) !== 'Writing unmodified DCT buffer.') {
                         if (strpos($_exec, 'Warning:') !== FALSE) {
                             errorHandle::newError("hocr2pdf Warning: " . $_exec, errorHandle::DEBUG);
                         } else {
                             errorHandle::errorMsg("Failed to Create PDF: " . basename($filename, "jpg") . ".pdf");
                             throw new Exception("hocr2pdf Error: " . $_exec);
                         }
                     }
                     // Add this pdf to a temp file that will be read in by gs
                     file_put_contents($gsTemp, $baseFilename . ".pdf" . PHP_EOL, FILE_APPEND);
                     // We're done with this file, delete it
                     unlink($baseFilename . ".html");
                 }
                 // Combine all PDF files in directory
                 $_exec = shell_exec(sprintf('gs -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=%s @%s 2>&1', self::getSaveDir($assetsID, 'combine') . "combined.pdf", $gsTemp));
                 if (!is_empty($_exec)) {
                     errorHandle::errorMsg("Failed to combine PDFs into single PDF.");
                     throw new Exception("GhostScript Error: " . $_exec);
                 }
                 $return['combine'][] = array('name' => 'combined.pdf', 'path' => self::getSaveDir($assetsID, 'combine', FALSE), 'size' => filesize(self::getSaveDir($assetsID, 'combine') . 'combined.pdf'), 'type' => 'application/pdf', 'errors' => $errors);
                 // Lastly, we delete our temp working dir (always nice to cleanup after yourself)
                 if (self::cleanupTempDirectory($tmpDir) === FALSE) {
                     errorHandle::errorMsg("Unable to clean up temporary directory: " . $tmpDir);
                     throw new Exception("Unable to clean up temporary directory: " . $tmpDir);
                 }
             } catch (Exception $e) {
                 // We need to delete our working dir
                 if (isset($tmpDir) && is_dir($tmpDir)) {
                     if (self::cleanupTempDirectory($tmpDir) === FALSE) {
                         errorHandle::errorMsg("Unable to clean up temporary directory (in Exception): " . $tmpDir);
                     }
                 }
                 throw new Exception($e->getMessage(), $e->getCode(), $e);
             }
         }
         // If Combine
         // This conditional needs updated when different conversion options are added or removed.
         // If the file has no processing to do, don't do any ...
         if (!isset($options['convert']) && !isset($options['thumbnail']) && !isset($options['ocr']) && !isset($options['mp3'])) {
             return $return;
         }
         foreach ($originalFiles as $filename) {
             $originalFile = $originalsFilepath . DIRECTORY_SEPARATOR . $filename;
             $_filename = pathinfo($originalFile);
             $filename = $_filename['filename'];
             // Convert uploaded files into some ofhter size/format/etc
             if (isset($options['convert']) && str2bool($options['convert'])) {
                 // we create the Imagick object here so that we can pass it to thumbnail creation
                 $image = new Imagick();
                 $image->readImage($originalFile);
                 // Convert it
                 if (($image = self::convertImage($image, $options, $assetsID, $filename)) === FALSE) {
                     throw new Exception("Failed to create processed image: " . $originalFile);
                 }
                 $filename = $filename . '.' . strtolower($image->getImageFormat());
                 // Create a thumbnail that includes converted options
                 if (isset($options['thumbnail']) && str2bool($options['thumbnail'])) {
                     if (($return['thumbs'][] = self::createThumbnail($image, $filename, $options, $assetsID)) === FALSE) {
                         throw new Exception("Failed to create thumbnail: " . $filename);
                     }
                 }
                 // Set the return array
                 $return['processed'][] = array('name' => $filename, 'path' => self::getSaveDir($assetsID, 'processed', FALSE), 'size' => filesize(self::getSaveDir($assetsID, 'processed') . $filename), 'type' => self::getMimeType(self::getSaveDir($assetsID, 'processed') . $filename), 'errors' => '');
             } else {
                 if (isset($options['thumbnail']) && str2bool($options['thumbnail'])) {
                     if (($return['thumbs'][] = self::createThumbnail($originalFile, $filename, $options, $assetsID)) === FALSE) {
                         throw new Exception("Failed to create thumbnail: " . $filename);
                     }
                 }
             }
             // Create an OCR text file
             if (isset($options['ocr']) && str2bool($options['ocr'])) {
                 if (($return['ocr'][] = self::createOCRTextFile($originalFile, $assetsID, $filename)) === FALSE) {
                     errorHandle::errorMsg("Failed to create OCR text file: " . $filename);
                     throw new Exception("Failed to create OCR file for {$filename}");
                 }
             }
             // Create MP3
             if (isset($options['mp3']) && str2bool($options['mp3'])) {
                 $return['mp3'][] = self::createMP3($originalFile);
             }
         }
         // Foreach File
     } catch (Exception $e) {
         errorHandle::newError(__METHOD__ . "() - {$e->getMessage()} {$e->getLine()}:{$e->getFile()}", errorHandle::HIGH);
     }
     return $return;
 }
Пример #8
0
    $xml .= '</ROW>';
    // deal with the files
    if ($object['modifiedTime'] > $lastExportDate && is_array($object['data']['digitalFiles'])) {
        foreach ($object['data']['digitalFiles']['files']['combine'] as $file) {
            switch ($file['name']) {
                case "thumb.jpg":
                    $destinationPath = $filesExportBaseDir . "/thumbs/" . $object['idno'] . ".jpg";
                    break;
                case "combined.pdf":
                    $destinationPath = $filesExportBaseDir . "/jpg/" . $object['idno'] . ".pdf";
                    break;
                default:
                    $destinationPath = NULL;
            }
            if (!isnull($destinationPath)) {
                exec(sprintf("ln -sf %s/%s%s %s", mfcs::config('convertedPath'), $file['path'], $file['name'], $destinationPath));
            }
        }
        // print "<pre>";
        // var_dump($object['data']['digitalFiles']['files']['combine']);
        // print "</pre>";
    }
}
$xml .= "</FMPDSORESULT>";
if (!($file = fopen($outFile, "w"))) {
    errorHandle::newError(__METHOD__ . "() - Error creating file", errorHandle::DEBUG);
    print "error opening file.";
    exit;
}
fwrite($file, $xml);
fclose($file);
Пример #9
0
function getIDNO($formID, $projectID, $increment = TRUE)
{
    return mfcs::getIDNO($formID, $increment);
}
Пример #10
0
 public static function create($formID, $data, $metadata, $parentID = 0, $modifiedTime = NULL, $createTime = NULL)
 {
     if (!is_array($data)) {
         errorHandle::newError(__METHOD__ . "() - : data is not array", errorHandle::DEBUG);
         return FALSE;
     }
     // Get the current Form
     if (($form = forms::get($formID)) === FALSE) {
         errorHandle::newError(__METHOD__ . "() - retrieving form by formID", errorHandle::DEBUG);
         return FALSE;
     }
     // begin transactions
     $result = mfcs::$engine->openDB->transBegin("objects");
     if ($result !== TRUE) {
         errorHandle::newError(__METHOD__ . "() - unable to start database transactions", errorHandle::DEBUG);
         return FALSE;
     }
     // Insert into the database
     $sql = sprintf("INSERT INTO `objects` (parentID,formID,data,metadata,modifiedTime,createTime,modifiedBy,createdBy) VALUES('%s','%s','%s','%s','%s','%s','%s','%s')", isset(mfcs::$engine->cleanPost['MYSQL']['parentID']) ? mfcs::$engine->cleanPost['MYSQL']['parentID'] : "0", mfcs::$engine->openDB->escape($formID), encodeFields($data), mfcs::$engine->openDB->escape($form['metadata']), time(), time(), mfcs::$engine->openDB->escape(users::user('ID')), mfcs::$engine->openDB->escape(users::user('ID')));
     $sqlResult = mfcs::$engine->openDB->query($sql);
     if (!$sqlResult['result']) {
         mfcs::$engine->openDB->transRollback();
         mfcs::$engine->openDB->transEnd();
         errorHandle::newError(__METHOD__ . "() - " . $sql . " -- " . $sqlResult['error'], errorHandle::DEBUG);
         return FALSE;
     }
     // Set the new object ID in a local variable
     $objectID = $sqlResult['id'];
     localvars::add("newObjectID", $objectID);
     // Insert into the new data table
     if (self::insertObjectData($objectID, $data, $formID) === FALSE) {
         mfcs::$engine->openDB->transRollback();
         mfcs::$engine->openDB->transEnd();
         errorHandle::newError(__METHOD__ . "() - inserting objects", errorHandle::DEBUG);
         return FALSE;
     }
     // if it is an object form (not a metadata form)
     // do the IDNO stuff
     if ($form['metadata'] == "0") {
         // the form is an object form, make sure that it has an ID field defined.
         if (($idnoInfo = forms::getFormIDInfo($formID)) === FALSE) {
             errorHandle::newError(__METHOD__ . "() - no IDNO field for object form.", errorHandle::DEBUG);
             return FALSE;
         }
         // if the idno is managed by the system get a new idno
         if ($idnoInfo['managedBy'] == "system") {
             $idno = mfcs::$engine->openDB->escape(mfcs::getIDNO($formID));
         } else {
             $idno = mfcs::$engine->cleanPost['MYSQL']['idno'];
         }
         if (isempty($idno)) {
             mfcs::$engine->openDB->transRollback();
             mfcs::$engine->openDB->transEnd();
             return FALSE;
         }
         if (!self::updateIDNO($objectID, $idno)) {
             mfcs::$engine->openDB->transRollback();
             mfcs::$engine->openDB->transEnd();
             errorHandle::newError(__METHOD__ . "() - updating the IDNO: " . $sqlResult['error'], errorHandle::DEBUG);
             return FALSE;
         }
         // increment the project counter
         $sql = sprintf("UPDATE `forms` SET `count`=`count`+'1' WHERE `ID`='%s'", mfcs::$engine->openDB->escape($form['ID']));
         $sqlResult = mfcs::$engine->openDB->query($sql);
         if (!$sqlResult['result']) {
             mfcs::$engine->openDB->transRollback();
             mfcs::$engine->openDB->transEnd();
             errorHandle::newError(__METHOD__ . "() - Error incrementing form counter: " . $sqlResult['error'], errorHandle::DEBUG);
             return FALSE;
         }
     }
     // Update duplicate matching table
     if (duplicates::updateDupeTable($formID, $objectID, $data) === FALSE) {
         mfcs::$engine->openDB->transRollback();
         mfcs::$engine->openDB->transEnd();
         errorHandle::newError(__METHOD__ . "() - updating dupe matching", errorHandle::DEBUG);
         return FALSE;
     }
     // Add it to the users current projects
     if (($currentProjects = users::loadProjects()) === FALSE) {
         mfcs::$engine->openDB->transRollback();
         mfcs::$engine->openDB->transEnd();
         return FALSE;
     }
     foreach ($currentProjects as $projectID => $projectName) {
         if (forms::checkFormInProject($projectID, $formID) === TRUE) {
             if (objects::addProject($objectID, $projectID) === FALSE) {
                 mfcs::$engine->openDB->transRollback();
                 mfcs::$engine->openDB->transEnd();
                 return FALSE;
             }
         }
     }
     // end transactions
     mfcs::$engine->openDB->transCommit();
     mfcs::$engine->openDB->transEnd();
     return TRUE;
 }
Пример #11
0
<?php

require_once "/home/mfcs.lib.wvu.edu/phpincludes/engine/engineAPI/latest/engine.php";
$engine = EngineAPI::singleton();
errorHandle::errorReporting(errorHandle::E_ALL);
$engine->dbConnect("database", "mfcs", TRUE);
require_once "../includes/index.php";
mfcs::singleton();
// Login Type
$loginType = "ldap";
// Domain for ldap login
$engine->localVars("domain", "wvu-ad");
$authFail = FALSE;
// Authorization to the current resource .. we may end up not using this
$loginFail = FALSE;
// Login Success/Failure
if (isset($engine->cleanGet['HTML']['page'])) {
    $page = $engine->cleanGet['HTML']['page'];
    if (isset($engine->cleanGet['HTML']['qs'])) {
        $qs = urldecode($engine->cleanGet['HTML']['qs']);
        $qs = preg_replace('/&amp;amp;/', '&', $qs);
        $qs = preg_replace('/&amp;/', '&', $qs);
    } else {
        $qs = "";
    }
}
//Login processing:
if (isset($engine->cleanPost['HTML']['loginSubmit'])) {
    if (!isset($engine->cleanPost['HTML']['username']) || !isset($engine->cleanPost['HTML']['password'])) {
        $authFail = TRUE;
        $loginFail = TRUE;