/** * Generate local thumbnail from remote * * @param string $service Service name (google or dropbox) * @param integer $uid User ID * @param array $remote Remote resource array * @param array $config Configuration array * @param string $alias Project alias name * * @return void */ public function generateThumbnail($service = 'google', $uid = 0, $remote = array(), $config = array(), $alias = NULL) { if (empty($remote) || !$remote['thumb'] || empty($config) || !$alias) { return false; } $thumb = substr($remote['remoteid'], 0, 20) . '_' . strtotime($remote['modified']) . '.png'; $imagepath = trim($config->get('imagepath', '/site/projects'), DS); $to_path = DS . $imagepath . DS . strtolower($alias) . DS . 'preview'; if (is_dir(PATH_APP . $to_path) && !is_file(PATH_APP . $to_path . DS . $thumb)) { // Get thumnail $fc = $this->sendHttpRequest($service, $uid, $remote['thumb']); if ($fc && $this->fetchFile($fc, $thumb, PATH_APP . $to_path)) { $handle = @fopen(PATH_APP . $to_path . DS . $thumb, 'w'); if ($handle) { fwrite($handle, $fc); fclose($handle); // Resize image $hi = new \Hubzero\Image\Processor(PATH_APP . $to_path . DS . $thumb); if (count($hi->getErrors()) == 0) { $hi->resize(180, false, false, true); $hi->save(PATH_APP . $to_path . DS . $thumb); } else { return false; } } } } }
/** * Get preview image * * @return mixed */ public function getPreview($model, $hash = '', $get = 'name', $render = '', $hashed = NULL) { if (!$model instanceof Project) { return false; } $image = NULL; if (!$hashed) { $hash = $hash ? $hash : $this->get('hash'); $hash = $hash ? substr($hash, 0, 10) : ''; // Determine name and size switch ($render) { case 'medium': $hashed = md5($this->get('name') . '-' . $hash) . '.png'; $maxWidth = 600; $maxHeight = 600; break; case 'thumb': $hashed = $hash ? Helpers\Html::createThumbName($this->get('name'), '-' . $hash, 'png') : NULL; $maxWidth = 80; $maxHeight = 80; break; default: $hashed = $hash ? Helpers\Html::createThumbName($this->get('name'), '-' . $hash . '-thumb', 'png') : NULL; $maxWidth = 180; $maxHeight = 180; break; } } // Target directory $target = PATH_APP . DS . trim($model->config()->get('imagepath', '/site/projects'), DS); $target .= DS . strtolower($model->get('alias')) . DS . 'preview'; $remoteThumb = NULL; if ($this->get('remoteId') && $this->get('modified')) { $remoteThumb = substr($this->get('remoteId'), 0, 20) . '_' . strtotime($this->get('modified')) . '.png'; } if ($hashed && is_file($target . DS . $hashed)) { // First check locally generated thumbnail $image = $target . DS . $hashed; } elseif ($remoteThumb && is_file($target . DS . $remoteThumb)) { // Check remotely generated thumbnail $image = $target . DS . $remoteThumb; // Copy this over as local thumb if ($hashed && Filesystem::copy($target . DS . $remoteThumb, $target . DS . $hashed)) { Filesystem::delete($target . DS . $remoteThumb); } } else { // Generate thumbnail locally if (!file_exists($target)) { Filesystem::makeDirectory($target, 0755, true, true); } // Make sure it's an image file if (!$this->isImage() || !is_file($this->get('fullPath'))) { return false; } if (!Filesystem::copy($this->get('fullPath'), $target . DS . $hashed)) { return false; } // Resize the image if necessary $hi = new \Hubzero\Image\Processor($target . DS . $hashed); $square = $render == 'thumb' ? true : false; $hi->resize($maxWidth, false, false, $square); $hi->save($target . DS . $hashed); $image = $target . DS . $hashed; } // Return image if ($get == 'localPath') { return str_replace(PATH_APP, '', $image); } elseif ($get == 'fullPath') { return $image; } elseif ($get == 'url') { return Route::url('index.php?option=com_projects&alias=' . $model->get('alias') . '&controller=media&media=' . urlencode(basename($image))); } return basename($image); }
/** * 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(); }
/** * Publish supporting database files * * @param object $objPD * * @return boolean or error */ public function publishDataFiles($objPD, $configs) { if (!$objPD->id) { return false; } // Get data definition $dd = json_decode($objPD->data_definition, true); $files = array(); $columns = array(); foreach ($dd['cols'] as $colname => $col) { if (isset($col['linktype']) && $col['linktype'] == "repofiles") { $dir = ''; if (isset($col['linkpath']) && $col['linkpath'] != '') { $dir = $col['linkpath']; } $columns[$col['idx']] = $dir; } } // No files to publish if (empty($columns)) { return false; } $repoPath = $objPD->source_dir ? $configs->path . DS . $objPD->source_dir : $configs->path; $csv = $repoPath . DS . $objPD->source_file; if (file_exists($csv) && ($handle = fopen($csv, "r")) !== FALSE) { // Check if expert mode CSV $expert_mode = false; $col_labels = fgetcsv($handle); $col_prop = fgetcsv($handle); $data_start = fgetcsv($handle); if (isset($data_start[0]) && $data_start[0] == 'DATASTART') { $expert_mode = true; } while ($r = fgetcsv($handle)) { for ($i = 0; $i < count($col_labels); $i++) { if (isset($columns[$i])) { if (isset($r[$i]) && $r[$i] != '') { $file = $columns[$i] ? $columns[$i] . DS . trim($r[$i]) : trim($r[$i]); if (file_exists($repoPath . DS . $file)) { $files[] = $file; } } } } } } // Copy files from repo to published location if (!empty($files)) { foreach ($files as $file) { if (!file_exists($repoPath . DS . $file)) { continue; } // If parent dir does not exist, we must create it if (!file_exists(dirname($configs->dataPath . DS . $file))) { Filesystem::makeDirectory(dirname($configs->dataPath . DS . $file), 0755, true, true); } if (Filesystem::copy($repoPath . DS . $file, $configs->dataPath . DS . $file)) { // Generate thumbnail $thumb = \Components\Publications\Helpers\Html::createThumbName($file, '_tn', $extension = 'gif'); Filesystem::copy($repoPath . DS . $file, $configs->dataPath . DS . $thumb); $hi = new \Hubzero\Image\Processor($configs->dataPath . DS . $thumb); if (count($hi->getErrors()) == 0) { $hi->resize(180, false, false, false); $hi->save($configs->dataPath . DS . $thumb); } else { return false; } // Generate medium image $med = \Components\Publications\Helpers\Html::createThumbName($file, '_medium', $extension = 'gif'); Filesystem::copy($repoPath . DS . $file, $configs->dataPath . DS . $med); $hi = new \Hubzero\Image\Processor($configs->dataPath . DS . $med); if (count($hi->getErrors()) == 0) { $hi->resize(800, false, false, false); $hi->save($configs->dataPath . DS . $med); } else { return false; } } } } }
/** * 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(); }
/** * Upload a file to the profile via AJAX * * @return string */ public function doajaxuploadTask() { //allowed extensions for uplaod $allowedExtensions = array('png', 'jpe', 'jpeg', 'jpg', 'gif'); //max upload size $sizeLimit = $this->config->get('maxAllowed', '40000000'); // get the file if (isset($_GET['qqfile'])) { $stream = true; $file = $_GET['qqfile']; $size = (int) $_SERVER["CONTENT_LENGTH"]; } elseif (isset($_FILES['qqfile'])) { $stream = false; $file = $_FILES['qqfile']['name']; $size = (int) $_FILES['qqfile']['size']; } else { echo json_encode(array('error' => Lang::txt('Please select a file to upload'))); return; } //check to make sure we have a file and its not too big if ($size == 0) { echo json_encode(array('error' => Lang::txt('File is empty'))); return; } if ($size > $sizeLimit) { $max = preg_replace('/<abbr \\w+=\\"\\w+\\">(\\w{1,3})<\\/abbr>/', '$1', \Hubzero\Utility\Number::formatBytes($sizeLimit)); echo json_encode(array('error' => Lang::txt('File is too large. Max file upload size is ') . $max)); return; } //check to make sure we have an allowable extension $pathinfo = pathinfo($file); $filename = $pathinfo['filename']; $ext = $pathinfo['extension']; if ($allowedExtensions && !in_array(strtolower($ext), $allowedExtensions)) { $these = implode(', ', $allowedExtensions); echo json_encode(array('error' => Lang::txt('File has an invalid extension, it should be one of ' . $these . '.'))); return; } // Make the filename safe $file = Filesystem::clean($file); // Check project exists if (!$this->model->exists()) { echo json_encode(array('error' => Lang::txt('Error loading project'))); return; } // Make sure user is authorized (project manager) if (!$this->model->access('manager')) { echo json_encode(array('error' => Lang::txt('Unauthorized action'))); return; } // Build project image path $path = PATH_APP . DS . trim($this->config->get('imagepath', '/site/projects'), DS); $path .= DS . $this->model->get('alias') . DS . 'images'; if (!is_dir($path)) { if (!Filesystem::makeDirectory($path, 0755, true, true)) { echo json_encode(array('error' => Lang::txt('COM_PROJECTS_UNABLE_TO_CREATE_UPLOAD_PATH'))); return; } } // Delete older file with same name if (file_exists($path . DS . $file)) { Filesystem::delete($path . DS . $file); } if ($stream) { //read the php input stream to upload file $input = fopen("php://input", "r"); $temp = tmpfile(); $realSize = stream_copy_to_stream($input, $temp); fclose($input); if (Helpers\Html::virusCheck($temp)) { echo json_encode(array('error' => Lang::txt('Virus detected, refusing to upload'))); return; } //move from temp location to target location which is user folder $target = fopen($path . DS . $file, "w"); fseek($temp, 0, SEEK_SET); stream_copy_to_stream($temp, $target); fclose($target); } else { move_uploaded_file($_FILES['qqfile']['tmp_name'], $path . DS . $file); } // Perform the upload if (!is_file($path . DS . $file)) { echo json_encode(array('error' => Lang::txt('COM_PROJECTS_ERROR_UPLOADING'))); return; } else { //resize image to max 200px and rotate in case user didnt before uploading $hi = new \Hubzero\Image\Processor($path . DS . $file); if (count($hi->getErrors()) == 0) { $hi->autoRotate(); $hi->resize(200); $hi->setImageType(IMAGETYPE_PNG); $hi->save($path . DS . $file); } else { echo json_encode(array('error' => $hi->getError())); return; } // Delete previous thumb if (file_exists($path . DS . 'thumb.png')) { Filesystem::delete($path . DS . 'thumb.png'); } // create thumb $hi = new \Hubzero\Image\Processor($path . DS . $file); if (count($hi->getErrors()) == 0) { $hi->resize(50, false, true, true); $hi->save($path . DS . 'thumb.png'); } else { echo json_encode(array('error' => $hi->getError())); return; } // Save picture name $this->model->set('picture', $file); if (!$this->model->store()) { echo json_encode(array('error' => $this->model->getError())); return; } elseif (!$this->model->inSetup()) { // Record activity $this->model->recordActivity(Lang::txt('COM_PROJECTS_REPLACED_PROJECT_PICTURE')); } } echo json_encode(array('success' => true)); return; }
<?php if ($this->row->get('background_img', false)) { ?> <fieldset class="adminform"> <legend><span><?php echo Lang::txt('COM_BILLBOARDS_CURRENT_IMG'); ?> </span></legend> <?php $image = new \Hubzero\Image\Processor(PATH_ROOT . DS . ltrim($this->row->background_img, DS)); ?> <?php if (count($image->getErrors()) == 0) { ?> <?php $image->resize(500); ?> <div style="padding: 10px;"><img src="<?php echo $image->inline(); ?> " alt="billboard image" /></div> <?php } ?> </fieldset> <?php } ?> <fieldset class="adminform"> <!-- @TODO: remove inline styles --> <legend id="styling" style="cursor:pointer;"><?php
/** * Upload a file * * @return void */ public function uploadTask() { // Check for request forgeries Request::checkToken(); // Incoming $id = Request::getInt('id', 0); $curfile = Request::getVar('file', ''); $file = Request::getVar('upload', '', 'files', 'array'); // Build upload path $dir = \Hubzero\Utility\String::pad($id); $path = PATH_APP . DS . trim($this->config->get('webpath', '/site/members'), DS) . DS . $dir; //allowed extensions for uplaod $allowedExtensions = array('png', 'jpe', 'jpeg', 'jpg', 'gif'); //max upload size $sizeLimit = $this->config->get('maxAllowed', '40000000'); // make sure we have id if (!$id) { $this->setError(Lang::txt('COM_MEMBERS_NO_ID')); $this->displayTask($curfile, $id); return; } // make sure we have a file if (!$file['name']) { $this->setError(Lang::txt('COM_MEMBERS_NO_FILE')); $this->displayTask($curfile, $id); return; } // make sure we have an upload path if (!is_dir($path)) { if (!Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('COM_MEMBERS_UNABLE_TO_CREATE_UPLOAD_PATH')); $this->displayTask($curfile, $id); return; } } // make sure file is not empty if ($file['size'] == 0) { $this->setError(Lang::txt('COM_MEMBERS_FILE_HAS_NO_SIZE')); $this->displayTask($curfile, $id); return; } // make sure file is not empty if ($file['size'] > $sizeLimit) { $max = preg_replace('/<abbr \\w+=\\"\\w+\\">(\\w{1,3})<\\/abbr>/', '$1', \Hubzero\Utility\Number::formatBytes($sizeLimit)); $this->setError(Lang::txt('FILE_SIZE_TOO_BIG', $max)); $this->displayTask($curfile, $id); return; } // must be in allowed extensions $pathInfo = pathinfo($file['name']); $ext = $pathInfo['extension']; if (!in_array($ext, $allowedExtensions)) { $these = implode(', ', $allowedExtensions); $this->setError(Lang::txt('COM_MEMBERS_FILE_TYPE_NOT_ALLOWED', $these)); $this->displayTask($curfile, $id); return; } // build needed paths $filePath = $path . DS . $file['name']; $profilePath = $path . DS . 'profile.png'; $thumbPath = $path . DS . 'thumb.png'; // upload image if (!Filesystem::upload($file['tmp_name'], $filePath)) { $this->setError(Lang::txt('COM_MEMBERS_ERROR_UPLOADING')); $this->displayTask($curfile, $id); return; } // create profile pic $imageProcessor = new \Hubzero\Image\Processor($filePath); if (count($imageProcessor->getErrors()) == 0) { $imageProcessor->autoRotate(); $imageProcessor->resize(400); $imageProcessor->setImageType(IMAGETYPE_PNG); $imageProcessor->save($profilePath); } // create thumb $imageProcessor = new \Hubzero\Image\Processor($filePath); if (count($imageProcessor->getErrors()) == 0) { $imageProcessor->resize(50, false, true, true); $imageProcessor->save($thumbPath); } // update profile $profile = \Hubzero\User\Profile::getInstance($id); $profile->set('picture', 'profile.png'); if (!$profile->update()) { $this->setError($profile->getError()); } // remove orig file unlink($filePath); // Push through to the image view $this->displayTask('profile.png', $id); }
/** * Upload a file to the profile via AJAX * * @return string */ public function doajaxuploadTask() { Request::checkToken(['get', 'post']); //allowed extensions for uplaod $allowedExtensions = array('png', 'jpe', 'jpeg', 'jpg', 'gif'); //max upload size $sizeLimit = $this->config->get('maxAllowed', '40000000'); //get the file if (isset($_GET['qqfile'])) { $stream = true; $file = $_GET['qqfile']; $size = (int) $_SERVER["CONTENT_LENGTH"]; } elseif (isset($_FILES['qqfile'])) { $stream = false; $file = $_FILES['qqfile']['name']; $size = (int) $_FILES['qqfile']['size']; } else { return; } //get the id and load profile $id = Request::getVar('id', 0); $profile = \Hubzero\User\Profile::getInstance($id); if (!$profile) { return; } //define upload directory and make sure its writable $uploadDirectory = PATH_APP . DS . $this->filespace() . DS . \Hubzero\Utility\String::pad($id) . DS; if (!is_dir($uploadDirectory)) { if (!Filesystem::makeDirectory($uploadDirectory)) { echo json_encode(array('error' => 'Server error. Unable to create upload directory.')); return; } } if (!is_writable($uploadDirectory)) { echo json_encode(array('error' => "Server error. Upload directory isn't writable.")); return; } //check to make sure we have a file and its not too big if ($size == 0) { echo json_encode(array('error' => 'File is empty')); return; } if ($size > $sizeLimit) { $max = preg_replace('/<abbr \\w+=\\"\\w+\\">(\\w{1,3})<\\/abbr>/', '$1', \Hubzero\Utility\Number::formatBytes($sizeLimit)); echo json_encode(array('error' => 'File is too large. Max file upload size is ' . $max)); return; } //check to make sure we have an allowable extension $pathinfo = pathinfo($file); $filename = $pathinfo['filename']; $ext = $pathinfo['extension']; if ($allowedExtensions && !in_array(strtolower($ext), $allowedExtensions)) { $these = implode(', ', $allowedExtensions); echo json_encode(array('error' => 'File has an invalid extension, it should be one of ' . $these . '.')); return; } // don't overwrite previous files that were uploaded while (file_exists($uploadDirectory . $filename . '.' . $ext)) { $filename .= rand(10, 99); } $file = $uploadDirectory . $filename . '.' . $ext; $final_file = $uploadDirectory . 'profile.png'; $final_thumb = $uploadDirectory . 'thumb.png'; if ($stream) { //read the php input stream to upload file $input = fopen("php://input", "r"); $temp = tmpfile(); $realSize = stream_copy_to_stream($input, $temp); fclose($input); //move from temp location to target location which is user folder $target = fopen($file, "w"); fseek($temp, 0, SEEK_SET); stream_copy_to_stream($temp, $target); fclose($target); } else { move_uploaded_file($_FILES['qqfile']['tmp_name'], $file); } //resize image to max 400px and rotate in case user didnt before uploading $hi = new \Hubzero\Image\Processor($file); if (count($hi->getErrors()) == 0) { $hi->autoRotate(); $hi->resize(400); $hi->setImageType(IMAGETYPE_PNG); $hi->save($final_file); } else { echo json_encode(array('error' => $hi->getError())); return; } // create thumb $hi = new \Hubzero\Image\Processor($final_file); if (count($hi->getErrors()) == 0) { $hi->resize(50, false, true, true); $hi->save($final_thumb); } else { echo json_encode(array('error' => $hi->getError())); return; } // remove orig unlink($file); echo json_encode(array('success' => true, 'file' => str_replace($uploadDirectory, '', $final_file), 'directory' => str_replace(PATH_ROOT, '', $uploadDirectory))); }
/** * Make thumb * * @return void */ public function makeThumbnail($row, $pub, $configs) { // Make sure we got config if (!$this->_config) { $this->getConfig(); } $fpath = $this->getFilePath($row->path, $row->id, $configs, $row->params); $thumbName = \Components\Publications\Helpers\Html::createThumbName(basename($fpath), $this->_config->params->thumbSuffix, $this->_config->params->thumbFormat); $thumbPath = $configs->pubPath . DS . $thumbName; // No file found if (!is_file($fpath)) { return; } // Check if image if (!getimagesize($fpath)) { return false; } $md5 = hash_file('sha256', $fpath); // Create/update thumb if doesn't exist or file changed if (!is_file($thumbPath) || $md5 != $row->content_hash) { Filesystem::copy($fpath, $thumbPath); $hi = new \Hubzero\Image\Processor($thumbPath); if (count($hi->getErrors()) == 0) { $hi->resize($this->_config->params->thumbWidth, false, true, true); $hi->save($thumbPath); } else { return false; } } return true; }