read() public static méthode

public static read ( $file )
Exemple #1
0
function migrate($migration, $connection)
{
    echo 'importing ' . $migration . '... ';
    $connection->query(utf8_decode(Filesystem::read('db/migrations/' . $migration)));
    $connection->create(array('table' => 'schema_migrations', 'values' => array('version' => get_migration_version($migration))));
    echo 'done' . PHP_EOL;
}
 /**
  * getLogs - Returns an array of search engine query log entries
  * 
  * @access public
  * @return void
  */
 public function getLogs()
 {
     if (file_exists($this->logPath)) {
         $log = Filesystem::read($this->logPath);
         $levels = array();
         $this->logs = explode("\n", $log);
     } else {
         return array();
     }
     return $this->logs;
 }
function migrate($migration, $connection)
{
    echo 'importing ' . $migration . '... ';
    $ext = Filesystem::extension($migration);
    if ($ext == 'php') {
        require_once 'db/migrations/' . $migration;
        $classname = get_migration_name($migration);
        $classname::migrate($connection);
    } else {
        $connection->query(utf8_decode(Filesystem::read('db/migrations/' . $migration)));
    }
    $connection->create(array('table' => 'schema_migrations', 'values' => array('version' => get_migration_version($migration))));
    echo 'done' . PHP_EOL;
}
    public function run(array $arguments)
    {
        if (count($arguments) > 2) {
            $text = "Too much arguments\n";
            $code = 1;
        } elseif (!empty($arguments[1])) {
            $parser = new Parser($this->filesystem);
            $text = $parser->run($this->filesystem->read($arguments[1]));
            $code = 0;
        } else {
            $readme = $this->filesystem->read(__DIR__ . '/../README.MD');
            $readme = str_replace('``', '', $readme);
            $text = <<<TEXT
Nginx conf parser
~~~~~~~~~~~~~~~~~

{$readme}

TEXT;
            $code = 0;
        }
        return array($code, $text);
    }
Exemple #5
0
 /**
  * Set driver by image type
  */
 public function __construct($path)
 {
     parent::__construct($path);
     $this->methods = new Core_ArrayObject($this->methods);
     switch ($this->info->type) {
         case IMAGETYPE_JPEG:
             $this->source = imagecreatefromjpeg($path);
             break;
         case IMAGETYPE_GIF:
             $this->source = imagecreatefromgif($path);
             break;
         case IMAGETYPE_PNG:
             $this->source = imagecreatefrompng($path);
             imagealphablending($this->source, TRUE);
             imagesavealpha($this->source, TRUE);
             break;
         case IMAGETYPE_ICO:
             $this->source = imagecreatefromstring(Filesystem::read($path));
             break;
     }
 }
Exemple #6
0
 /**
  * Method to rename the template in the XML files and rename the language files
  *
  * @return	boolean   true if successful, false otherwise
  * @since	2.5
  */
 protected function fixTemplateName()
 {
     // Rename Language files
     // Get list of language files
     $result = true;
     $files = Filesystem::files($this->getState('to_path'), '.ini', true, true);
     $newName = strtolower($this->getState('new_name'));
     $oldName = $this->getTemplate()->element;
     foreach ($files as $file) {
         $newFile = str_replace($oldName, $newName, $file);
         $result = Filesystem::move($file, $newFile) && $result;
     }
     // Edit XML file
     $xmlFile = $this->getState('to_path') . '/templateDetails.xml';
     if (Filesystem::exists($xmlFile)) {
         $contents = Filesystem::read($xmlFile);
         $pattern[] = '#<name>\\s*' . $oldName . '\\s*</name>#i';
         $replace[] = '<name>' . $newName . '</name>';
         $pattern[] = '#<language(.*)' . $oldName . '(.*)</language>#';
         $replace[] = '<language${1}' . $newName . '${2}</language>';
         $contents = preg_replace($pattern, $replace, $contents);
         $result = Filesystem::write($xmlFile, $contents) && $result;
     }
     return $result;
 }
Exemple #7
0
 public function getLog()
 {
     $config = $this->getConfig();
     $log = Filesystem::read($config['endpoint']['localhost']['log_path']);
     $levels = array();
     $this->logs = explode("\n", $log);
     return $this;
 }
