/** * 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(); }
/** * Checks if the file can be uploaded * * @param array File information * @param string An error message to be returned * @return boolean */ public static function canUpload($file, &$err) { $params = Component::params('com_media'); if (empty($file['name'])) { $err = 'COM_MEDIA_ERROR_UPLOAD_INPUT'; return false; } if ($file['name'] !== Filesystem::clean($file['name'])) { $err = 'COM_MEDIA_ERROR_WARNFILENAME'; return false; } $format = strtolower(Filesystem::extension($file['name'])); // Media file names should never have executable extensions buried in them. $executable = array('php', 'js', 'exe', 'phtml', 'java', 'perl', 'py', 'asp', 'dll', 'go', 'ade', 'adp', 'bat', 'chm', 'cmd', 'com', 'cpl', 'hta', 'ins', 'isp', 'jse', 'lib', 'mde', 'msc', 'msp', 'mst', 'pif', 'scr', 'sct', 'shb', 'sys', 'vb', 'vbe', 'vbs', 'vxd', 'wsc', 'wsf', 'wsh'); $explodedFileName = explode('.', $file['name']); if (count($explodedFileName > 2)) { foreach ($executable as $extensionName) { if (in_array($extensionName, $explodedFileName)) { $app->enqueueMessage(Lang::txt('JLIB_MEDIA_ERROR_WARNFILETYPE'), 'notice'); return false; } } } $allowable = explode(',', $params->get('upload_extensions')); $ignored = explode(',', $params->get('ignore_extensions')); if ($format == '' || $format == false || !in_array($format, $allowable) && !in_array($format, $ignored)) { $err = 'COM_MEDIA_ERROR_WARNFILETYPE'; return false; } $maxSize = (int) ($params->get('upload_maxsize', 0) * 1024 * 1024); if ($maxSize > 0 && (int) $file['size'] > $maxSize) { $err = 'COM_MEDIA_ERROR_WARNFILETOOLARGE'; return false; } $imginfo = null; if ($params->get('restrict_uploads', 1)) { $images = explode(',', $params->get('image_extensions')); if (in_array($format, $images)) { // if its an image run it through getimagesize // if tmp_name is empty, then the file was bigger than the PHP limit if (!empty($file['tmp_name'])) { if (($imginfo = getimagesize($file['tmp_name'])) === FALSE) { $err = 'COM_MEDIA_ERROR_WARNINVALID_IMG'; return false; } } else { $err = 'COM_MEDIA_ERROR_WARNFILETOOLARGE'; return false; } } elseif (!in_array($format, $ignored)) { // if its not an image...and we're not ignoring it $allowed_mime = explode(',', $params->get('upload_mime')); $illegal_mime = explode(',', $params->get('upload_mime_illegal')); if (function_exists('finfo_open') && $params->get('check_mime', 1)) { // We have fileinfo $finfo = finfo_open(FILEINFO_MIME); $type = finfo_file($finfo, $file['tmp_name']); if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) { $err = 'COM_MEDIA_ERROR_WARNINVALID_MIME'; return false; } finfo_close($finfo); } elseif (function_exists('mime_content_type') && $params->get('check_mime', 1)) { // we have mime magic $type = mime_content_type($file['tmp_name']); if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) { $err = 'COM_MEDIA_ERROR_WARNINVALID_MIME'; return false; } } elseif (!User::authorise('core.manage')) { $err = 'COM_MEDIA_ERROR_WARNNOTADMIN'; return false; } } } $xss_check = Filesystem::read($file['tmp_name'], false, 256); $html_tags = array('abbr', 'acronym', 'address', 'applet', 'area', 'audioscope', 'base', 'basefont', 'bdo', 'bgsound', 'big', 'blackface', 'blink', 'blockquote', 'body', 'bq', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'comment', 'custom', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'fn', 'font', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'html', 'iframe', 'ilayer', 'img', 'input', 'ins', 'isindex', 'keygen', 'kbd', 'label', 'layer', 'legend', 'li', 'limittext', 'link', 'listing', 'map', 'marquee', 'menu', 'meta', 'multicol', 'nobr', 'noembed', 'noframes', 'noscript', 'nosmartquotes', 'object', 'ol', 'optgroup', 'option', 'param', 'plaintext', 'pre', 'rt', 'ruby', 's', 'samp', 'script', 'select', 'server', 'shadow', 'sidebar', 'small', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'ul', 'var', 'wbr', 'xml', 'xmp', '!DOCTYPE', '!--'); foreach ($html_tags as $tag) { // A tag is '<tagname ', so we need to add < and a space or '<tagname>' if (stristr($xss_check, '<' . $tag . ' ') || stristr($xss_check, '<' . $tag . '>')) { $err = 'COM_MEDIA_ERROR_WARNIEXSS'; return false; } } return true; }
/** * 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') . '}'; } }
/** * Get remote folder content * * @param Google_DriveService $apiService Drive API service instance * @param string $folderID Folder ID * @param array $remotes Array of remote items * @param string $path Path * @param array $connections Array of local-remote connections * @param array &$duplicates Collector array for duplicates * * @return void */ public static function getFolderContent($apiService, $folderID = 0, $remotes, $path = '', $since, $connections, &$duplicates) { // Check for what we need if (!$apiService || !$folderID) { return false; } $conIds = $connections['ids']; $conPaths = $connections['paths']; // Search param $q = "'" . $folderID . "' in parents"; $parameters = array('q' => $q, 'fields' => 'items(id,title,mimeType,downloadUrl,md5Checksum,labels,fileSize,thumbnailLink,modifiedDate,parents/id,originalFilename,lastModifyingUserName,ownerNames)'); // Get a list of files in remote folder try { $data = $apiService->files->listFiles($parameters); if (!empty($data['items'])) { $lpath = $path ? $path : ''; foreach ($data['items'] as $item) { $time = strtotime($item['modifiedDate']); $status = $item['labels']['trashed'] ? 'D' : 'A'; $skip = 0; // Check against modified date $changed = strtotime(date("c", strtotime($item['modifiedDate']))) - strtotime($since); if ($since && $changed <= 0 && $item['labels']['trashed'] != 1) { $skip = 1; } $converted = preg_match("/google-apps/", $item['mimeType']) && !preg_match("/.folder/", $item['mimeType']) ? 1 : 0; $url = isset($item['downloadUrl']) ? $item['downloadUrl'] : ''; $original = isset($item['originalFilename']) ? $item['originalFilename'] : ''; $thumb = isset($item['thumbnailLink']) ? $item['thumbnailLink'] : NULL; $author = isset($item['lastModifyingUserName']) ? utf8_encode($item['lastModifyingUserName']) : utf8_encode($item['ownerNames'][0]); if (!preg_match("/.folder/", $item['mimeType'])) { $title = Filesystem::clean($item['title']); if ($converted) { $ext = self::getGoogleConversionFormat($item['mimeType'], false, true); if ($ext) { $title = $title . '.' . $ext; } } $type = 'file'; } else { $title = Filesystem::cleanPath($item['title']); $type = 'folder'; } $fpath = $lpath ? $lpath . DS . $title : $title; $synced = isset($conIds[$item['id']]) ? $conIds[$item['id']]['synced'] : NULL; $md5Checksum = isset($item['md5Checksum']) ? $item['md5Checksum'] : NULL; $fileSize = isset($item['fileSize']) ? $item['fileSize'] : NULL; /// Make sure path is not already used (Google allows files with same name in same dir, Git doesn't) $fpath = self::buildDuplicatePath($item['id'], $fpath, $item['mimeType'], $connections, $remotes, $duplicates); // Detect a rename or move $rename = ''; if (isset($conIds[$item['id']])) { $oFilePath = $conIds[$item['id']]['path']; $oDirPath = $conIds[$item['id']]['dirpath']; $nDirPath = dirname($fpath) == '.' ? '' : dirname($fpath); $nFilePath = $fpath; if ($oDirPath != $nDirPath && $oFilePath != $nFilePath) { $status = 'W'; $rename = $oFilePath; } elseif ($oFilePath != $nFilePath) { $status = 'R'; $rename = $oFilePath; } } // Check that file was last synced after modified date // (important to pick up failed updates) if (isset($conIds[$item['id']])) { if ($conIds[$item['id']]['modified'] < gmdate('Y-m-d H:i:s', $time)) { $skip = 0; } } elseif ($status == 'A') { // Never skip new files $skip = 0; } if (!$skip) { $remotes[$fpath] = array('status' => $status, 'time' => $time, 'modified' => gmdate('Y-m-d H:i:s', $time), 'type' => $type, 'local_path' => $fpath, 'remoteid' => $item['id'], 'title' => $item['title'], 'converted' => $converted, 'rParent' => self::getParentID($item['parents']), 'url' => $url, 'original' => $original, 'author' => $author, 'synced' => $synced, 'md5' => $md5Checksum, 'mimeType' => $item['mimeType'], 'thumb' => $thumb, 'rename' => $rename, 'fileSize' => $fileSize); } if (preg_match("/.folder/", $item['mimeType'])) { // Recurse $remotes = self::getFolderContent($apiService, $item['id'], $remotes, $fpath, $since, $connections, $duplicates); } } } } catch (Exception $e) { return $remotes; } return $remotes; }
/** * Upload a file via AJAX * * @return string */ public function ajaxUploadTask() { // Ensure we have an ID to work with $pid = strtolower(Request::getInt('pid', 0)); if (!$pid) { echo json_encode(array('error' => Lang::txt('COM_RESOURCES_NO_ID'))); return; } //max upload size $sizeLimit = $this->config->get('maxAllowed', 40000000); // get the file if (isset($_GET['qqfile']) && isset($_SERVER["CONTENT_LENGTH"])) { $stream = true; $file = $_GET['qqfile']; $size = (int) $_SERVER["CONTENT_LENGTH"]; } elseif (isset($_FILES['qqfile'])) { //$files = Request::getVar('qqfile', '', 'files', 'array'); $stream = false; $file = $_FILES['qqfile']['name']; $size = (int) $_FILES['qqfile']['size']; } else { echo json_encode(array('error' => Lang::txt('File not found'))); 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', Number::formatBytes($sizeLimit)); echo json_encode(array('error' => Lang::txt('File is too large. Max file upload size is %s', $max))); return; } // don't overwrite previous files that were uploaded $pathinfo = pathinfo($file); $filename = $pathinfo['filename']; // Make the filename safe $filename = urldecode($filename); $filename = \Filesystem::clean($filename); $filename = str_replace(' ', '_', $filename); $ext = $pathinfo['extension']; /*while (file_exists($path . DS . $filename . '.' . $ext)) { $filename .= rand(10, 99); }*/ // Instantiate a new resource object $resource = Resource::blank()->set(array('title' => $filename . '.' . $ext, 'introtext' => $filename . '.' . $ext, 'created' => Date::toSql(), 'created_by' => User::get('id'), 'published' => 1, 'publish_up' => Date::toSql(), 'publish_down' => '0000-00-00 00:00:00', 'standalone' => 0, 'access' => 0, 'path' => '', 'type' => $this->_getChildType($filename . '.' . $ext))); // Setup videos to auto-play in hub if ($this->config->get('file_video_html5', 1)) { if (in_array($ext, array('mp4', 'webm', 'ogv'))) { $resource->type = 41; // Video type } } // File already exists $parent = Resource::oneOrFail($pid); if ($parent->hasChild($filename)) { echo json_encode(array('error' => Lang::txt('A file with this name and type appears to already exist.'))); return; } // Store new content if (!$resource->save()) { echo json_encode(array('error' => $resource->getError())); return; } // Define upload directory and make sure its writable $path = $resource->filespace(); if (!is_dir($path)) { if (!Filesystem::makeDirectory($path)) { echo json_encode(array('error' => Lang::txt('Error uploading. Unable to create path.'))); return; } } if (!is_writable($path)) { echo json_encode(array('error' => Lang::txt('Server error. Upload directory isn\'t writable.'))); return; } $file = $path . DS . $filename . '.' . $ext; 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); } // Create new parent/child association if (!$resource->makeChildOf($pid)) { echo json_encode(array('success' => false, 'errors' => $resource->getErrors(), 'file' => $filename . '.' . $ext, 'directory' => '', 'parent' => $pid)); return; } // Virus scan if (!Filesystem::isSafe($file)) { if (Filesystem::delete($file)) { // Delete resource $resource->destroy(); } $this->setError(Lang::txt('File rejected because the anti-virus scan failed.')); echo json_encode(array('success' => false, 'errors' => $this->getErrors(), 'file' => $filename . '.' . $ext, 'directory' => str_replace(PATH_APP, '', $path), 'parent' => $pid)); return; } // Set the path if (!$resource->get('path')) { $resource->set('path', $resource->relativepath() . DS . $filename . '.' . $ext); } $resource->set('path', ltrim($resource->get('path'), DS)); $resource->save(); // Textifier $this->textifier($file, $resource->get('id')); // Output results echo json_encode(array('success' => true, 'errors' => $this->getErrors(), 'file' => $filename . '.' . $ext, 'directory' => str_replace(PATH_APP, '', $path), 'parent' => $pid)); }
/** * Upload a screenshot * * @return void */ public function uploadTask() { // Incoming $pid = Request::getInt('pid', 0); if (!$pid) { $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_NO_ID')); $this->displayTask($pid, $version); return; } $version = Request::getVar('version', 'dev'); $title = preg_replace('/\\s+/', ' ', Request::getVar('title', '')); $allowed = array('.gif', '.jpg', '.png', '.bmp'); $changing_version = Request::getInt('changing_version', 0); if ($changing_version) { // reload screen $this->displayTask($pid, $version); return; } // Get resource information $resource = new \Components\Resources\Tables\Resource($this->database); $resource->load($pid); // Incoming file $file = Request::getVar('upload', '', 'files', 'array'); if (!$file['name']) { $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_NO_FILE')); $this->displayTask($pid, $version); return; } // Make the filename safe $file['name'] = Filesystem::clean($file['name']); $file['name'] = str_replace(' ', '_', $file['name']); $file['name'] = str_replace('-tn', '', $file['name']); $file_basename = substr($file['name'], 0, strripos($file['name'], '.')); // strip extention $file_ext = substr($file['name'], strripos($file['name'], '.')); // Make sure we have an allowed format if (!in_array(strtolower($file_ext), $allowed)) { $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_WRONG_FILE_FORMAT')); $this->displayTask($pid, $version); return; } // Get version id $objV = new \Components\Tools\Tables\Version($this->database); $vid = $objV->getVersionIdFromResource($pid, $version); if ($vid == NULL) { $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_VERSION_ID_NOT_FOUND')); $this->displayTask($pid, $version); return; } // Instantiate a new screenshot object $row = new \Components\Resources\Tables\Screenshot($this->database); // Check if file with the same name already exists $files = $row->getFiles($pid, $vid); if (count($files) > 0) { $files = \Components\Tools\Helpers\Utils::transform($files, 'filename'); foreach ($files as $f) { if ($f == $file['name']) { // append extra characters in the end $file['name'] = $file_basename . '_' . time() . $file_ext; $file_basename = $file_basename . '_' . time(); } } } $row->title = preg_replace('/"((.)*?)"/i', "“\\1”", $title); $row->versionid = $vid; $ordering = $row->getLastOrdering($pid, $vid); $row->ordering = $ordering ? $ordering + 1 : count($files) + 1; // put in the end $row->filename = $file['name']; $row->resourceid = $pid; // Check content if (!$row->check()) { $this->setError($row->getError()); $this->displayTask($pid, $version); return; } // 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, $pid, ''); $listdir .= DS . $vid; $path = $this->_buildUploadPath($listdir, ''); // Make sure the upload path exist if (!is_dir($path)) { if (!Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('COM_TOOLS_UNABLE_TO_CREATE_UPLOAD_PATH') . $path); $this->displayTask($pid, $version); return; } } // Perform the upload if (!\Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('COM_TOOLS_ERROR_UPLOADING')); } else { // Store new content if (!$row->store()) { $this->setError($row->getError()); $this->displayTask($pid, $version); return; } if (!$row->id) { $row->id = $row->insertid(); } // Create thumbnail $ss_height = intval($this->config->get('screenshot_maxheight', 58)) > 30 ? intval($this->config->get('screenshot_maxheight', 58)) : 58; $ss_width = intval($this->config->get('screenshot_maxwidth', 91)) > 80 ? intval($this->config->get('screenshot_maxwidth', 91)) : 91; $tn = \Components\Resources\Helpers\Html::thumbnail($file['name']); if ($file_ext != '.swf') { $this->_createThumb($path . DS . $file['name'], $ss_width, $ss_height, $path, $tn); } else { //$this->_createAnimThumb($path . DS . $file['name'], $ss_width, $ss_height, $path, $tn); } } // Store new content if (!$row->store()) { $this->setError($row->getError()); $this->displayTask($pid, $version); return; } $this->_rid = $pid; // Push through to the screenshot view $this->displayTask($pid, $version); }
/** * 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(); }
/** * 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; }
/** * Add files to repo from extracted archive * * @return boolean */ protected function _addFromExtracted($extractPath, $zipName, $target, $params, &$available) { $reserved = isset($params['reserved']) ? $params['reserved'] : array(); $dirPath = isset($params['subdir']) ? $params['subdir'] : NULL; $extracted = Filesystem::files($extractPath, '.', true, true, $exclude = array('.svn', 'CVS', '.DS_Store', '__MACOSX')); $z = 0; foreach ($extracted as $e) { $fileinfo = pathinfo($e); $a_dir = $fileinfo['dirname']; $a_dir = str_replace($extractPath . DS, '', $a_dir); // Skip certain system files if (preg_match("/__MACOSX/", $e) or preg_match("/.DS_Store/", $e)) { continue; } $file = $fileinfo['basename']; $size = filesize($e); // Run some checks, stop in case of a problem if (!$this->_check($file, $e, $size, $available)) { return false; } // Clean up filename $safe_dir = $a_dir && $a_dir != '.' ? Filesystem::cleanPath($a_dir) : ''; $safe_dir = trim($safe_dir, DS); $safe_file = Filesystem::clean($file); $skipDir = false; if (is_array($reserved) && $safe_dir && in_array(strtolower($safe_dir), $reserved)) { $skipDir = true; } $safeName = $safe_dir && !$skipDir ? $safe_dir . DS . $safe_file : $safe_file; $localPath = $dirPath ? $dirPath . DS . $safeName : $safeName; $where = $target . DS . $safeName; $exists = is_file($where) ? true : false; // Provision directory if ($safe_dir && !$skipDir && !is_dir($target . DS . $safe_dir)) { if (Filesystem::makeDirectory($target . DS . $safe_dir, 0755, true, true)) { // File object $localDirPath = $dirPath ? $dirPath . DS . $safe_dir : $safe_dir; $fileObject = new Models\File(trim($localDirPath), $this->get('path')); $fileObject->set('type', 'folder'); $params['file'] = $fileObject; $params['replace'] = false; // Success - check in change $this->call('checkin', $params); $z++; } } // Copy file into project if (Filesystem::copy($e, $target . DS . $safeName)) { // File object $fileObject = new Models\File(trim($localPath), $this->get('path')); $params['file'] = $fileObject; $params['replace'] = $exists; // Success - check in change $this->call('checkin', $params); $z++; } } return $z; }
/** * Add files to repo from extracted archive * * @return boolean */ protected function _addFromExtracted($extractPath, $zipName, $target, $params, &$available) { $reserved = isset($params['reserved']) ? $params['reserved'] : array(); $dirPath = isset($params['subdir']) ? $params['subdir'] : NULL; $extracted = Filesystem::files($extractPath, '.', true, true, $exclude = array('.svn', 'CVS', '.DS_Store', '__MACOSX')); // check for viruses - scans the directory for efficency $command = "clamscan -i --no-summary --block-encrypted -r " . $extractPath; exec($command, $output, $virus_status); $virusChecked = FALSE; if ($virus_status == 0) { $virusChecked = TRUE; } else { Filesystem::deleteDirectory($extractPath); $this->setError('The antivirus software has rejected your files.'); return false; } $z = 0; foreach ($extracted as $e) { $fileinfo = pathinfo($e); $a_dir = $fileinfo['dirname']; $a_dir = str_replace($extractPath . DS, '', $a_dir); // Skip certain system files if (preg_match("/__MACOSX/", $e) or preg_match("/.DS_Store/", $e)) { continue; } $file = $fileinfo['basename']; $size = filesize($e); // Run some checks, stop in case of a problem if (!$this->_check($file, $e, $size, $available, $virusChecked)) { return false; } // Clean up filename $safe_dir = $a_dir && $a_dir != '.' ? Filesystem::cleanPath($a_dir) : ''; $safe_dir = trim($safe_dir, DS); $safe_file = Filesystem::clean($file); // Strips out temporary path if (strpos($safe_dir, 'tmp/') !== FALSE) { $parts = explode('/', $safe_dir); $safe_dir = str_replace($parts[0] . '/', '', $safe_dir); $safe_dir = str_replace($parts[1] . '/', '', $safe_dir); } $skipDir = false; if (is_array($reserved) && $safe_dir && in_array(strtolower($safe_dir), $reserved)) { $skipDir = true; } $safeName = $safe_dir && !$skipDir ? $safe_dir . DS . $safe_file : $safe_file; $localPath = $dirPath ? $dirPath . DS . $safeName : $safeName; $where = $target . DS . $safeName; $exists = is_file($where) ? true : false; // Provision directory if ($safe_dir && !$skipDir && !is_dir($target . DS . $safe_dir)) { if (Filesystem::makeDirectory($target . DS . $safe_dir, 0755, true, true)) { // File object $localDirPath = $dirPath ? $dirPath . DS . $safe_dir : $safe_dir; $fileObject = new Models\File(trim($localDirPath), $this->get('path')); $fileObject->set('type', 'folder'); $params['file'] = $fileObject; $params['replace'] = false; // Success - check in change $this->call('checkin', $params); $z++; } } // Strips out temporary path if (strpos($safeName, 'tmp/') !== FALSE) { $parts = explode('/', $safeName); $safeName = str_replace($parts[0] . '/', '', $safeName); $safeName = str_replace($parts[1] . '/', '', $safeName); } // Copy file into project if (Filesystem::copy($e, $target . DS . $safeName)) { // File object $fileObject = new Models\File(trim($localPath), $this->get('path')); $params['file'] = $fileObject; $params['replace'] = $exists; // Success - check in change $this->call('checkin', $params); $z++; } } return $z; }
/** * Upload a file * * @return void */ public function uploadTask() { if (Request::getVar('no_html', 0)) { return $this->ajaxUploadTask(); } // Check for request forgeries Request::checkToken(); // Incoming $id = Request::getInt('id', 0); if (!$id) { $this->setError(Lang::txt('COM_STOREFRONT_ERROR_NO_ID')); $this->displayTask('', $id); return; } // Build the path $type = strtolower(Request::getWord('type', '')); $path = $this->_path($type, $id); if (!$path) { $this->displayTask('', $id); return; } // Incoming file $file = Request::getVar('upload', '', 'files', 'array'); if (!$file['name']) { $this->setError(Lang::txt('COM_STOREFRONT_NO_FILE')); $this->displayTask('', $id); return; } $curfile = Request::getVar('curfile', ''); if (!is_dir($path)) { if (!Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('COM_STOREFRONT_ERROR_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']); // Perform the upload if (!Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('COM_STOREFRONT_ERROR_UPLOADING')); $file = $curfile; } else { if (!Filesystem::isSafe($path . DS . $file['name'])) { Filesystem::delete($path . DS . $file['name']); $this->setError(Lang::txt('COM_STOREFRONT_ERROR_FILE_UNSAFE')); $this->displayTask($curfile, $id); return; } // 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_COURSES_ERROR_UNABLE_TO_DELETE_FILE')); $this->displayTask($file['name'], $id); return; } } } switch ($type) { case 'product': // Instantiate a model, change some info and save $product = new Product($id); $product->setImage($file['name']); break; default: echo json_encode(array('error' => Lang::txt('COM_STOREFRONT_ERROR_INVALID_TYPE'))); return; break; } if (!$product->update()) { $this->setError('Error updating product'); } $file = $file['name']; } // Push through to the image view $this->displayTask($file, $id); }
/** * Deletes paths from the current path * * @since 1.5 */ public function delete() { Session::checkToken(['get', 'post']); // Get some data from the request $tmpl = Request::getCmd('tmpl'); $paths = Request::getVar('rm', array(), '', 'array'); $folder = Request::getVar('folder', '', '', 'path'); $redirect = 'index.php?option=com_media&folder=' . $folder; if ($tmpl == 'component') { // We are inside the iframe $redirect .= '&view=mediaList&tmpl=component'; } $this->setRedirect($redirect); // Nothing to delete if (empty($paths)) { return true; } // Authorize the user if (!$this->authoriseUser('delete')) { return false; } // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); // Initialise variables. $ret = true; foreach ($paths as $path) { if ($path !== Filesystem::clean($path)) { // filename is not safe $filename = htmlspecialchars($path, ENT_COMPAT, 'UTF-8'); Notify::warning(Lang::txt('COM_MEDIA_ERROR_UNABLE_TO_DELETE_FILE_WARNFILENAME', substr($filename, strlen(COM_MEDIA_BASE)))); continue; } $fullPath = Filesystem::cleanPath(implode(DIRECTORY_SEPARATOR, array(COM_MEDIA_BASE, $folder, $path))); $object_file = new \Hubzero\Base\Object(array('filepath' => $fullPath)); if (is_file($fullPath)) { // Trigger the onContentBeforeDelete event. $result = Event::trigger('content.onContentBeforeDelete', array('com_media.file', &$object_file)); if (in_array(false, $result, true)) { // There are some errors in the plugins Notify::warning(Lang::txts('COM_MEDIA_ERROR_BEFORE_DELETE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); continue; } $ret &= Filesystem::delete($fullPath); // Trigger the onContentAfterDelete event. Event::trigger('content.onContentAfterDelete', array('com_media.file', &$object_file)); $this->setMessage(Lang::txt('COM_MEDIA_DELETE_COMPLETE', substr($fullPath, strlen(COM_MEDIA_BASE)))); } elseif (is_dir($fullPath)) { $contents = Filesystem::files($fullPath, '.', true, false, array('.svn', 'CVS', '.DS_Store', '__MACOSX', 'index.html')); if (empty($contents)) { // Trigger the onContentBeforeDelete event. $result = Event::trigger('content.onContentBeforeDelete', array('com_media.folder', &$object_file)); if (in_array(false, $result, true)) { // There are some errors in the plugins Notify::warning(Lang::txts('COM_MEDIA_ERROR_BEFORE_DELETE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); continue; } $ret &= Filesystem::deleteDirectory($fullPath); // Trigger the onContentAfterDelete event. Event::trigger('content.onContentAfterDelete', array('com_media.folder', &$object_file)); $this->setMessage(Lang::txt('COM_MEDIA_DELETE_COMPLETE', substr($fullPath, strlen(COM_MEDIA_BASE)))); } else { // This makes no sense... Notify::warning(Lang::txt('COM_MEDIA_ERROR_UNABLE_TO_DELETE_FOLDER_NOT_EMPTY', substr($fullPath, strlen(COM_MEDIA_BASE)))); } } } return $ret; }
/** * Save an attachment * * @return void */ public function saveTask() { if (Request::getVar('no_html', 0)) { return $this->ajaxUploadTask(); } // Incoming $pid = Request::getInt('pid', 0); if (!$pid) { $this->setError(Lang::txt('CONTRIBUTE_NO_ID')); $this->displayTask($pid); return; } // Incoming file $file = Request::getVar('upload', '', 'files', 'array'); if (!$file['name']) { $this->setError(Lang::txt('CONTRIBUTE_NO_FILE')); $this->displayTask($pid); 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; } // Instantiate a new resource object $row = new Resource($this->database); if (!$row->bind($_POST)) { $this->setError($row->getError()); $this->displayTask($pid); return; } $row->title = $row->title ? $row->title : $file['name']; $row->introtext = $row->title; $row->created = Date::toSql(); $row->created_by = User::get('id'); $row->published = 1; $row->publish_up = Date::toSql(); $row->publish_down = '0000-00-00 00:00:00'; $row->standalone = 0; $row->path = ''; // make sure no path is specified just yet // Check content if (!$row->check()) { $this->setError($row->getError()); $this->displayTask($pid); return; } // File already exists if ($row->loadByFile($file['name'], $pid)) { $this->setError(Lang::txt('A file with this name and type appears to already exist.')); $this->displayTask($pid); return; } // Store new content if (!$row->store()) { $this->setError($row->getError()); $this->displayTask($pid); return; } if (!$row->id) { $row->id = $row->insertid(); } // Build the path $listdir = $this->_buildPathFromDate($row->created, $row->id, ''); $path = $this->_buildUploadPath($listdir, ''); // Make sure the upload path exist if (!is_dir($path)) { if (!\Filesystem::makeDirectory($path)) { $this->setError(Lang::txt('COM_CONTRIBUTE_UNABLE_TO_CREATE_UPLOAD_PATH')); $this->displayTask($pid); return; } } // Perform the upload if (!\Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('COM_CONTRIBUTE_ERROR_UPLOADING')); } else { // File was uploaded // Check the file type $row->type = $this->_getChildType($file['name']); // If it's a package (ZIP, etc) ... /* Breeze presentations haven't been used for some time. Completely unnecessary code? if ($row->type == 38) { require_once(PATH_CORE . DS . 'includes' . DS . 'pcl' . DS . 'pclzip.lib.php'); if (!extension_loaded('zlib')) { $this->setError(Lang::txt('COM_CONTRIBUTE_ZLIB_PACKAGE_REQUIRED')); } else { // Check the table of contents and look for a Breeze viewer.swf file $isbreeze = 0; $zip = new PclZip($path . DS . $file['name']); $file_to_unzip = preg_replace('/(.+)\..*$/', '$1', $path . DS . $file['name']); if (($list = $zip->listContent()) == 0) { die('Error: '.$zip->errorInfo(true)); } for ($i=0; $i<sizeof($list); $i++) { if (substr($list[$i]['filename'], strlen($list[$i]['filename']) - 10, strlen($list[$i]['filename'])) == 'viewer.swf') { $isbreeze = $list[$i]['filename']; break; } //$this->setError(substr($list[$i]['filename'], strlen($list[$i]['filename']), -4).' '.substr($file['name'], strlen($file['name']), -4)); } if (!$isbreeze) { for ($i=0; $i<sizeof($list); $i++) { if (strtolower(substr($list[$i]['filename'], -3)) == 'swf' && substr($list[$i]['filename'], strlen($list[$i]['filename']), -4) == substr($file['name'], strlen($file['name']), -4)) { $isbreeze = $list[$i]['filename']; break; } //$this->setError(substr($list[$i]['filename'], strlen($list[$i]['filename']), -4).' '.substr($file['name'], strlen($file['name']), -4)); } } // It IS a breeze presentation if ($isbreeze) { // unzip the file $do = $zip->extract($path); if (!$do) { $this->setError(Lang::txt('COM_CONTRIBUTE_UNABLE_TO_EXTRACT_PACKAGE')); } else { $row->path = $listdir . DS . $isbreeze; @unlink($path . DS . $file['name']); } $row->type = $this->_getChildType($row->path); $row->title = $isbreeze; } } }*/ } // Scan for viruses $fpath = $path . DS . $file['name']; if (!\Filesystem::isSafe($fpath)) { if (\Filesystem::delete($fpath)) { // Delete associations to the resource $row->deleteExistence(); // Delete resource $row->delete(); } $this->setError(Lang::txt('File rejected because the anti-virus scan failed.')); $this->displayTask($pid); return; } if (!$row->path) { $row->path = $listdir . DS . $file['name']; } $row->path = ltrim($row->path, DS); // Store new content if (!$row->store()) { $this->setError($row->getError()); $this->displayTask($pid); return; } // Instantiate a Resources Assoc object $assoc = new Assoc($this->database); // Get the last child in the ordering $assoc->ordering = $assoc->getLastOrder($pid); $assoc->ordering = $assoc->ordering ? $assoc->ordering : 0; // Increase the ordering - new items are always last $assoc->ordering++; // Create new parent/child association $assoc->parent_id = $pid; $assoc->child_id = $row->id; $assoc->grouping = 0; if (!$assoc->check()) { $this->setError($assoc->getError()); } if (!$assoc->store(true)) { $this->setError($assoc->getError()); } else { if (is_readable($path . DS . $file['name'])) { $hash = @sha1_file($path . DS . $file['name']); if (!empty($hash)) { $this->database->setQuery('SELECT id FROM `#__document_text_data` WHERE hash = \'' . $hash . '\''); if (!($doc_id = $this->database->loadResult())) { $this->database->execute('INSERT INTO `#__document_text_data` (hash) VALUES (\'' . $hash . '\')'); $doc_id = $this->database->insertId(); } $this->database->execute('INSERT IGNORE INTO `#__document_resource_rel` (document_id, resource_id) VALUES (' . (int) $doc_id . ', ' . (int) $row->id . ')'); system('/usr/bin/textifier ' . escapeshellarg($path . DS . $file['name']) . ' >/dev/null'); } } } // Push through to the attachments view $this->displayTask($pid); }
/** * 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()); } } }
/** * 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); }
/** * Upload a file * * @since 1.5 */ function upload() { $params = Component::params('com_media'); // Check for request forgeries if (!Session::checkToken(['get', 'post'], true)) { $response = array('status' => '0', 'error' => Lang::txt('JINVALID_TOKEN')); echo json_encode($response); return; } // Get the user $log = JLog::getInstance('upload.error.php'); // Get some data from the request $file = Request::getVar('Filedata', '', 'files', 'array'); $folder = Request::getVar('folder', '', '', 'path'); $return = Request::getVar('return-url', null, 'post', 'base64'); if ($_SERVER['CONTENT_LENGTH'] > $params->get('upload_maxsize', 0) * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('upload_max_filesize') * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('post_max_size') * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('memory_limit') * 1024 * 1024) { $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_WARNFILETOOLARGE')); echo json_encode($response); return; } // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe $file['name'] = Filesystem::clean($file['name']); if (isset($file['name'])) { // The request is valid $err = null; $filepath = \Hubzero\Filesystem\Util::normalizePath(COM_MEDIA_BASE . '/' . $folder . '/' . strtolower($file['name'])); if (!MediaHelper::canUpload($file, $err)) { $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err)); $response = array('status' => '0', 'error' => Lang::txt($err)); echo json_encode($response); return; } // Trigger the onContentBeforeSave event. $object_file = new \Hubzero\Base\Object($file); $object_file->filepath = $filepath; $result = Event::trigger('content.onContentBeforeSave', array('com_media.file', &$object_file, true)); if (in_array(false, $result, true)) { // There are some errors in the plugins $log->addEntry(array('comment' => 'Errors before save: ' . $filepath . ' : ' . implode(', ', $object_file->getErrors()))); $response = array('status' => '0', 'error' => Lang::txts('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); echo json_encode($response); return; } if (Filesystem::exists($filepath)) { // File exists $log->addEntry(array('comment' => 'File exists: ' . $filepath . ' by user_id ' . User::get('id'))); $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_FILE_EXISTS')); echo json_encode($response); return; } elseif (!User::authorise('core.create', 'com_media')) { // File does not exist and user is not authorised to create $log->addEntry(array('comment' => 'Create not permitted: ' . $filepath . ' by user_id ' . User::get('id'))); $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_CREATE_NOT_PERMITTED')); echo json_encode($response); return; } $file = (array) $object_file; if (!Filesystem::upload($file['tmp_name'], $file['filepath'])) { // Error in upload $log->addEntry(array('comment' => 'Error on upload: ' . $filepath)); $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')); echo json_encode($response); return; } else { // Trigger the onContentAfterSave event. Event::trigger('content.onContentAfterSave', array('com_media.file', &$object_file, true)); $log->addEntry(array('comment' => $folder)); $response = array('status' => '1', 'error' => Lang::txt('COM_MEDIA_UPLOAD_COMPLETE', substr($file['filepath'], strlen(COM_MEDIA_BASE)))); echo json_encode($response); return; } } else { $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_BAD_REQUEST')); echo json_encode($response); return; } }
/** * Download a wiki file * * @return void */ public function downloadTask() { // Get some needed libraries if (!$this->course->access('view')) { return App::abort(404, Lang::txt('COM_COURSES_NO_COURSE_FOUND')); } // Get the scope of the parent page the file is attached to $filename = Request::getVar('file', ''); if (substr(strtolower($filename), 0, strlen('image:')) == 'image:') { $filename = substr($filename, strlen('image:')); } else { if (substr(strtolower($filename), 0, strlen('file:')) == 'file:') { $filename = substr($filename, strlen('file:')); } } $filename = urldecode($filename); $filename = \Filesystem::clean($filename); $filename = str_replace(' ', '_', $filename); // Get the configured upload path $base_path = DS . trim($this->config->get('filepath', '/site/courses'), DS) . DS . $this->course->get('id') . DS . 'pagefiles'; // Does the path start with a slash? $filename = DS . ltrim($filename, DS); // Does the beginning of the $attachment->path match the config path? if (substr($filename, 0, strlen($base_path)) == $base_path) { // Yes - this means the full path got saved at some point } else { // No - append it $filename = $base_path . $filename; } // Add PATH_CORE $filepath = PATH_APP . $filename; // Ensure the file exist if (!file_exists($filepath)) { return App::abort(404, Lang::txt('COM_COURSES_FILE_NOT_FOUND') . ' ' . $filename); } // Initiate a new content server and serve up the file $xserver = new Server(); $xserver->filename($filepath); $xserver->disposition('inline'); $xserver->acceptranges(false); // @TODO fix byte range support if (!$xserver->serve()) { // Should only get here on error throw new Exception(Lang::txt('COM_COURSES_SERVER_ERROR'), 500); } else { exit; } return; }
/** * Upload a resume * * @param object $database Database * @param string $option Component name * @param object $member Profile * @return string */ protected function _upload($database, $option, $member) { $path = $this->build_path($member->get('id')); $emp = Request::getInt('emp', 0); if (!$path) { $this->setError(Lang::txt('PLG_MEMBERS_RESUME_SUPPORT_NO_UPLOAD_DIRECTORY')); return $this->_view($database, $option, $member, $emp); } // Check for request forgeries Request::checkToken(['get', 'post']); // Incoming file $file = Request::getVar('uploadres', '', 'files', 'array'); if (!$file['name']) { $this->setError(Lang::txt('PLG_MEMBERS_RESUME_SUPPORT_NO_FILE')); return $this->_view($database, $option, $member, $emp); } // Incoming $title = Request::getVar('title', ''); $default_title = $member->get('firstname') ? $member->get('firstname') . ' ' . $member->get('lastname') . ' ' . ucfirst(Lang::txt('PLG_MEMBERS_RESUME_RESUME')) : $member->get('name') . ' ' . ucfirst(Lang::txt('PLG_MEMBERS_RESUME_RESUME')); $path = PATH_APP . $path; // Replace file title with user name $file_ext = substr($file['name'], strripos($file['name'], '.')); $file['name'] = $member->get('firstname') ? $member->get('firstname') . ' ' . $member->get('lastname') . ' ' . ucfirst(Lang::txt('PLG_MEMBERS_RESUME_RESUME')) : $member->get('name') . ' ' . ucfirst(Lang::txt('PLG_MEMBERS_RESUME_RESUME')); $file['name'] .= $file_ext; // Make the filename safe $file['name'] = Filesystem::clean($file['name']); $file['name'] = str_replace(' ', '_', $file['name']); $ext = strtolower(Filesystem::extension($file['name'])); if (!in_array($ext, explode(',', $this->params->get('file_ext', 'jpg,jpeg,jpe,bmp,tif,tiff,png,gif,pdf,txt,rtf,doc,docx,ppt')))) { $this->setError(Lang::txt('Disallowed file type.')); return $this->_view($database, $option, $member, $emp); } $row = new \Components\Jobs\Tables\Resume($database); if (!$row->loadResume($member->get('id'))) { $row = new \Components\Jobs\Tables\Resume($database); $row->id = 0; $row->uid = $member->get('id'); $row->main = 1; } else { if (file_exists($path . DS . $row->filename)) { Filesystem::delete($path . DS . $row->filename); // Remove stats for prev resume $jobstats = new \Components\Jobs\Tables\JobStats($database); $jobstats->deleteStats($member->get('id'), 'seeker'); } } // Perform the upload if (!Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) { $this->setError(Lang::txt('ERROR_UPLOADING')); } else { $fpath = $path . DS . $file['name']; if (!Filesystem::isSafe($fpath)) { Filesystem::delete($fpath); $this->setError(Lang::txt('File rejected because the anti-virus scan failed.')); return $this->_view($database, $option, $member, $emp); } // File was uploaded, create database entry $title = htmlspecialchars($title); $row->created = Date::toSql(); $row->filename = $file['name']; $row->title = $title ? $title : $default_title; if (!$row->check()) { $this->setError($row->getError()); } if (!$row->store()) { $this->setError($row->getError()); } } return $this->_view($database, $option, $member, $emp); }
/** * Download a wiki file * * @return void */ public function _fileDownload() { if (!$this->view->course->access('view')) { return App::abort(404, Lang::txt('COM_COURSES_NO_COURSE_FOUND')); } // Get the scope of the parent page the file is attached to $filename = Request::getVar('group', ''); if (substr(strtolower($filename), 0, strlen('image:')) == 'image:') { $filename = substr($filename, strlen('image:')); } else { if (substr(strtolower($filename), 0, strlen('file:')) == 'file:') { $filename = substr($filename, strlen('file:')); } } $filename = urldecode($filename); $filename = Filesystem::clean($filename); $filename = str_replace(' ', '_', $filename); // Ensure we have a path if (empty($filename)) { return App::abort(404, Lang::txt('COM_COURSES_FILE_NOT_FOUND') . $filename); } $page = $this->view->offering->page(Request::getVar('unit', '')); if (!$page->exists()) { $pages = $this->view->offering->pages(array('url' => Request::getVar('unit', ''), 'offering_id' => array(0, $this->view->offering->get('id')), 'section_id' => array(0, $this->view->offering->section()->get('id')), 'limit' => 1, 'start' => 0), true); $page = isset($pages[0]) ? $pages[0] : null; } // Add PATH_CORE $filepath = $this->_path($page) . DS . ltrim($filename, DS); // Ensure the file exist $found = true; if (!file_exists($filepath)) { if (!$page) { Request::setVar('section_id', $this->view->offering->section()->get('id')); $filepath = $this->_path($page) . DS . ltrim($filename, DS); if (!file_exists($filepath)) { $found = false; } } else { $found = false; } if (!$found) { return App::abort(404, Lang::txt('COM_COURSES_FILE_NOT_FOUND') . $filename); } } // Initiate a new content server and serve up the file $xserver = new \Hubzero\Content\Server(); $xserver->filename($filepath); $xserver->disposition('inline'); $xserver->acceptranges(false); // @TODO fix byte range support if (!$xserver->serve()) { // Should only get here on error return App::abort(404, Lang::txt('COM_COURSES_SERVER_ERROR')); } else { exit; } }