/** * Constructor * * @param object $connect * @return void */ public function __construct($connect = NULL) { if (empty($connect)) { return false; } $this->_db = \App::get('db'); $this->_connect = $connect; $this->model = $connect->model; $this->_uid = User::get('id'); $this->params = Plugin::params('projects', 'files'); $this->_logPath = \Components\Projects\Helpers\Html::getProjectRepoPath($this->model->get('alias'), 'logs', false); if (!is_dir($this->_logPath)) { Filesystem::makeDirectory($this->_logPath, 0755, true, true); } $this->_path = $this->model->repo()->get('path'); }
/** * Make dir * * @param array $params * * @return array */ public function makeDirectory($params = array()) { $file = isset($params['file']) ? $params['file'] : NULL; if (!$file instanceof Models\File || $file->get('type') != 'folder') { return false; } if (!$this->get('remote')) { if (Filesystem::makeDirectory($file->get('fullPath'), 0755, true, true)) { $this->checkin($params); return true; } } 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); }
/** * Build the path for uploading a resume to * * @param integer $uid User ID * @return mixed False if errors, string otherwise */ public function build_path($uid) { // Get the configured upload path $base_path = $this->params->get('webpath', '/site/members'); $base_path = DS . trim($base_path, DS); $dir = \Hubzero\Utility\String::pad($uid); $listdir = $base_path . DS . $dir; if (!is_dir(PATH_APP . $listdir)) { if (!Filesystem::makeDirectory(PATH_APP . $listdir)) { return false; } } // Build the path return $listdir; }
/** * 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; } } } } }
/** * Generate detailed responses CSV files and zip and offer up as download * * @return void **/ private function downloadresponses() { require_once PATH_CORE . DS . 'components' . DS . 'com_courses' . DS . 'models' . DS . 'formReport.php'; // Only allow for instructors if (!$this->course->offering()->section()->access('manage')) { App::abort(403, 'Sorry, you don\'t have permission to do this'); } if (!($asset_ids = Request::getVar('assets', false))) { App::abort(422, 'Sorry, we don\'t know what results you\'re trying to retrieve'); } $protected = 'site' . DS . 'protected'; $tmp = $protected . DS . 'tmp'; // We're going to temporarily house this in PATH_APP/site/protected/tmp if (!Filesystem::exists($protected)) { App::abort(500, 'Missing temporary directory'); } // Make sure tmp folder exists if (!Filesystem::exists($tmp)) { Filesystem::makeDirectory($tmp); } else { // Folder was already there - do a sanity check and make sure no old responses zips are lying around $files = Filesystem::files($tmp); if ($files && count($files) > 0) { foreach ($files as $file) { if (strstr($file, 'responses.zip') !== false) { Filesystem::delete($tmp . DS . $file); } } } } // Get the individual asset ids $asset_ids = explode('-', $asset_ids); // Set up our zip archive $zip = new ZipArchive(); $path = PATH_APP . DS . $tmp . DS . time() . '.responses.zip'; $zip->open($path, ZipArchive::CREATE); // Loop through the assets foreach ($asset_ids as $asset_id) { // Is it a number? if (!is_numeric($asset_id)) { continue; } // Get the rest of the asset row $asset = new \Components\Courses\Tables\Asset($this->db); $asset->load($asset_id); // Make sure asset is a part of this course if ($asset->get('course_id') != $this->course->get('id')) { continue; } if ($details = \Components\Courses\Models\FormReport::getLetterResponsesForAssetId($this->db, $asset_id, true, $this->course->offering()->section()->get('id'))) { $output = implode(',', $details['headers']) . "\n"; if (isset($details['responses']) && count($details['responses']) > 0) { foreach ($details['responses'] as $response) { $output .= implode(',', $response) . "\n"; } } $zip->addFromString($asset_id . '.responses.csv', $output); } else { continue; } } // Close the zip archive handler $zip->close(); if (is_file($path)) { // Set up the server $xserver = new \Hubzero\Content\Server(); $xserver->filename($path); $xserver->saveas('responses.zip'); $xserver->disposition('attachment'); $xserver->acceptranges(false); // Serve the file $xserver->serve(); // Now delete the file Filesystem::delete($path); } // All done! exit; }
/** * 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; }
/** * Upload an image * * @return void */ public function uploadTask() { // Check for request forgeries Request::checkToken(); // Incoming $id = Request::getInt('id', 0); if (!$id) { $this->setError(Lang::txt('COM_STORE_FEEDBACK_NO_ID')); $this->displayTask($id); return; } // Incoming file $file = Request::getVar('upload', '', 'files', 'array'); if (!$file['name']) { $this->setError(Lang::txt('COM_STORE_FEEDBACK_NO_FILE')); $this->displayTask($id); return; } // Build upload path $path = PATH_APP . DS . trim($this->config->get('webpath', '/site/store'), DS) . DS . $id; if (!is_dir($path)) { if (!\Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('COM_STORE_UNABLE_TO_CREATE_UPLOAD_PATH')); $this->displayTask($id); return; } } // Make the filename safe $file['name'] = \Filesystem::clean($file['name']); $file['name'] = str_replace(' ', '_', $file['name']); require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'imghandler.php'; // Perform the upload if (!\Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('COM_STORE_ERROR_UPLOADING')); } else { $ih = new ImgHandler(); // Do we have an old file we're replacing? if ($curfile = Request::getVar('currentfile', '')) { // Remove old image if (file_exists($path . DS . $curfile)) { if (!\Filesystem::delete($path . DS . $curfile)) { $this->setError(Lang::txt('COM_STORE_UNABLE_TO_DELETE_FILE')); $this->displayTask($id); return; } } // Get the old thumbnail name $curthumb = $ih->createThumbName($curfile); // Remove old thumbnail if (file_exists($path . DS . $curthumb)) { if (!\Filesystem::delete($path . DS . $curthumb)) { $this->setError(Lang::txt('COM_STORE_UNABLE_TO_DELETE_FILE')); $this->displayTask($id); return; } } } // Create a thumbnail image $ih->set('image', $file['name']); $ih->set('path', $path . DS); $ih->set('maxWidth', 80); $ih->set('maxHeight', 80); $ih->set('cropratio', '1:1'); $ih->set('outputName', $ih->createThumbName()); if (!$ih->process()) { $this->setError($ih->getError()); } } // Push through to the image view $this->displayTask($id); }
/** * Publish file attachment * * @param object $objPA * @param object $pub * @param object $configs * @param boolean $update force update of file * * @return boolean or error */ public function publishAttachment($objPA, $pub, $configs, $update = 0) { // Create pub version path if (!is_dir($configs->pubPath)) { if (!Filesystem::makeDirectory($configs->pubPath, 0755, true, true)) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_UNABLE_TO_CREATE_PATH')); return false; } } $file = $objPA->path; $copyFrom = isset($configs->copyFrom) ? $configs->copyFrom : $configs->path . DS . $file; $copyTo = $this->getFilePath($file, $objPA->id, $configs, $objPA->params); // Copy if (is_file($copyFrom)) { // If parent dir does not exist, we must create it if ($configs->dirHierarchy && !file_exists(dirname($copyTo))) { Filesystem::makeDirectory(dirname($copyTo), 0755, true, true); } if (!is_file($copyTo) || $update) { Filesystem::copy($copyFrom, $copyTo); } } // Store content hash if (is_file($copyTo)) { $md5hash = hash_file('sha256', $copyTo); $objPA->content_hash = $md5hash; // Create hash file $hfile = $copyTo . '.hash'; if (!is_file($hfile)) { $handle = fopen($hfile, 'w'); fwrite($handle, $md5hash); fclose($handle); chmod($hfile, 0644); } $objPA->store(); // Produce thumbnail (if applicable) if ($configs->handler && $configs->handler->getName() == 'imageviewer') { $configs->handler->makeThumbnail($objPA, $pub, $configs); } } else { return false; } return true; }
/** * Create images * * @return void */ public function renderPageImages() { try { if (!$this->exists()) { $this->setError(Lang::txt('No pages exist for nonexistent certificate.')); return false; } $base = $this->path('system'); if (!file_exists($base)) { if (!\Filesystem::makeDirectory($base)) { $this->setError(Lang::txt('Unable to create directory.')); return false; } } $fname = $base . DS . $this->get('filename', 'certificate.pdf'); // Get the number of images for our for-loop $im = new Imagick($fname); $num = $im->getNumberImages(); // Now actually do the image creation and cropping based on min margin for ($pages = 0; $pages < $num; ++$pages) { $im = new Imagick(); $im->setResolution(300, 300); $im->readImage($fname . '[' . $pages . ']'); $im->setImageFormat('png'); $im->setImageUnits(Imagick::RESOLUTION_PIXELSPERINCH); $im->writeImage($base . DS . ($pages + 1) . '.png'); } return true; } catch (ImagickException $ex) { // nothing $this->setError($ex->getMessage()); return false; } }
* @license http://opensource.org/licenses/MIT MIT */ // No direct access defined('_HZEXEC_') or die; $database = App::get('db'); $jt = new \Components\Jobs\Tables\JobType($database); $jc = new \Components\Jobs\Tables\JobCategory($database); $profile = \Hubzero\User\Profile::getInstance($this->seeker->uid); $jobtype = $jt->getType($this->seeker->sought_type, strtolower(Lang::txt('COM_JOBS_TYPE_ANY'))); $jobcat = $jc->getCat($this->seeker->sought_cid, strtolower(Lang::txt('COM_JOBS_CATEGORY_ANY'))); $title = Lang::txt('COM_JOBS_ACTION_DOWNLOAD') . ' ' . $this->seeker->name . ' ' . ucfirst(Lang::txt('COM_JOBS_RESUME')); // Get the configured upload path $base_path = DS . trim($this->params->get('webpath', '/site/members'), DS); $path = $base_path . DS . \Hubzero\Utility\String::pad($this->seeker->uid); if (!is_dir(PATH_APP . $path)) { if (!Filesystem::makeDirectory(PATH_APP . $path)) { $path = ''; } } $resume = is_file(PATH_APP . $path . DS . $this->seeker->filename) ? $path . DS . $this->seeker->filename : ''; ?> <div class="aboutme<?php echo $this->seeker->mine && $this->list ? ' mine' : ''; echo isset($this->seeker->shortlisted) && $this->seeker->shortlisted ? ' shortlisted' : ''; ?> "> <div class="thumb"> <img src="<?php echo $profile->getPicture(); ?> " alt="<?php
/** * Generate a receipt * * @return void */ public function receiptTask() { // Incoming $id = Request::getInt('id', 0); // Load the order $row = new Order($this->database); $row->load($id); // Instantiate an OrderItem object $oi = new OrderItem($this->database); if ($id) { // Get order items $orderitems = $oi->getOrderItems($id); if ($orderitems) { foreach ($orderitems as $r) { $params = new Registry($r->params); $selections = new Registry($r->selections); // Get size selection $r->sizes = $params->get('size', ''); $r->sizes = str_replace(' ', '', $r->sizes); $r->selectedsize = trim($selections->get('size', '')); $r->sizes = preg_split('/,/', $r->sizes); $r->sizeavail = in_array($r->selectedsize, $r->sizes) ? 1 : 0; // Get color selection $r->colors = $params->get('color', ''); $r->colors = str_replace(' ', '', $r->colors); $r->selectedcolor = trim($selections->get('color', '')); $r->colors = preg_split('/,/', $r->colors); } } else { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('Order empty, cannot generate receipt'), 'error'); return; } $customer = User::getInstance($row->uid); } else { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('Need order ID to issue a receipt'), 'error'); return; } // Include needed libraries // require_once(JPATH_COMPONENT . DS . 'helpers' . DS . 'receipt.pdf.php'); // Build the link displayed $sef = Route::url('index.php?option=' . $this->_option); if (substr($sef, 0, 1) == '/') { $sef = substr($sef, 1, strlen($sef)); } $webpath = str_replace('/administrator/', '/', Request::base() . $sef); $webpath = str_replace('//', '/', $webpath); if (isset($_SERVER['HTTPS'])) { $webpath = str_replace('http:', 'https:', $webpath); } if (!strstr($webpath, '://')) { $webpath = str_replace(':/', '://', $webpath); } //require_once(PATH_CORE . DS . 'libraries/tcpdf/tcpdf.php'); $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $receipt_title = $this->config->get('receipt_title') ? $this->config->get('receipt_title') : 'Your Order'; $hubaddress = array(); $hubaddress[] = $this->config->get('hubaddress_ln1') ? $this->config->get('hubaddress_ln1') : ''; $hubaddress[] = $this->config->get('hubaddress_ln2') ? $this->config->get('hubaddress_ln2') : ''; $hubaddress[] = $this->config->get('hubaddress_ln3') ? $this->config->get('hubaddress_ln3') : ''; $hubaddress[] = $this->config->get('hubaddress_ln4') ? $this->config->get('hubaddress_ln4') : ''; $hubaddress[] = $this->config->get('hubaddress_ln5') ? $this->config->get('hubaddress_ln5') : ''; $hubaddress[] = $this->config->get('hubemail') ? $this->config->get('hubemail') : ''; $hubaddress[] = $this->config->get('hubphone') ? $this->config->get('hubphone') : ''; $headertext_ln1 = $this->config->get('headertext_ln1') ? $this->config->get('headertext_ln1') : ''; $headertext_ln2 = $this->config->get('headertext_ln2') ? $this->config->get('headertext_ln2') : Config::get('sitename'); $footertext = $this->config->get('footertext') ? $this->config->get('footertext') : 'Thank you for contributions to our HUB!'; $receipt_note = $this->config->get('receipt_note') ? $this->config->get('receipt_note') : ''; // Get front-end template name $sql = "SELECT template FROM `#__template_styles` WHERE `client_id`=0 AND `home`=1"; $this->database->setQuery($sql); $tmpl = $this->database->loadResult(); // set default header data $pdf->SetHeaderData(NULL, 0, strtoupper($receipt_title) . ' - #' . $id, NULL, array(84, 94, 124), array(146, 152, 169)); $pdf->setFooterData(array(255, 255, 255), array(255, 255, 255)); // set header and footer fonts $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); // set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(10); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); // set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); // Set font $pdf->SetFont('dejavusans', '', 11, '', true); $pdf->AddPage(); // HTML content $this->view->setLayout('receipt'); $this->view->hubaddress = $hubaddress; $this->view->headertext_ln1 = $headertext_ln1; $this->view->headertext_ln2 = $headertext_ln2; $this->view->receipt_note = $receipt_note; $this->view->receipt_title = $receipt_title; $this->view->option = $this->_option; $this->view->url = $webpath; $this->view->customer = $customer; $this->view->row = $row; $this->view->orderitems = $orderitems; $html = $this->view->loadTemplate(); // output the HTML content $pdf->writeHTML($html, true, false, true, false, ''); // --------------------------------------------------------- $dir = PATH_APP . DS . 'site' . DS . 'store' . DS . 'temp'; $tempFile = $dir . DS . 'receipt_' . $id . '.pdf'; if (!is_dir($dir)) { if (!\Filesystem::makeDirectory($dir)) { throw new Exception(Lang::txt('Failed to create folder to store receipts'), 500); } } // Close and output PDF document $pdf->Output($tempFile, 'F'); if (is_file($tempFile)) { $xserver = new Server(); $xserver->filename($tempFile); $xserver->serve_inline($tempFile); exit; } else { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('There was an error creating a receipt'), 'error'); return; } return; }
/** * Save incoming * * @return boolean */ public function save($element, $elementId, $pub, $blockParams, $toAttach = array()) { // Incoming selections if (empty($toAttach)) { $selections = Request::getVar('selecteditems', ''); $toAttach = explode(',', $selections); } // Get configs $configs = $this->getConfigs($element, $elementId, $pub, $blockParams); // Cannot make changes if ($configs->freeze) { return false; } // Nothing to change if (empty($toAttach)) { return false; } // Create new version path if (!is_dir($configs->dataPath)) { if (!Filesystem::makeDirectory($configs->dataPath, 0755, true, true)) { $this->_parent->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_UNABLE_TO_CREATE_PATH')); return false; } } // Counters $i = 0; $a = 0; // Attach/refresh each selected item foreach ($toAttach as $identifier) { if (!trim($identifier)) { continue; } $a++; $ordering = $i + 1; if ($this->addAttachment($identifier, $pub, $configs, User::get('id'), $elementId, $element, $ordering)) { $i++; } } // Success if ($i > 0 && $i == $a) { $message = $this->get('_message') ? $this->get('_message') : Lang::txt('Selection successfully saved'); $this->set('_message', $message); } return true; }
/** * Upload a file or create a new folder * * @return void */ public function uploadTask() { // Check for request forgeries Request::checkToken(); // Incoming directory (this should be a path built from a resource ID and its creation year/month) $listdir = Request::getVar('listdir', '', 'post'); if (!$listdir) { $this->setError(Lang::txt('COM_RESOURCES_ERROR_NO_LISTDIR')); $this->displayTask(); return; } // Incoming sub-directory $subdir = Request::getVar('dirPath', '', 'post'); // Build the path $path = Utilities::buildUploadPath($listdir, $subdir); // Are we creating a new folder? $foldername = Request::getVar('foldername', '', 'post'); if ($foldername != '') { // Make sure the name is valid if (preg_match("/[^0-9a-zA-Z_]/i", $foldername)) { $this->setError(Lang::txt('COM_RESOURCES_ERROR_DIR_INVALID_CHARACTERS')); } else { if (!is_dir($path . DS . $foldername)) { if (!\Filesystem::makeDirectory($path . DS . $foldername)) { $this->setError(Lang::txt('COM_RESOURCES_ERROR_UNABLE_TO_CREATE_UPLOAD_PATH')); } } else { $this->setError(Lang::txt('COM_RESOURCES_ERROR_DIR_EXISTS')); } } // Directory created } else { // Make sure the upload path exist if (!is_dir($path)) { if (!\Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('COM_RESOURCES_ERROR_UNABLE_TO_CREATE_UPLOAD_PATH')); $this->displayTask(); return; } } // Incoming file $file = Request::getVar('upload', '', 'files', 'array'); if (!$file['name']) { $this->setError(Lang::txt('COM_RESOURCES_ERROR_NO_FILE')); $this->displayTask(); return; } // Make the filename safe $file['name'] = \Filesystem::clean($file['name']); // Ensure file names fit. $ext = \Filesystem::extension($file['name']); $file['name'] = str_replace(' ', '_', $file['name']); if (strlen($file['name']) > 230) { $file['name'] = substr($file['name'], 0, 230); $file['name'] .= '.' . $ext; } // Perform the upload if (!\Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('COM_RESOURCES_ERROR_UPLOADING')); } else { // File was uploaded // Was the file an archive that needs unzipping? $batch = Request::getInt('batch', 0, 'post'); if ($batch) { //build path $path = rtrim($path, DS) . DS; $escaped_file = escapeshellarg($path . $file['name']); //determine command to uncompress switch ($ext) { case 'gz': $cmd = "tar zxvf {$escaped_file} -C {$path}"; break; case 'tar': $cmd = "tar xvf {$escaped_file} -C {$path}"; break; case 'zip': default: $cmd = "unzip -o {$escaped_file} -d {$path}"; } //unzip file if ($result = shell_exec($cmd)) { // Remove original archive \Filesystem::delete($path . $file['name']); // Remove MACOSX dirs if there if (\Filesystem::exists($path . '__MACOSX')) { \Filesystem::deleteDirectory($path . '__MACOSX'); } //remove ._ files $dotFiles = \Filesystem::files($path, '._[^\\s]*', true, true); foreach ($dotFiles as $dotFile) { \Filesystem::delete($dotFile); } } } } } // Push through to the media view $this->displayTask(); }
/** * Method to create import filespace if needed * * @param object $import Models\Import * @return boolean */ private function _createImportFilespace(Models\Import $import) { // upload path $uploadPath = $import->fileSpacePath(); // if we dont have a filespace, create it if (!is_dir($uploadPath)) { \Filesystem::makeDirectory($uploadPath, 0775); } // all set return true; }
/** * Runs a rappture job. * * This is more than just invoking a tool. We're expecting a driver file to pass to the * tool to be picked up and automatically run by rappture. * * @apiMethod POST * @apiUri /tools/run * @apiParameter { * "name": "app", * "description": "Name of app installed as a tool in the hub", * "type": "string", * "required": true, * } * @apiParameter { * "name": "revision", * "description": "The specific requested revision of the app", * "type": "string", * "required": false, * "default": "default", * } * @apiParameter { * "name": "xml", * "description": "Content of the driver file that rappture will use to invoke the given app", * "type": "string", * "required": true, * } * @return void */ public function runTask() { $this->requiresAuthentication(); // Get the user_id and attempt to load user profile $userid = App::get('authn')['user_id']; $profile = User::getInstance($userid); // Make sure we have a user if (!$profile->get('id')) { throw new Exception(Lang::txt('Unable to find user.'), 404); } // Grab tool name and version $tool_name = Request::getVar('app', ''); $tool_version = Request::getVar('revision', 'default'); // Build application object $app = new stdClass(); $app->name = trim(str_replace(':', '-', $tool_name)); $app->version = $tool_version; $app->ip = $_SERVER["REMOTE_ADDR"]; // Check to make sure we have an app to invoke if (!$app->name) { throw new Exception(Lang::txt('A valid app name must be provided'), 404); } // Include needed tool libraries require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'version.php'; require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'session.php'; require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'viewperm.php'; // Create database object $database = \App::get('db'); // Load the tool version $tv = new \Components\Tools\Tables\Version($database); switch ($app->version) { case 1: case 'default': $app->name = $tv->getCurrentVersionProperty($app->name, 'instance'); break; case 'test': case 'dev': $app->name .= '_dev'; break; default: $app->name .= '_r' . $app->version; break; } $app->toolname = $app->name; if ($parent = $tv->getToolname($app->name)) { $app->toolname = $parent; } // Check of the toolname has a revision indicator $r = substr(strrchr($app->name, '_'), 1); if (substr($r, 0, 1) != 'r' && substr($r, 0, 3) != 'dev') { $r = ''; } // No version passed and no revision if ((!$app->version || $app->version == 'default') && !$r) { // Get the latest version $app->version = $tv->getCurrentVersionProperty($app->toolname, 'revision'); $app->name = $app->toolname . '_r' . $app->version; } // Get the caption/session title $tv->loadFromInstance($app->name); $app->caption = stripslashes($tv->title); $app->title = stripslashes($tv->title); // Make sure we have a valid tool if ($app->title == '' || $app->toolname == '') { throw new Exception(Lang::txt('The tool "%s" does not exist on the HUB.', $tool_name), 404); } // Get tool access $toolAccess = \Components\Tools\Helpers\Utils::getToolAccess($app->name, $profile->get('username')); // Do we have access if ($toolAccess->valid != 1) { throw new Exception($toolAccess->error->message, 500); } // Log the launch attempt \Components\Tools\Helpers\Utils::recordToolUsage($app->toolname, $profile->get('id')); // Get the middleware database $mwdb = \Components\Tools\Helpers\Utils::getMWDBO(); // Find out how many sessions the user is running $ms = new \Components\Tools\Tables\Session($mwdb); $jobs = $ms->getCount($profile->get('username')); // Find out how many sessions the user is ALLOWED to run. include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'preferences.php'; $preferences = new \Components\Tools\Tables\Preferences($database); $preferences->loadByUser($profile->get('id')); if (!$preferences || !$preferences->id) { $default = $preferences->find('one', array('alias' => 'default')); $preferences->user_id = $profile->get('id'); $preferences->class_id = $default->id; $preferences->jobs = $default->jobs; $preferences->store(); } $remain = $preferences->jobs - $jobs; //can we open another session if ($remain <= 0) { throw new Exception(Lang::txt('You are using all (%s) your available job slots.', $jobs), 401); } // Check for an incoming driver file if ($driver = Request::getVar('xml', false, 'post', 'none', 2)) { // Build a path to where the driver file will go through webdav $base = DS . 'webdav' . DS . 'home'; $user = DS . $profile->get('username'); $data = DS . 'data'; $drvr = DS . '.queued_drivers'; $inst = DS . md5(time()) . '.xml'; // Real home directory $homeDir = $profile->get('homeDirectory'); // First, make sure webdav is there and that the necessary folders are there if (!\Filesystem::exists($base)) { throw new Exception(Lang::txt('Home directories are unavailable'), 500); } // Now see if the user has a home directory yet if (!\Filesystem::exists($homeDir)) { // Try to create their home directory require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'utils.php'; if (!\Components\Tools\Helpers\Utils::createHomeDirectory($profile->get('username'))) { throw new Exception(Lang::txt('Failed to create user home directory'), 500); } } // Check for, and create if needed a session data directory if (!\Filesystem::exists($base . $user . $data) && !\Filesystem::makeDirectory($base . $user . $data, 0700)) { throw new Exception(Lang::txt('Failed to create data directory'), 500); } // Check for, and create if needed a queued drivers directory if (!\Filesystem::exists($base . $user . $data . $drvr) && !\Filesystem::makeDirectory($base . $user . $data . $drvr, 0700)) { throw new Exception(Lang::txt('Failed to create drivers directory'), 500); } // Write the driver file out if (!\Filesystem::write($base . $user . $data . $drvr . $inst, $driver)) { throw new Exception(Lang::txt('Failed to create driver file'), 500); } } else { throw new Exception(Lang::txt('No driver file provided'), 404); } // Now build params path that will be included with tool execution // We know from the checks above that this directory already exists $params = 'file(execute):' . $homeDir . DS . 'data' . DS . '.queued_drivers' . $inst; $encoded = ' params=' . rawurlencode($params) . ' '; $command = 'start user='******'username') . " ip={$app->ip} app={$app->name} version={$app->version}" . $encoded; $status = \Components\Tools\Helpers\Utils::middleware($command, $output); if (!$status) { throw new Exception(Lang::txt('Tool invocation failed'), 500); } $this->send(array('success' => true, 'session' => $output->session)); }
/** * Uploads a file to a given directory and returns an attachment string * that is appended to report/comment bodies * * @param string $listdir Directory to upload files to * @return string A string that gets appended to messages */ public function upload($listdir, $post_id) { // Check if they are logged in if (User::isGuest()) { return; } if (!$listdir) { $this->setError(Lang::txt('PLG_GROUPS_FORUM_NO_UPLOAD_DIRECTORY')); return; } // Incoming file $file = Request::getVar('upload', '', 'files', 'array'); if (!$file['name']) { return; } // Incoming $description = trim(Request::getVar('description', '')); // Construct our file path $path = PATH_APP . DS . trim($this->params->get('filepath', '/site/forum'), DS) . DS . $listdir; if ($post_id) { $path .= DS . $post_id; } // Build the path if it doesn't exist if (!is_dir($path)) { if (!Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('PLG_GROUPS_FORUM_UNABLE_TO_CREATE_UPLOAD_PATH')); return; } } // Make the filename safe $file['name'] = Filesystem::clean($file['name']); $file['name'] = str_replace(' ', '_', $file['name']); $ext = strtolower(Filesystem::extension($file['name'])); // Perform the upload if (!Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('PLG_GROUPS_FORUM_ERROR_UPLOADING')); return; } else { // File was uploaded // Create database entry $row = new \Components\Forum\Tables\Attachment($this->database); $row->bind(array('id' => 0, 'parent' => $listdir, 'post_id' => $post_id, 'filename' => $file['name'], 'description' => $description)); if (!$row->check()) { $this->setError($row->getError()); } if (!$row->store()) { $this->setError($row->getError()); } } }
/** * Save a billboard * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); // Incoming, make sure to allow HTML to pass through $data = Request::getVar('billboard', array(), 'post', 'array', JREQUEST_ALLOWHTML); // Create object $billboard = Billboard::oneOrNew($data['id'])->set($data); // Check to make sure collection exists $collection = Collection::oneOrNew($billboard->collection_id); if ($collection->isNew()) { $collection->set('name', 'Default Collection')->save(); $billboard->set('collection_id', $collection->id); } if (!$billboard->save()) { // Something went wrong...return errors foreach ($billboard->getErrors() as $error) { $this->view->setError($error); } $this->view->setLayout('edit'); $this->view->task = 'edit'; $this->editTask($billboard); return; } // See if we have an image coming in as well $billboard_image = Request::getVar('billboard-image', false, 'files', 'array'); // If so, proceed with saving the image if (isset($billboard_image['name']) && $billboard_image['name']) { // Build the upload path if it doesn't exist $image_location = $this->config->get('image_location', 'app' . DS . 'site' . DS . 'media' . DS . 'images' . DS . 'billboards'); $uploadDirectory = PATH_ROOT . DS . trim($image_location, DS) . DS; // Make sure upload directory exists and is writable if (!is_dir($uploadDirectory)) { if (!\Filesystem::makeDirectory($uploadDirectory)) { $this->view->setError(Lang::txt('COM_BILLBOARDS_ERROR_UNABLE_TO_CREATE_UPLOAD_PATH')); $this->view->setLayout('edit'); $this->view->task = 'edit'; $this->editTask($billboard); return; } } // Scan for viruses if (!\Filesystem::isSafe($billboard_image['tmp_name'])) { $this->view->setError(Lang::txt('COM_BILLBOARDS_ERROR_FAILED_VIRUS_SCAN')); $this->view->setLayout('edit'); $this->view->task = 'edit'; $this->editTask($billboard); return; } if (!move_uploaded_file($billboard_image['tmp_name'], $uploadDirectory . $billboard_image['name'])) { $this->view->setError(Lang::txt('COM_BILLBOARDS_ERROR_FILE_MOVE_FAILED')); $this->view->setLayout('edit'); $this->view->task = 'edit'; $this->editTask($billboard); return; } else { // Move successful, save the image url to the billboard entry $billboard->set('background_img', $billboard_image['name'])->save(); } } // Check in the billboard now that we've saved it $billboard->checkin(); // Redirect App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_BILLBOARDS_BILLBOARD_SUCCESSFULLY_SAVED')); }
/** * Log access * * @param string $type * * @return void */ public function logAccess($type = 'view') { // Only logging access for published if (!$this->isPublished()) { return false; } if (!isset($this->_tblLog)) { $this->_tblLog = new Tables\Log($this->_db); } // Build log path (access logs) $logPath = $this->path('logs'); // Create log directory if (!is_dir(PATH_APP . $logPath)) { Filesystem::makeDirectory(PATH_APP . $logPath, 0755, true, true); } $this->_tblLog->logAccess($this->get('id'), $this->get('version_id'), $type, $logPath); }
/** * Transfer files from one version to another * * @param string $sourceid Source version ID * @param string $destid Destination version ID * @param integer $rid Resource ID * @return boolean False if errors, True on success */ public function transfer($sourceid, $destid, $rid) { Log::debug(__FUNCTION__ . '()'); // Get resource information $resource = new \Components\Resources\Tables\Resource($this->database); $resource->load($rid); // Get screenshot information $ss = new \Components\Resources\Tables\Screenshot($this->database); $shots = $ss->getFiles($rid, $sourceid); // Build the path include_once PATH_CORE . DS . 'components' . DS . 'com_resources' . DS . 'helpers' . DS . 'html.php'; $listdir = \Components\Resources\Helpers\Html::build_path($resource->created, $rid, ''); $srcdir = $listdir . DS . $sourceid; $destdir = $listdir . DS . $destid; $src = $this->_buildUploadPath($srcdir, ''); $dest = $this->_buildUploadPath($destdir, ''); // Make sure the path exist if (!is_dir($src)) { if (!Filesystem::makeDirectory($src)) { $this->setError(Lang::txt('COM_TOOLS_UNABLE_TO_CREATE_UPLOAD_PATH')); return false; } } Log::debug(__FUNCTION__ . "() {$src}"); // do we have files to transfer? $files = Filesystem::files($src, '.', false, true, array()); Log::debug(__FUNCTION__ . "() " . implode(',', $files)); if (!empty($files)) { // Copy directory Log::debug(__FUNCTION__ . "() copying {$src} to {$dest}"); if (!Filesystem::copyDirectory($src, $dest, '', true)) { return false; } else { // Update screenshot information for this resource $ss->updateFiles($rid, $sourceid, $destid, $copy = 1); Log::debug(__FUNCTION__ . '() updated files'); return true; } } Log::debug(__FUNCTION__ . '() done'); return true; }
/** * Create group folder id doesnt exist * * @param [type] $path [description] * @return [type] [description] */ private function _createGroupFolder($path) { // create base group folder if (!Filesystem::exists($path)) { Filesystem::makeDirectory($path); } // create uploads file if (!Filesystem::exists($path . DS . 'uploads')) { Filesystem::makeDirectory($path . DS . 'uploads'); } }
/** * 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; }
/** * Upload file * * @param string $name * @param string $temp * @return bool */ public function upload($name, $temp) { $destination = $this->getUploadDir() . DS . $this->get('comment_id'); if (!is_dir($destination)) { if (!\Filesystem::makeDirectory($destination)) { $this->addError('Unable to create upload path.'); return false; } } $filename = $this->uniqueFilename(array('filename' => $name, 'comment_id' => $this->get('comment_id'))); $destination .= DS . $filename; if (!\Filesystem::upload($temp, $destination)) { $this->addError('Unable to upload file.'); return false; } $this->set('filename', $filename); return true; }
/** * Upload a file * * @param integer $listdir Wish ID * @return string */ public function uploadTask($listdir) { if (!$listdir) { $this->setError(Lang::txt('COM_WISHLIST_ERROR_NO_UPLOAD_DIRECTORY')); return ''; } // Incoming file $file = Request::getVar('upload', array(), 'files', 'array'); if (!isset($file['name']) || !$file['name']) { $this->setError(Lang::txt('COM_WISHLIST_ERROR_NO_FILE')); return ''; } // Make the filename safe $file['name'] = \Filesystem::clean($file['name']); $file['name'] = str_replace(' ', '_', $file['name']); //make sure that file is acceptable type $attachment = new Attachment(array('id' => 0, 'description' => Request::getVar('description', ''), 'wish' => $listdir, 'filename' => $file['name'])); // make sure that file is acceptable type if (!$attachment->isAllowedType()) { $this->setError(Lang::txt('ATTACHMENT: Incorrect file type.')); return Lang::txt('ATTACHMENT: Incorrect file type.'); } $path = $attachment->link('dir'); // Build the path if it doesn't exist if (!is_dir($path)) { if (!\Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('COM_WISHLIST_UNABLE_TO_CREATE_UPLOAD_PATH')); return 'ATTACHMENT: ' . Lang::txt('COM_WISHLIST_UNABLE_TO_CREATE_UPLOAD_PATH'); } } // Perform the upload if (!\Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('COM_WISHLIST_ERROR_UPLOADING')); return 'ATTACHMENT: ' . Lang::txt('COM_WISHLIST_ERROR_UPLOADING'); } else { // Scan for viruses $path = $path . DS . $file['name']; //PATH_CORE . DS . 'virustest'; if (!\Filesystem::isSafe($path)) { if (\Filesystem::delete($path)) { $this->setError(Lang::txt('ATTACHMENT: File rejected because the anti-virus scan failed.')); return Lang::txt('ATTACHMENT: File rejected because the anti-virus scan failed.'); } } if (!$attachment->store(true)) { $this->setError($attachment->getError()); } return '{attachment#' . $attachment->get('id') . '}'; } }
/** * Create method for this handler * * @return array of assets created **/ public function create() { // Include needed files require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'asset.association.php'; require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'asset.php'; require_once dirname(__DIR__) . DS . 'asset.php'; // Get the file if (isset($_FILES['files'])) { $file = $_FILES['files']['name'][0]; $size = (int) $_FILES['files']['size']; // Get the file extension $pathinfo = pathinfo($file); $filename = $pathinfo['filename']; $ext = $pathinfo['extension']; } else { return array('error' => 'No files provided'); } // @FIXME: should these come from the global settings, or should they be courses specific // Get config $config = Component::params('com_media'); // Max upload size $sizeLimit = (int) $config->get('upload_maxsize'); $sizeLimit = $sizeLimit * 1024 * 1024; // Check to make sure we have a file and its not too big if ($size == 0) { return array('error' => 'File is empty'); } if ($size > $sizeLimit) { $max = preg_replace('/<abbr \\w+=\\"\\w+\\">(\\w{1,3})<\\/abbr>/', '$1', \Hubzero\Utility\Number::formatBytes($sizeLimit)); return array('error' => "File is too large. Max file upload size is {$max}"); } // Create our asset table object $assetObj = new Tables\Asset($this->db); $this->asset['title'] = $filename; $this->asset['type'] = !empty($this->asset['type']) ? $this->asset['type'] : 'file'; $this->asset['subtype'] = !empty($this->asset['subtype']) ? $this->asset['subtype'] : 'file'; $this->asset['url'] = $file; $this->asset['created'] = Date::toSql(); $this->asset['created_by'] = App::get('authn')['user_id']; $this->asset['course_id'] = Request::getInt('course_id', 0); // Save the asset if (!$assetObj->save($this->asset)) { return array('error' => 'Asset save failed'); } // Create asset assoc object $assocObj = new Tables\AssetAssociation($this->db); $this->assoc['asset_id'] = $assetObj->get('id'); $this->assoc['scope'] = Request::getCmd('scope', 'asset_group'); $this->assoc['scope_id'] = Request::getInt('scope_id', 0); // Save the asset association if (!$assocObj->save($this->assoc)) { return array('error' => 'Asset association save failed'); } // Get courses config $cconfig = Component::params('com_courses'); // Build the upload path if it doesn't exist $uploadDirectory = PATH_APP . DS . trim($cconfig->get('uploadpath', '/site/courses'), DS) . DS . $this->asset['course_id'] . DS . $this->assoc['asset_id'] . DS; // Make sure upload directory exists and is writable if (!is_dir($uploadDirectory)) { if (!Filesystem::makeDirectory($uploadDirectory, 0755, true)) { return array('error' => 'Server error. Unable to create upload directory'); } } if (!is_writable($uploadDirectory)) { return array('error' => 'Server error. Upload directory isn\'t writable'); } // Get the final file path $target_path = $uploadDirectory . $filename . '.' . $ext; // Move the file to the site folder set_time_limit(60); // Scan for viruses if (!Filesystem::isSafe($_FILES['files']['tmp_name'][0])) { // Scan failed, delete asset and association and return an error $assetObj->delete(); $assocObj->delete(); Filesystem::deleteDirectory($uploadDirectory); return array('error' => 'File rejected because the anti-virus scan failed.'); } if (!($move = move_uploaded_file($_FILES['files']['tmp_name'][0], $target_path))) { // Move failed, delete asset and association and return an error $assetObj->delete(); $assocObj->delete(); Filesystem::deleteDirectory($uploadDirectory); return array('error' => 'Move file failed'); } // Get the url to return to the page $course_id = Request::getInt('course_id', 0); $offering_alias = Request::getCmd('offering', ''); $course = new \Components\Courses\Models\Course($course_id); $url = Route::url('index.php?option=com_courses&controller=offering&gid=' . $course->get('alias') . '&offering=' . $offering_alias . '&asset=' . $assetObj->get('id')); $url = rtrim(str_replace('/api', '', Request::root()), '/') . '/' . ltrim($url, '/'); $return_info = array('asset_id' => $this->assoc['asset_id'], 'asset_title' => $this->asset['title'], 'asset_type' => $this->asset['type'], 'asset_subtype' => $this->asset['subtype'], 'asset_url' => $url, 'course_id' => $this->asset['course_id'], 'offering_alias' => Request::getCmd('offering', ''), 'scope_id' => $this->assoc['scope_id'], 'asset_ext' => $ext, 'upload_path' => $uploadDirectory, 'target_path' => $target_path); // Return info return array('assets' => $return_info); }
/** * Upload a file to the wiki * * @return void */ public function _fileUpload() { // Check if they're logged in if (User::isGuest()) { return $this->_files(); } if (Request::getVar('no_html', 0)) { return $this->_ajaxUpload(); } // Check for request forgeries Request::checkToken(); // Ensure we have an ID to work with $listdir = Request::getInt('listdir', 0, 'post'); if (!$listdir) { $this->setError(Lang::txt('PLG_COURSES_PAGES_ERROR_NO_ID_PROVIDED')); return $this->_files(); } // Incoming file $file = Request::getVar('upload', '', 'files', 'array'); if (!$file['name']) { $this->setError(Lang::txt('PLG_COURSES_PAGES_ERROR_NO_FILE_PROVIDED')); return $this->_files(); } // Build the upload path if it doesn't exist $path = $this->_path(); if (!is_dir($path)) { if (!Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('PLG_COURSES_PAGES_ERROR_UNABLE_TO_MAKE_PATH')); return $this->_files(); } } // Make the filename safe $file['name'] = urldecode($file['name']); $file['name'] = Filesystem::clean($file['name']); $file['name'] = str_replace(' ', '_', $file['name']); // Upload new files if (!Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('PLG_COURSES_PAGES_ERROR_UNABLE_TO_UPLOAD')); } if (!Filesystem::isSafe($path . DS . $file['name'])) { Filesystem::delete($path . DS . $file['name']); $this->setError(Lang::txt('PLG_COURSES_PAGES_ERROR_UNSAFE_FILE')); } // Push through to the media view return $this->_files(); }
/** * 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(); }
/** * Download a citation for a publication * * @return void */ public function citationTask() { // Incoming $format = Request::getVar('type', 'bibtex'); // Get our model and load publication data $this->model = new Models\Publication($this->_identifier, $this->_version); // Make sure we got a result from the database if (!$this->model->exists() || $this->model->isDeleted()) { App::redirect(Route::url('index.php?option=' . $this->_option), Lang::txt('COM_PUBLICATIONS_RESOURCE_NOT_FOUND'), 'error'); return; } // Get version authors $authors = $this->model->table('Author')->getAuthors($this->model->version->get('id')); // Build publication path $path = $this->model->path('base', true); if (!is_dir($path)) { if (!Filesystem::makeDirectory(PATH_APP . $path, 0755, true, true)) { $this->setError('Error. Unable to create path.'); } } // Build the URL for this resource $sef = Route::url($this->model->link('version')); $url = Request::base() . ltrim($sef, '/'); // Choose the format switch ($format) { case 'endnote': $doc = "%0 " . Lang::txt('COM_PUBLICATIONS_GENERIC') . "\r\n"; $doc .= "%D " . Date::of($this->model->published())->toLocal('Y') . "\r\n"; $doc .= "%T " . trim(stripslashes($this->model->version->get('title'))) . "\r\n"; if ($authors) { foreach ($authors as $author) { $name = $author->name ? $author->name : $author->p_name; $auth = preg_replace('/{{(.*?)}}/s', '', $name); if (!strstr($auth, ',')) { $bits = explode(' ', $auth); $n = array_pop($bits) . ', '; $bits = array_map('trim', $bits); $auth = $n . trim(implode(' ', $bits)); } $doc .= "%A " . trim($auth) . "\r\n"; } } $doc .= "%U " . $url . "\r\n"; if ($this->model->published()) { $doc .= "%8 " . Date::of($this->model->published())->toLocal('M') . "\r\n"; } if ($this->model->version->get('doi')) { $doc .= "%1 " . 'doi:' . $this->model->version->get('doi'); $doc .= "\r\n"; } $file = 'publication' . $this->model->get('id') . '.enw'; $mime = 'application/x-endnote-refer'; break; case 'bibtex': default: include_once PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'BibTex.php'; $bibtex = new \Structures_BibTex(); $addarray = array(); $addarray['type'] = 'misc'; $addarray['cite'] = Config::get('sitename') . $this->model->get('id'); $addarray['title'] = stripslashes($this->model->version->get('title')); if ($authors) { $i = 0; foreach ($authors as $author) { $name = $author->name ? $author->name : $author->p_name; $author_arr = explode(',', $name); $author_arr = array_map('trim', $author_arr); $addarray['author'][$i]['first'] = isset($author_arr[1]) ? $author_arr[1] : ''; $addarray['author'][$i]['last'] = isset($author_arr[0]) ? $author_arr[0] : ''; $i++; } } $addarray['month'] = Date::of($this->model->published())->toLocal('M'); $addarray['url'] = $url; $addarray['year'] = Date::of($this->model->published())->toLocal('Y'); if ($this->model->version->get('doi')) { $addarray['doi'] = 'doi:' . DS . $this->model->version->get('doi'); } $bibtex->addEntry($addarray); $file = 'publication_' . $this->model->get('id') . '.bib'; $mime = 'application/x-bibtex'; $doc = $bibtex->bibTex(); break; } // Write the contents to a file $fp = fopen($path . DS . $file, "w") or die("can't open file"); fwrite($fp, $doc); fclose($fp); $this->_serveup(false, $path, $file, $mime); die; // REQUIRED }
/** * Get path to member dir (for provisioned projects) * * @return string */ public function getMembersPath() { // Get members config $mconfig = Component::params('com_members'); // Build upload path $dir = \Hubzero\Utility\String::pad($this->_uid); $path = DS . trim($mconfig->get('webpath', '/site/members'), DS) . DS . $dir . DS . 'files'; if (!is_dir(PATH_APP . $path)) { if (!Filesystem::makeDirectory(PATH_APP . $path, 0755, true, true)) { $this->setError(Lang::txt('UNABLE_TO_CREATE_UPLOAD_PATH')); return; } } return PATH_APP . $path; }
/** * Create local repo * * @return boolean */ public function iniLocal() { if ($this->get('path') && !is_dir($this->get('path'))) { if (!Filesystem::makeDirectory($this->get('path'), 0755, true, true)) { $this->setError(Lang::txt('COM_PROJECTS_FILES_ERROR_UNABLE_TO_CREATE_PATH')); return false; } } // Initialize $this->_adapter->ini(); return true; }