Exemple #8
0
 /**
  * Checks if the file can be uploaded
  *
  * @param array File information
  * @param string An error message to be returned
  * @return  boolean
  */
 public static function canUpload($file, &$err)
 {
     $params = Component::params('com_media');
     if (empty($file['name'])) {
         $err = 'COM_MEDIA_ERROR_UPLOAD_INPUT';
         return false;
     }
     if ($file['name'] !== Filesystem::clean($file['name'])) {
         $err = 'COM_MEDIA_ERROR_WARNFILENAME';
         return false;
     }
     $format = strtolower(Filesystem::extension($file['name']));
     // Media file names should never have executable extensions buried in them.
     $executable = array('php', 'js', 'exe', 'phtml', 'java', 'perl', 'py', 'asp', 'dll', 'go', 'ade', 'adp', 'bat', 'chm', 'cmd', 'com', 'cpl', 'hta', 'ins', 'isp', 'jse', 'lib', 'mde', 'msc', 'msp', 'mst', 'pif', 'scr', 'sct', 'shb', 'sys', 'vb', 'vbe', 'vbs', 'vxd', 'wsc', 'wsf', 'wsh');
     $explodedFileName = explode('.', $file['name']);
     if (count($explodedFileName > 2)) {
         foreach ($executable as $extensionName) {
             if (in_array($extensionName, $explodedFileName)) {
                 $app->enqueueMessage(Lang::txt('JLIB_MEDIA_ERROR_WARNFILETYPE'), 'notice');
                 return false;
             }
         }
     }
     $allowable = explode(',', $params->get('upload_extensions'));
     $ignored = explode(',', $params->get('ignore_extensions'));
     if ($format == '' || $format == false || !in_array($format, $allowable) && !in_array($format, $ignored)) {
         $err = 'COM_MEDIA_ERROR_WARNFILETYPE';
         return false;
     }
     $maxSize = (int) ($params->get('upload_maxsize', 0) * 1024 * 1024);
     if ($maxSize > 0 && (int) $file['size'] > $maxSize) {
         $err = 'COM_MEDIA_ERROR_WARNFILETOOLARGE';
         return false;
     }
     $imginfo = null;
     if ($params->get('restrict_uploads', 1)) {
         $images = explode(',', $params->get('image_extensions'));
         if (in_array($format, $images)) {
             // if its an image run it through getimagesize
             // if tmp_name is empty, then the file was bigger than the PHP limit
             if (!empty($file['tmp_name'])) {
                 if (($imginfo = getimagesize($file['tmp_name'])) === FALSE) {
                     $err = 'COM_MEDIA_ERROR_WARNINVALID_IMG';
                     return false;
                 }
             } else {
                 $err = 'COM_MEDIA_ERROR_WARNFILETOOLARGE';
                 return false;
             }
         } elseif (!in_array($format, $ignored)) {
             // if its not an image...and we're not ignoring it
             $allowed_mime = explode(',', $params->get('upload_mime'));
             $illegal_mime = explode(',', $params->get('upload_mime_illegal'));
             if (function_exists('finfo_open') && $params->get('check_mime', 1)) {
                 // We have fileinfo
                 $finfo = finfo_open(FILEINFO_MIME);
                 $type = finfo_file($finfo, $file['tmp_name']);
                 if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) {
                     $err = 'COM_MEDIA_ERROR_WARNINVALID_MIME';
                     return false;
                 }
                 finfo_close($finfo);
             } elseif (function_exists('mime_content_type') && $params->get('check_mime', 1)) {
                 // we have mime magic
                 $type = mime_content_type($file['tmp_name']);
                 if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) {
                     $err = 'COM_MEDIA_ERROR_WARNINVALID_MIME';
                     return false;
                 }
             } elseif (!User::authorise('core.manage')) {
                 $err = 'COM_MEDIA_ERROR_WARNNOTADMIN';
                 return false;
             }
         }
     }
     $xss_check = Filesystem::read($file['tmp_name'], false, 256);
     $html_tags = array('abbr', 'acronym', 'address', 'applet', 'area', 'audioscope', 'base', 'basefont', 'bdo', 'bgsound', 'big', 'blackface', 'blink', 'blockquote', 'body', 'bq', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'comment', 'custom', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'fn', 'font', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'html', 'iframe', 'ilayer', 'img', 'input', 'ins', 'isindex', 'keygen', 'kbd', 'label', 'layer', 'legend', 'li', 'limittext', 'link', 'listing', 'map', 'marquee', 'menu', 'meta', 'multicol', 'nobr', 'noembed', 'noframes', 'noscript', 'nosmartquotes', 'object', 'ol', 'optgroup', 'option', 'param', 'plaintext', 'pre', 'rt', 'ruby', 's', 'samp', 'script', 'select', 'server', 'shadow', 'sidebar', 'small', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'ul', 'var', 'wbr', 'xml', 'xmp', '!DOCTYPE', '!--');
     foreach ($html_tags as $tag) {
         // A tag is '<tagname ', so we need to add < and a space or '<tagname>'
         if (stristr($xss_check, '<' . $tag . ' ') || stristr($xss_check, '<' . $tag . '>')) {
             $err = 'COM_MEDIA_ERROR_WARNIEXSS';
             return false;
         }
     }
     return true;
 }
Exemple #9
0
 /**
  * Read SSH key
  *
  * @return string - .ssh/authorized_keys file content
  */
 private function readKey()
 {
     // Webdav path
     $base = DS . 'webdav' . DS . 'home';
     $user = DS . $this->member->get('username');
     $ssh = DS . '.ssh';
     $auth = DS . 'authorized_keys';
     // Real home directory
     $homeDir = $this->member->get('homeDirectory');
     $key = '';
     // First, make sure webdav is there and that the necessary folders are there
     if (!Filesystem::exists($base)) {
         // Not sure what to do here
         return $key = false;
     }
     if (!Filesystem::exists($homeDir)) {
         // Try to create their home directory
         require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'helpers' . DS . 'utils.php';
         if (!\Components\Tools\Helpers\Utils::createHomeDirectory($this->member->get('username'))) {
             return $key = false;
         }
     }
     if (!Filesystem::exists($base . $user . $ssh)) {
         // User doesn't have an ssh directory, so try to create one (with appropriate permissions)
         if (!Filesystem::makeDirectory($base . $user . $ssh, 0700)) {
             return $key = false;
         }
     }
     if (!Filesystem::exists($base . $user . $ssh . $auth)) {
         // Try to create their authorized keys file
         $content = '';
         // J25 passes param by reference so couldn't use constant below
         Filesystem::write($base . $user . $ssh . $auth, $content);
         if (!Filesystem::exists($base . $user . $ssh . $auth)) {
             return $key = false;
         } else {
             // Set correct permissions on authorized_keys file
             JPath::setPermissions($base . $user . $ssh . $auth, '0600');
             return $key;
         }
     }
     // Read the file contents
     $key = Filesystem::read($base . $user . $ssh . $auth);
     return $key;
 }
Exemple #10
0
<?php

require_once 'system/classes/Filesystem.php';
require_once 'system/classes/Gui.php';
require_once 'system/classes/Security.php';
$security = new Security();
$gui = new Gui();
$filesystem = new Filesystem();
echo $gui->renderResults($filesystem->read($_GET['absolutePath'], $_GET['relativePath'], $_GET['sortName'], $_GET['sortOrder']));
Exemple #11
0
 /**
  * Compile PDF/image preview for any kind of file
  *
  *
  * @return  mixed  array or false
  */
 protected function _compile()
 {
     // Combine file and folder data
     $items = $this->_sortIncoming();
     // Get stored remote connections
     $remotes = $this->_getRemoteConnections();
     // Params for repo call
     $params = array('subdir' => $this->subdir, 'remoteConnections' => $remotes);
     // Incoming
     $commit = Request::getInt('commit', 0);
     $download = Request::getInt('download', 0);
     // Check that we have compile enabled
     if (!$this->params->get('latex')) {
         $this->setError(Lang::txt('PLG_PROJECTS_FILES_COMPILE_NOTALLOWED'));
         return;
     }
     // Output HTML
     $view = new \Hubzero\Plugin\View(array('folder' => 'projects', 'element' => 'files', 'name' => 'compiled'));
     // Get selected item
     if (!$items) {
         $view->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_NO_FILES_TO_COMPILE'));
         $view->loadTemplate();
         return;
     } else {
         foreach ($items as $element) {
             foreach ($element as $type => $item) {
                 // Get our metadata
                 $file = $this->repo->getMetadata($item, 'file', $params);
                 break;
             }
         }
     }
     // We need a file
     if (empty($file)) {
         $view->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_NO_FILES_TO_COMPILE'));
         $view->loadTemplate();
         return;
     }
     // Path for storing temp previews
     $imagePath = trim($this->model->config()->get('imagepath', '/site/projects'), DS);
     $outputDir = DS . $imagePath . DS . strtolower($this->model->get('alias')) . DS . 'compiled';
     // Make sure output dir exists
     if (!is_dir(PATH_APP . $outputDir)) {
         if (!Filesystem::makeDirectory(PATH_APP . $outputDir)) {
             $this->setError(Lang::txt('PLG_PROJECTS_FILES_UNABLE_TO_CREATE_UPLOAD_PATH'));
             return;
         }
     }
     // Get LaTeX helper
     $compiler = new \Components\Projects\Helpers\Compiler();
     // Tex compiler path
     $texPath = DS . trim($this->params->get('texpath'), DS);
     $view->file = $file;
     $view->oWidth = '780';
     $view->oHeight = '460';
     $view->url = Route::url($this->model->link('files'));
     $cExt = 'pdf';
     // Take out Google native extension if present
     $fileName = $file->get('name');
     if (in_array($file->get('ext'), \Components\Projects\Helpers\Google::getGoogleNativeExts())) {
         $fileName = preg_replace("/." . $file->get('ext') . "\\z/", "", $file->get('name'));
     }
     // Tex file?
     $tex = $compiler->isTexFile($fileName);
     // Build temp name
     $tempBase = $tex ? 'temp__' . \Components\Projects\Helpers\Html::takeOutExt($fileName) : $fileName;
     $tempBase = str_replace(' ', '_', $tempBase);
     // Get file contents
     if (!empty($this->_remoteService) && $file->get('converted')) {
         // Load remote resource
         $this->_connect->setUser($this->model->get('owned_by_user'));
         $resource = $this->_connect->loadRemoteResource($this->_remoteService, $this->model->get('owned_by_user'), $file->get('remoteId'));
         $cExt = $tex ? 'tex' : \Components\Projects\Helpers\Google::getGoogleImportExt($resource['mimeType']);
         $cExt = in_array($cExt, array('tex', 'jpeg')) ? $cExt : 'pdf';
         $url = \Components\Projects\Helpers\Google::getDownloadUrl($resource, $cExt);
         // Get data
         $view->data = $this->_connect->sendHttpRequest($this->_remoteService, $this->model->get('owned_by_user'), $url);
     } elseif ($file->exists()) {
         $view->data = $file->isImage() ? NULL : $file->contents();
     } else {
         $this->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_COMPILE_NO_DATA'));
     }
     // LaTeX file?
     if ($tex && !empty($view->data)) {
         // Clean up data from Windows characters - important!
         $view->data = preg_replace('/[^(\\x20-\\x7F)\\x0A]*/', '', $view->data);
         // Compile and get path to PDF
         $contentFile = $compiler->compileTex($file->get('fullPath'), $view->data, $texPath, PATH_APP . $outputDir, 1, $tempBase);
         // Read log (to show in case of error)
         $logFile = $tempBase . '.log';
         if (file_exists(PATH_APP . $outputDir . DS . $logFile)) {
             $view->log = Filesystem::read(PATH_APP . $outputDir . DS . $logFile);
         }
         if (!$contentFile) {
             $this->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_COMPILE_TEX_FAILED'));
         }
     } elseif ($file->get('converted') && !empty($view->data)) {
         $tempBase = \Components\Projects\Helpers\Google::getImportFilename($file->get('name'), $cExt);
         // Write content to temp file
         $this->_connect->fetchFile($view->data, $tempBase, PATH_APP . $outputDir);
         $contentFile = $tempBase;
     } elseif (!$this->getError()) {
         // Make sure we can handle preview of this type of file
         if ($file->get('ext') == 'pdf' || $file->isImage() || !$file->isBinary()) {
             Filesystem::copy($file->get('fullPath'), PATH_APP . $outputDir . DS . $tempBase);
             $contentFile = $tempBase;
         }
     }
     $url = $this->model->link('files');
     $url .= $this->repo->isLocal() ? '' : '&repo=' . $this->repo->get('name');
     $url .= $this->subdir ? '&subdir=' . urlencode($this->subdir) : '';
     // Parse output
     if (!empty($contentFile) && file_exists(PATH_APP . $outputDir . DS . $contentFile)) {
         // Get compiled content mimetype
         $cType = Filesystem::mimetype(PATH_APP . $outputDir . DS . $contentFile);
         // Is image?
         if (strpos($cType, 'image/') !== false) {
             // Fix up object width & height
             list($width, $height, $type, $attr) = getimagesize(PATH_APP . $outputDir . DS . $contentFile);
             $xRatio = $view->oWidth / $width;
             $yRatio = $view->oHeight / $height;
             if ($xRatio * $height < $view->oHeight) {
                 // Resize the image based on width
                 $view->oHeight = ceil($xRatio * $height);
             } else {
                 // Resize the image based on height
                 $view->oWidth = ceil($yRatio * $width);
             }
         }
         // Download compiled file?
         if ($download) {
             $pdfName = $tex ? str_replace('temp__', '', basename($contentFile)) : basename($contentFile);
             // Serve up file
             $server = new \Hubzero\Content\Server();
             $server->filename(PATH_APP . $outputDir . DS . $contentFile);
             $server->disposition('attachment');
             $server->acceptranges(false);
             $server->saveas($pdfName);
             $result = $server->serve_attachment(PATH_APP . $outputDir . DS . $contentFile, $pdfName, false);
             if (!$result) {
                 // Should only get here on error
                 App::abort(404, Lang::txt('PLG_PROJECTS_FILES_SERVER_ERROR'));
             } else {
                 exit;
             }
         }
         // Add compiled PDF to repository?
         if ($commit && $tex) {
             $pdfName = str_replace('temp__', '', basename($contentFile));
             $where = $this->subdir ? $this->subdir . DS . $pdfName : $pdfName;
             if (Filesystem::copy(PATH_APP . $outputDir . DS . $contentFile, $this->_path . DS . $where)) {
                 // Checkin into repo
                 $params = array('subdir' => $this->subdir);
                 $params['file'] = $this->repo->getMetadata($pdfName, 'file', $params);
                 $this->repo->call('checkin', $params);
                 if ($this->repo->isLocal()) {
                     $this->model->saveParam('google_sync_queue', 1);
                 }
                 \Notify::message(Lang::txt('PLG_PROJECTS_FILES_SUCCESS_COMPILED'), 'success', 'projects');
                 // Redirect to file list
                 App::redirect(Route::url($url));
                 return;
             }
         }
         // Generate preview image for browsers that cannot embed pdf
         if ($cType == 'application/pdf') {
             // GS path
             $gspath = trim($this->params->get('gspath'), DS);
             if ($gspath && file_exists(DS . $gspath . DS . 'gs')) {
                 $gspath = DS . $gspath . DS;
                 $pdfName = $tex ? str_replace('temp__', '', basename($contentFile)) : basename($contentFile);
                 $pdfPath = PATH_APP . $outputDir . DS . $contentFile;
                 $exportPath = PATH_APP . $outputDir . DS . $tempBase . '%d.jpg';
                 exec($gspath . "gs -dNOPAUSE -sDEVICE=jpeg -r300 -dFirstPage=1 -dLastPage=1 -sOutputFile={$exportPath} {$pdfPath} 2>&1", $out);
                 if (is_file(PATH_APP . $outputDir . DS . $tempBase . '1.jpg')) {
                     $hi = new \Hubzero\Image\Processor(PATH_APP . $outputDir . DS . $tempBase . '1.jpg');
                     if (count($hi->getErrors()) == 0) {
                         $hi->resize($view->oWidth, false, false, true);
                         $hi->save(PATH_APP . $outputDir . DS . $tempBase . '1.jpg');
                     } else {
                         return false;
                     }
                 }
                 if (is_file(PATH_APP . $outputDir . DS . $tempBase . '1.jpg')) {
                     $image = $tempBase . '1.jpg';
                 }
             }
         }
     } elseif (!$this->getError()) {
         $this->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_COMPILE_PREVIEW_FAILED'));
     }
     $view->file = $file;
     $view->outputDir = $outputDir;
     $view->embed = $contentFile;
     $view->cType = $cType;
     $view->subdir = $this->subdir;
     $view->option = $this->_option;
     $view->image = !empty($image) ? $image : NULL;
     $view->model = $this->model;
     $view->repo = $this->repo;
     if ($this->getError()) {
         $view->setError($this->getError());
     }
     return $view->loadTemplate();
 }
Exemple #12
0
        } else {
            $status = '';
        }
        $tpl->content = $gui->renderConfig($security->config, $status);
        $content = 'config.tpl.php';
        break;
    case 'login':
        if (isset($_POST['password'])) {
            $retry = $security->checkLogin($_POST['password']);
        }
        $tpl->content = $gui->renderLogin(isset($retry));
        $content = 'login.tpl.php';
        break;
    case 'browser':
        $security->checkPath();
        if (isset($_POST['submit_delete'])) {
            unset($_POST['submit_delete'], $_POST['p']);
            $filesystem->delete($security->absolutePath, $_POST);
        }
        $tpl->absolutePath = $security->absolutePath;
        $tpl->relativePath = $security->relativePath;
        $tpl->sortName = isset($_GET['sortName']) ? $_GET['sortName'] : 'filename';
        $tpl->sortOrder = isset($_GET['sortOrder']) ? $_GET['sortOrder'] : 'asc';
        $tpl->content = $gui->renderResults($filesystem->read($security->absolutePath, $security->relativePath, $tpl->sortName, $tpl->sortOrder));
        $tpl->up = $gui->renderUp($filesystem->dirUp($security->relativePath), $security->config['root']);
        $content = 'browser.tpl.php';
        break;
}
$tpl->display('header.tpl.php');
$tpl->display($content);
$tpl->display('footer.tpl.php');
Exemple #13
0
 /**
  * @expectedException \UnexpectedValueException
  * @expectedExceptionMessage Instance of the DOM config merger is expected, got StdClass instead.
  */
 public function testReadException()
 {
     $this->_fileResolverMock->expects($this->once())->method('get')->will($this->returnValue([$this->_file]));
     $model = new Filesystem($this->_fileResolverMock, $this->_converterMock, $this->_schemaLocatorMock, $this->_validationStateMock, 'fileName', [], 'StdClass');
     $model->read();
 }
Exemple #14
0
 /**
  * @dataProvider filesystemProvider
  */
 public function testPutStream(Filesystem $filesystem, $adapter, $cache)
 {
     $filesystem->flushCache();
     $stream = tmpfile();
     fwrite($stream, 'new content');
     $this->assertFalse($filesystem->has('new_file.txt'));
     $this->assertTrue($filesystem->putStream('new_file.txt', $stream));
     fclose($stream);
     unset($stream);
     $this->assertTrue($filesystem->has('new_file.txt'));
     $this->assertEquals('new content', $filesystem->read('new_file.txt'));
     $update = tmpfile();
     fwrite($update, 'modified content');
     $this->assertTrue($filesystem->putStream('new_file.txt', $update));
     $filesystem->flushCache();
     fclose($update);
     $this->assertEquals('modified content', $filesystem->read('new_file.txt'));
 }
Exemple #15
0
 /**
  * Load the contents of a file into the registry
  *
  * @param   string   $file     Path to file to load
  * @param   string   $format   Format of the file [optional: defaults to JSON]
  * @param   mixed    $options  Options used by the formatter
  * @return  boolean  True on success
  */
 public function loadFile($file, $format = 'JSON', $options = array())
 {
     // Get the contents of the file
     $data = \Filesystem::read($file);
     return $this->loadString($data, $format, $options);
 }
 /**
  * Compiles PDF/image preview for any kind of file
  *
  * @return  string
  */
 public function compile()
 {
     // Combine file and folder data
     $items = $this->getCollection();
     // Incoming
     $download = Request::getInt('download', 0);
     // Check that we have compile enabled
     // @FIXME: why are latex and compiled preview tied together?
     //         presumedly we are also 'compiling' pdfs?
     if (!$this->params->get('latex')) {
         $this->setError(Lang::txt('PLG_PROJECTS_FILES_COMPILE_NOTALLOWED'));
         return;
     }
     // Output HTML
     $view = new \Hubzero\Plugin\View(['folder' => 'projects', 'element' => 'files', 'name' => 'connected', 'layout' => 'compiled']);
     // Make sure we have an item
     if (count($items) == 0) {
         $view->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_NO_FILES_TO_COMPILE'));
         $view->loadTemplate();
         return;
     }
     // We can only handle one file at a time
     $file = $items->first();
     // Build path for storing temp previews
     $imagePath = trim($this->model->config()->get('imagepath', '/site/projects'), DS);
     $outputDir = DS . $imagePath . DS . strtolower($this->model->get('alias')) . DS . 'compiled';
     // Make sure output dir exists
     if (!is_dir(PATH_APP . $outputDir)) {
         if (!Filesystem::makeDirectory(PATH_APP . $outputDir)) {
             $this->setError(Lang::txt('PLG_PROJECTS_FILES_UNABLE_TO_CREATE_UPLOAD_PATH'));
             return;
         }
     }
     // Get LaTeX helper
     $compiler = new \Components\Projects\Helpers\Compiler();
     // Tex compiler path
     $texPath = DS . trim($this->params->get('texpath'), DS);
     // Set view args and defaults
     $view->file = $file;
     $view->oWidth = '780';
     $view->oHeight = '460';
     $view->url = $this->model->link('files');
     $cExt = 'pdf';
     // Tex file?
     $tex = $compiler->isTexFile($file->getName());
     // Build temp name
     $tempBase = $tex ? 'temp__' . \Components\Projects\Helpers\Html::takeOutExt($file->getName()) : $file->getName();
     $tempBase = str_replace(' ', '_', $tempBase);
     $view->data = $file->isImage() ? NULL : $file->read();
     // LaTeX file?
     if ($tex && !empty($view->data)) {
         // Clean up data from Windows characters - important!
         $view->data = preg_replace('/[^(\\x20-\\x7F)\\x0A]*/', '', $view->data);
         // Store file locally
         $tmpfile = PATH_APP . $outputDir . DS . $tempBase;
         file_put_contents($tmpfile, $view->data);
         // Compile and get path to PDF
         $contentFile = $compiler->compileTex($tmpfile, $view->data, $texPath, PATH_APP . $outputDir, 1, $tempBase);
         // Read log (to show in case of error)
         $logFile = $tempBase . '.log';
         if (file_exists(PATH_APP . $outputDir . DS . $logFile)) {
             $view->log = Filesystem::read(PATH_APP . $outputDir . DS . $logFile);
         }
         if (!$contentFile) {
             $this->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_COMPILE_TEX_FAILED'));
         }
         $cType = Filesystem::mimetype(PATH_APP . $outputDir . DS . $contentFile);
     } else {
         // Make sure we can handle preview of this type of file
         if ($file->hasExtension('pdf') || $file->isImage() || !$file->isBinary()) {
             $origin = $this->connection->provider->alias . '://' . $file->getPath();
             $dest = 'compiled://' . $tempBase;
             // Do the copy
             Manager::adapter('local', ['path' => PATH_APP . $outputDir . DS], 'compiled');
             Manager::copy($origin, $dest);
             $contentFile = $tempBase;
         }
     }
     // Parse output
     if (!empty($contentFile) && file_exists(PATH_APP . $outputDir . DS . $contentFile)) {
         // Get compiled content mimetype
         $cType = Filesystem::mimetype(PATH_APP . $outputDir . DS . $contentFile);
         // Is image?
         if (strpos($cType, 'image/') !== false) {
             // Fix up object width & height
             list($width, $height, $type, $attr) = getimagesize(PATH_APP . $outputDir . DS . $contentFile);
             $xRatio = $view->oWidth / $width;
             $yRatio = $view->oHeight / $height;
             if ($xRatio * $height < $view->oHeight) {
                 // Resize the image based on width
                 $view->oHeight = ceil($xRatio * $height);
             } else {
                 // Resize the image based on height
                 $view->oWidth = ceil($yRatio * $width);
             }
         }
         // Download compiled file?
         if ($download) {
             $pdfName = $tex ? str_replace('temp__', '', basename($contentFile)) : basename($contentFile);
             // Serve up file
             $server = new \Hubzero\Content\Server();
             $server->filename(PATH_APP . $outputDir . DS . $contentFile);
             $server->disposition('attachment');
             $server->acceptranges(false);
             $server->saveas($pdfName);
             $result = $server->serve();
             if (!$result) {
                 // Should only get here on error
                 throw new Exception(Lang::txt('PLG_PROJECTS_FILES_SERVER_ERROR'), 404);
             } else {
                 exit;
             }
         }
         // Generate preview image for browsers that cannot embed pdf
         if ($cType == 'application/pdf') {
             // GS path
             $gspath = trim($this->params->get('gspath'), DS);
             if ($gspath && file_exists(DS . $gspath . DS . 'gs')) {
                 $gspath = DS . $gspath . DS;
                 $pdfName = $tex ? str_replace('temp__', '', basename($contentFile)) : basename($contentFile);
                 $pdfPath = PATH_APP . $outputDir . DS . $contentFile;
                 $exportPath = PATH_APP . $outputDir . DS . $tempBase . '%d.jpg';
                 exec($gspath . "gs -dNOPAUSE -sDEVICE=jpeg -r300 -dFirstPage=1 -dLastPage=1 -sOutputFile={$exportPath} {$pdfPath} 2>&1", $out);
                 if (is_file(PATH_APP . $outputDir . DS . $tempBase . '1.jpg')) {
                     $hi = new \Hubzero\Image\Processor(PATH_APP . $outputDir . DS . $tempBase . '1.jpg');
                     if (count($hi->getErrors()) == 0) {
                         $hi->resize($view->oWidth, false, false, true);
                         $hi->save(PATH_APP . $outputDir . DS . $tempBase . '1.jpg');
                     } else {
                         return false;
                     }
                 }
                 if (is_file(PATH_APP . $outputDir . DS . $tempBase . '1.jpg')) {
                     $image = $tempBase . '1.jpg';
                 }
             }
         }
     } elseif (!$this->getError()) {
         $this->setError(Lang::txt('PLG_PROJECTS_FILES_ERROR_COMPILE_PREVIEW_FAILED'));
     }
     $view->file = $file;
     $view->outputDir = $outputDir;
     $view->embed = $contentFile;
     $view->cType = $cType;
     $view->subdir = $this->subdir;
     $view->option = $this->_option;
     $view->image = !empty($image) ? $image : NULL;
     $view->model = $this->model;
     $view->repo = $this->repo;
     $view->connection = $this->connection;
     if ($this->getError()) {
         $view->setError($this->getError());
     }
     return $view->loadTemplate();
 }
 public static function printUsage($type)
 {
     $type = Inflector::underscore($type);
     echo Filesystem::read('/lib/generators/' . $type . '/USAGE');
 }
Exemple #18
0
 public static function tearDownAfterClass()
 {
     $connection = Connection::get('test');
     $connection->query(Filesystem::read('test/sql/users_down.sql'));
 }
Exemple #19
0
 /**
  * Method to get a single record.
  *
  * @return	mixed	Object on success, false on failure.
  * @since	1.6
  */
 public function &getSource()
 {
     $item = new stdClass();
     if (!$this->_template) {
         $this->getTemplate();
     }
     if ($this->_template) {
         $fileName = $this->getState('filename');
         $client = JApplicationHelper::getClientInfo($this->_template->client_id);
         $filePath = \Hubzero\Filesystem\Util::normalizePath($client->path . '/templates/' . $this->_template->element . '/' . $fileName);
         if (file_exists($filePath)) {
             $item->extension_id = $this->getState('extension.id');
             $item->filename = $this->getState('filename');
             $item->source = Filesystem::read($filePath);
         } else {
             $this->setError(Lang::txt('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_FOUND'));
         }
     }
     return $item;
 }
Exemple #20
0
 /**
  * Get an associative list of default pages and their content
  *
  * @return  array
  */
 private function _defaultPages()
 {
     $path = dirname(__DIR__) . DS . 'default';
     if ($this->_scope != '__site__') {
         $path .= DS . 'groups';
     }
     $pages = array();
     if (is_dir($path)) {
         $dirIterator = new \DirectoryIterator($path);
         foreach ($dirIterator as $file) {
             if ($file->isDot() || $file->isDir()) {
                 continue;
             }
             if ($file->isFile()) {
                 $fl = $file->getFilename();
                 if (strtolower(\Filesystem::extension($fl)) == 'txt') {
                     $name = \Filesystem::name($fl);
                     $pages[$name] = \Filesystem::read($path . DS . $fl);
                 }
             }
         }
     }
     return $pages;
 }