/** * Build browsable list of files * * @return array */ public function getFolders() { if (!empty($this->folders)) { return $this->folders; } $currentFolder = $this->getCurrentFolder(); if (!file_exists($currentFolder)) { return $this->folders; } $folderList = JFolder::folders($currentFolder); $mediaHelper = new JHelperMedia(); // Iterate over the folders if they exist if ($folderList !== false) { foreach ($folderList as $folder) { $tmp = new JObject(); $tmp->name = basename($folder); $tmp->path = str_replace(DIRECTORY_SEPARATOR, '/', JPath::clean($currentFolder . '/' . $folder)); $tmp->path_relative = str_replace($currentFolder, '', $tmp->path); $tmp->count = $mediaHelper->countFiles($tmp->path); $tmp->files = $tmp->count[0]; $tmp->folders = $tmp->count[1]; $this->folders[] = $tmp; } } return $this->folders; }
/** * Checks if the uploaded files are valid. * * @param array $files Array containing the uploaded files. * * @return bool True if all files are valid, false if not. */ public function canUpload($files) { foreach ($files as $file) { $helper = new JHelperMedia(); if (!$helper->canUpload($file[0], 'com_monitor')) { return false; } } return true; }
/** * Counts the files and directories in a directory that are not php or html files. * * @param string $dir Directory name * * @return array The number of files and directories in the given directory * * @since 1.5 * @deprecated 4.0 Use JHelperMedia::countFiles instead */ public static function countFiles($dir) { JLog::add('MediaHelper::countFiles() is deprecated. Use JHelperMedia::countFiles() instead.', JLog::WARNING, 'deprecated'); $mediaHelper = new JHelperMedia(); return $mediaHelper->countFiles($dir); }
private function upload_image() { $input = JFactory::getApplication()->input; $image = $input->files->get('image'); $imageonly = $input->post->get('imageonly', false, 'BOOLEAN'); $tplRegistry = new JRegistry(); $tplParams = $tplRegistry->loadString(self::getTemplate()->params); $report = array(); // User is not authorised if (!JFactory::getUser()->authorise('core.create', 'com_media')) { $report['status'] = false; $report['output'] = JText::_('You are not authorised to upload file.'); echo json_encode($report); die; } if (count($image)) { if ($image['error'] == UPLOAD_ERR_OK) { $error = false; $params = JComponentHelper::getParams('com_media'); // Total length of post back data in bytes. $contentLength = (int) $_SERVER['CONTENT_LENGTH']; // Instantiate the media helper $mediaHelper = new JHelperMedia(); // Maximum allowed size of post back data in MB. $postMaxSize = $mediaHelper->toBytes(ini_get('post_max_size')); // Maximum allowed size of script execution in MB. $memoryLimit = $mediaHelper->toBytes(ini_get('memory_limit')); // Check for the total size of post back data. if ($postMaxSize > 0 && $contentLength > $postMaxSize || $memoryLimit != -1 && $contentLength > $memoryLimit) { $report['status'] = false; $report['output'] = JText::_('Total size of upload exceeds the limit.'); $error = true; echo json_encode($report); die; } $uploadMaxSize = $params->get('upload_maxsize', 0) * 1024 * 1024; $uploadMaxFileSize = $mediaHelper->toBytes(ini_get('upload_max_filesize')); if ($image['error'] == 1 || $uploadMaxSize > 0 && $image['size'] > $uploadMaxSize || $uploadMaxFileSize > 0 && $image['size'] > $uploadMaxFileSize) { $report['status'] = false; $report['output'] = JText::_('This file is too large to upload.'); $error = true; } // Upload if no error found if (!$error) { // Organised folder structure $date = JFactory::getDate(); $folder = JHtml::_('date', $date, 'Y') . '/' . JHtml::_('date', $date, 'm') . '/' . JHtml::_('date', $date, 'd'); if (!file_exists(JPATH_ROOT . '/images/' . $folder)) { JFolder::create(JPATH_ROOT . '/images/' . $folder, 0755); } $name = $image['name']; $path = $image['tmp_name']; // Do no override existing file $file = pathinfo($name); $i = 0; do { $base_name = $file['filename'] . ($i ? "{$i}" : ""); $ext = $file['extension']; $image_name = $base_name . "." . $ext; $i++; $dest = JPATH_ROOT . '/images/' . $folder . '/' . $image_name; $src = 'images/' . $folder . '/' . $image_name; $data_src = 'images/' . $folder . '/' . $image_name; } while (file_exists($dest)); // End Do not override if (JFile::upload($path, $dest)) { $sizes = array(); if ($tplParams->get('image_small', 0)) { $sizes['small'] = strtolower($tplParams->get('image_small_size', '100X100')); } if ($tplParams->get('image_thumbnail', 1)) { $sizes['thumbnail'] = strtolower($tplParams->get('image_thumbnail_size', '200X200')); } if ($tplParams->get('image_medium', 0)) { $sizes['medium'] = strtolower($tplParams->get('image_medium_size', '300X300')); } if ($tplParams->get('image_large', 0)) { $sizes['large'] = strtolower($tplParams->get('image_large_size', '600X600')); } if (count($sizes)) { $image = new Helix3Image($dest); $image->createThumbs($sizes, 5); } if (file_exists(JPATH_ROOT . '/images/' . $folder . '/' . $base_name . '_thumbnail.' . $ext)) { $src = 'images/' . $folder . '/' . $base_name . '_thumbnail.' . $ext; } $report['status'] = true; if ($imageonly) { $report['output'] = '<img src="' . JURI::root(true) . '/' . $src . '" data-src="' . $data_src . '" alt="">'; } else { $report['output'] = '<li data-src="' . $data_src . '"><a href="#" class="btn btn-mini btn-danger btn-remove-image">Delete</a><img src="' . JURI::root(true) . '/' . $src . '" alt=""></li>'; } } } } } else { $report['status'] = false; $report['output'] = JText::_('Upload Failed!'); } echo json_encode($report); die; }
/** * Upload a file * * @return void * * @since 1.5 */ function upload() { $params = JComponentHelper::getParams('com_media'); // Check for request forgeries if (!JSession::checkToken('request')) { $response = array('status' => '0', 'error' => JText::_('JINVALID_TOKEN')); echo json_encode($response); return; } // Get the user $user = JFactory::getUser(); JLog::addLogger(array('text_file' => 'upload.error.php'), JLog::ALL, array('upload')); // Get some data from the request $file = $this->input->files->get('Filedata', '', 'array'); $folder = $this->input->get('folder', '', 'path'); // Instantiate the media helper $mediaHelper = new JHelperMedia(); if ($_SERVER['CONTENT_LENGTH'] > $params->get('upload_maxsize', 0) * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > $mediaHelper->toBytes(ini_get('upload_max_filesize')) || $_SERVER['CONTENT_LENGTH'] > $mediaHelper->toBytes(ini_get('post_max_size')) || $_SERVER['CONTENT_LENGTH'] > $mediaHelper->toBytes(ini_get('memory_limit'))) { $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE')); echo json_encode($response); return; } // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe $file['name'] = JFile::makeSafe($file['name']); if (isset($file['name'])) { // The request is valid $err = null; $filepath = JPath::clean(COM_MEDIA_BASE . '/' . $folder . '/' . strtolower($file['name'])); if (!MediaHelper::canUpload($file, $err)) { JLog::add('Invalid: ' . $filepath . ': ' . $err, JLog::INFO, 'upload'); $response = array('status' => '0', 'error' => JText::_($err)); echo json_encode($response); return; } // Trigger the onContentBeforeSave event. JPluginHelper::importPlugin('content'); $dispatcher = JEventDispatcher::getInstance(); $object_file = new JObject($file); $object_file->filepath = $filepath; $result = $dispatcher->trigger('onContentBeforeSave', array('com_media.file', &$object_file, true)); if (in_array(false, $result, true)) { // There are some errors in the plugins JLog::add('Errors before save: ' . $object_file->filepath . ' : ' . implode(', ', $object_file->getErrors()), JLog::INFO, 'upload'); $response = array('status' => '0', 'error' => JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); echo json_encode($response); return; } if (JFile::exists($object_file->filepath)) { // File exists JLog::add('File exists: ' . $object_file->filepath . ' by user_id ' . $user->id, JLog::INFO, 'upload'); $response = array('status' => '0', 'error' => JText::_('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 JLog::add('Create not permitted: ' . $object_file->filepath . ' by user_id ' . $user->id, JLog::INFO, 'upload'); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_CREATE_NOT_PERMITTED')); echo json_encode($response); return; } if (!JFile::upload($object_file->tmp_name, $object_file->filepath)) { // Error in upload JLog::add('Error on upload: ' . $object_file->filepath, JLog::INFO, 'upload'); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')); echo json_encode($response); return; } else { // Trigger the onContentAfterSave event. $dispatcher->trigger('onContentAfterSave', array('com_media.file', &$object_file, true)); JLog::add($folder, JLog::INFO, 'upload'); $response = array('status' => '1', 'error' => JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', substr($object_file->filepath, strlen(COM_MEDIA_BASE)))); echo json_encode($response); return; } } else { $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_BAD_REQUEST')); echo json_encode($response); return; } }
/** * Upload one or more files * * @return boolean * * @since 1.5 */ public function upload() { // Check for request forgeries JSession::checkToken('request') or jexit(JText::_('JINVALID_TOKEN')); $params = JComponentHelper::getParams('com_media'); // Get some data from the request $files = $this->input->files->get('Filedata', '', 'array'); $return = JFactory::getSession()->get('com_media.return_url'); $this->folder = $this->input->get('folder', '', 'path'); // Don't redirect to an external URL. if (!JUri::isInternal($return)) { $return = ''; } // Set the redirect if ($return) { $this->setRedirect($return . '&folder=' . $this->folder); } else { $this->setRedirect('index.php?option=com_media&folder=' . $this->folder); } // Authorize the user if (!$this->authoriseUser('create')) { return false; } // Total length of post back data in bytes. $contentLength = (int) $_SERVER['CONTENT_LENGTH']; // Instantiate the media helper $mediaHelper = new JHelperMedia(); // Maximum allowed size of post back data in MB. $postMaxSize = $mediaHelper->toBytes(ini_get('post_max_size')); // Maximum allowed size of script execution in MB. $memoryLimit = $mediaHelper->toBytes(ini_get('memory_limit')); // Check for the total size of post back data. if ($postMaxSize > 0 && $contentLength > $postMaxSize || $memoryLimit != -1 && $contentLength > $memoryLimit) { JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_WARNUPLOADTOOLARGE')); return false; } $uploadMaxSize = $params->get('upload_maxsize', 0) * 1024 * 1024; $uploadMaxFileSize = $mediaHelper->toBytes(ini_get('upload_max_filesize')); // Perform basic checks on file info before attempting anything foreach ($files as &$file) { $file['name'] = JFile::makeSafe($file['name']); $file['filepath'] = JPath::clean(implode(DIRECTORY_SEPARATOR, array(COM_MEDIA_BASE, $this->folder, $file['name']))); if ($file['error'] == 1 || $uploadMaxSize > 0 && $file['size'] > $uploadMaxSize || $uploadMaxFileSize > 0 && $file['size'] > $uploadMaxFileSize) { // File size exceed either 'upload_max_filesize' or 'upload_maxsize'. JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE')); return false; } if (JFile::exists($file['filepath'])) { // A file with this name already exists JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_FILE_EXISTS')); return false; } if (!isset($file['name'])) { // No filename (after the name was cleaned by JFile::makeSafe) $this->setRedirect('index.php', JText::_('COM_MEDIA_INVALID_REQUEST'), 'error'); return false; } } // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); JPluginHelper::importPlugin('content'); $dispatcher = JEventDispatcher::getInstance(); foreach ($files as &$file) { // The request is valid $err = null; if (!MediaHelper::canUpload($file, $err)) { // The file can't be uploaded return false; } // Trigger the onContentBeforeSave event. $object_file = new JObject($file); $result = $dispatcher->trigger('onContentBeforeSave', array('com_media.file', &$object_file, true)); if (in_array(false, $result, true)) { // There are some errors in the plugins JError::raiseWarning(100, JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); return false; } if (!JFile::upload($object_file->tmp_name, $object_file->filepath)) { // Error in upload JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')); return false; } else { // Trigger the onContentAfterSave event. $dispatcher->trigger('onContentAfterSave', array('com_media.file', &$object_file, true)); $this->setMessage(JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', substr($object_file->filepath, strlen(COM_MEDIA_BASE)))); } } return true; }
/** * Upload a file * * @return void * * @since 1.5 */ public function upload() { $params = JComponentHelper::getParams('com_media'); // Check for request forgeries if (!JSession::checkToken('request')) { $response = array('status' => '0', 'message' => JText::_('JINVALID_TOKEN'), 'error' => JText::_('JINVALID_TOKEN')); echo json_encode($response); return; } // Get the user $user = JFactory::getUser(); JLog::addLogger(array('text_file' => 'upload.error.php'), JLog::ALL, array('upload')); // Get some data from the request $file = $this->input->files->get('Filedata', '', 'array'); $folder = $this->input->get('folder', '', 'path'); // Instantiate the media helper $mediaHelper = new JHelperMedia(); if ($_SERVER['CONTENT_LENGTH'] > $params->get('upload_maxsize', 0) * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > $mediaHelper->toBytes(ini_get('upload_max_filesize')) || $_SERVER['CONTENT_LENGTH'] > $mediaHelper->toBytes(ini_get('post_max_size')) || $_SERVER['CONTENT_LENGTH'] > $mediaHelper->toBytes(ini_get('memory_limit'))) { $response = array('status' => '0', 'message' => JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE'), 'error' => JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE')); echo json_encode($response); return; } // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); if (isset($file['name'])) { // Make the filename safe $file['name'] = JFile::makeSafe($file['name']); // We need a URL safe name $fileparts = pathinfo(COM_MEDIA_BASE . '/' . $folder . '/' . $file['name']); // Transform filename to punycode $fileparts['filename'] = JStringPunycode::toPunycode($fileparts['filename']); $tempExt = !empty($fileparts['extension']) ? strtolower($fileparts['extension']) : ''; // Transform filename to punycode, then neglect otherthan non-alphanumeric characters & underscores. Also transform extension to lowercase $safeFileName = preg_replace(array("/[\\s]/", "/[^a-zA-Z0-9_]/"), array("_", ""), $fileparts['filename']) . '.' . $tempExt; // Create filepath with safe-filename $files['final'] = $fileparts['dirname'] . DIRECTORY_SEPARATOR . $safeFileName; $file['name'] = $safeFileName; $filepath = JPath::clean($files['final']); if (!$mediaHelper->canUpload($file, 'com_media')) { JLog::add('Invalid: ' . $filepath, JLog::INFO, 'upload'); $response = array('status' => '0', 'message' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE'), 'error' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')); echo json_encode($response); return; } // Trigger the onContentBeforeSave event. JPluginHelper::importPlugin('content'); $dispatcher = JEventDispatcher::getInstance(); $object_file = new JObject($file); $object_file->filepath = $filepath; $result = $dispatcher->trigger('onContentBeforeSave', array('com_media.file', &$object_file, true)); if (in_array(false, $result, true)) { // There are some errors in the plugins JLog::add('Errors before save: ' . $object_file->filepath . ' : ' . implode(', ', $object_file->getErrors()), JLog::INFO, 'upload'); $response = array('status' => '0', 'message' => JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors)), 'error' => JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); echo json_encode($response); return; } if (JFile::exists($object_file->filepath)) { // File exists JLog::add('File exists: ' . $object_file->filepath . ' by user_id ' . $user->id, JLog::INFO, 'upload'); $response = array('status' => '0', 'message' => JText::_('COM_MEDIA_ERROR_FILE_EXISTS'), 'error' => JText::_('COM_MEDIA_ERROR_FILE_EXISTS'), 'location' => str_replace(JPATH_ROOT, '', $filepath)); echo json_encode($response); return; } elseif (!$user->authorise('core.create', 'com_media')) { // File does not exist and user is not authorised to create JLog::add('Create not permitted: ' . $object_file->filepath . ' by user_id ' . $user->id, JLog::INFO, 'upload'); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_CREATE_NOT_PERMITTED'), 'message' => JText::_('COM_MEDIA_ERROR_CREATE_NOT_PERMITTED')); echo json_encode($response); return; } if (!JFile::upload($object_file->tmp_name, $object_file->filepath)) { // Error in upload JLog::add('Error on upload: ' . $object_file->filepath, JLog::INFO, 'upload'); $response = array('status' => '0', 'message' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE'), 'error' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')); echo json_encode($response); return; } else { // Trigger the onContentAfterSave event. $dispatcher->trigger('onContentAfterSave', array('com_media.file', &$object_file, true)); JLog::add($folder, JLog::INFO, 'upload'); $returnUrl = str_replace(JPATH_ROOT, '', $object_file->filepath); $response = array('status' => '1', 'message' => JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', $returnUrl), 'error' => JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', $returnUrl), 'location' => str_replace('\\', '/', $returnUrl)); echo json_encode($response); return; } } else { $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_BAD_REQUEST'), 'message' => JText::_('COM_MEDIA_ERROR_BAD_REQUEST')); echo json_encode($response); return; } }
public function upload_media() { $model = $this->getModel(); $input = JFactory::getApplication()->input; $image = $input->files->get('image'); $dir = $input->post->get('folder', '', 'PATH'); $report = array(); if (count($image)) { if ($image['error'] == UPLOAD_ERR_OK) { $error = false; $params = JComponentHelper::getParams('com_media'); $contentLength = (int) $_SERVER['CONTENT_LENGTH']; $mediaHelper = new JHelperMedia(); $postMaxSize = $mediaHelper->toBytes(ini_get('post_max_size')); $memoryLimit = $mediaHelper->toBytes(ini_get('memory_limit')); // Check for the total size of post back data. if ($postMaxSize > 0 && $contentLength > $postMaxSize || $memoryLimit != -1 && $contentLength > $memoryLimit) { $report['status'] = false; $report['output'] = JText::_('COM_SPPAGEBUILDER_MEDIA_MANAGER_MEDIA_TOTAL_SIZE_EXCEEDS'); $error = true; echo json_encode($report); die; } $uploadMaxSize = $params->get('upload_maxsize', 0) * 1024 * 1024; $uploadMaxFileSize = $mediaHelper->toBytes(ini_get('upload_max_filesize')); if ($image['error'] == 1 || $uploadMaxSize > 0 && $image['size'] > $uploadMaxSize || $uploadMaxFileSize > 0 && $image['size'] > $uploadMaxFileSize) { $report['status'] = false; $report['output'] = JText::_('COM_SPPAGEBUILDER_MEDIA_MANAGER_MEDIA_LARGE'); $error = true; } // Upload if no error found if (!$error) { $date = JFactory::getDate(); $folder = 'images/' . JHtml::_('date', $date, 'Y') . '/' . JHtml::_('date', $date, 'm') . '/' . JHtml::_('date', $date, 'd'); if ($dir != '') { $folder = ltrim($dir, '/'); } if (!JFolder::exists(JPATH_ROOT . '/' . $folder)) { JFolder::create(JPATH_ROOT . '/' . $folder, 0755); } if (!JFolder::exists(JPATH_ROOT . '/' . $folder . '/_spmedia_thumbs')) { JFolder::create(JPATH_ROOT . '/' . $folder . '/_spmedia_thumbs', 0755); } $name = $image['name']; $path = $image['tmp_name']; // Do no override existing file $file = preg_replace('#\\s+#', "-", JFile::makeSafe(basename($name))); $i = 0; do { $base_name = JFile::stripExt($file) . ($i ? "{$i}" : ""); $ext = JFile::getExt($file); $image_name = $base_name . '.' . $ext; $i++; $dest = JPATH_ROOT . '/' . $folder . '/' . $image_name; $src = $folder . '/' . $image_name; } while (file_exists($dest)); // End Do not override if (JFile::upload($path, $dest)) { $thumb = ''; if (strtolower($ext) == 'svg') { $report['src'] = JURI::root(true) . '/' . $src; } else { $image = new SppagebuilderHelperImage($dest); if ($image->getWidth() > 300 || $image->getWidth() > 225) { $image->createThumbs(array('spmedia_thumb' => '300x225'), 5, '_spmedia_thumbs'); $report['src'] = JURI::root(true) . '/' . $folder . '/_spmedia_thumbs/' . $base_name . '.' . $ext; $thumb = $folder . '/_spmedia_thumbs/' . $base_name . '.' . $ext; } else { $report['src'] = JURI::root(true) . '/' . $src; } } $insertid = $model->insertMedia($base_name, $src, $thumb, 'image'); $report['status'] = true; $report['title'] = $base_name; $report['id'] = $insertid; $report['path'] = $src; } } } } else { $report['status'] = false; $report['output'] = JText::_('COM_SPPAGEBUILDER_MEDIA_MANAGER_UPLOAD_FAILED'); } echo json_encode($report); die; }
/** * Tests the imageResize method * * @param string $fileName The filename * @param string $expected Expected result * * @return void * * @dataProvider imageResizeProvider * @since 3.2 */ public function testImageResize($width, $height, $target, $expected) { $newSize = $this->object->imageResize($width, $height, $target); $this->assertEquals($newSize, $expected); }
jexit('Invalid root directory!'); } // Get allowed file extensions from com_media's configuration $params = JComponentHelper::getParams('com_media'); $regEx = '^[a-zA-Z0-9\\-_]+\\.(' . str_replace(',', '|', $params->get('upload_extensions')) . ')$'; // Execute requested task switch ($task = $app->input->getCmd('task')) { case 'post.upload': // Check if uploaded file is image? if (JSNVersion::isJoomlaCompatible('2.5')) { // Load com_media's helper class require_once JPATH_ROOT . '/administrator/components/com_media/helpers/media.php'; if (!@MediaHelper::canUpload($_FILES['file'], $err)) { jexit(JText::_('JSN_EXTFW_GENERAL_UPLOADED_FILE_TYPE_NOT_SUPPORTED')); } } elseif (!@JHelperMedia::canUpload($_FILES['file'])) { jexit(JText::_('JSN_EXTFW_GENERAL_UPLOADED_FILE_TYPE_NOT_SUPPORTED')); } // Move uploaded file to target directory if (!JFile::upload($_FILES['file']['tmp_name'], JPATH_ROOT . $root . '/' . $_FILES['file']['name'])) { jexit(JText::_('JSN_EXTFW_GENERAL_MOVE_UPLOAD_FILE_FAIL')); } exit; break; case 'get.directory': // Get directory list $list = JFolder::folders(JPATH_ROOT . $root); // Initialize return value foreach ($list as $k => $v) { $id = $root . '/' . str_replace(array('/', '\\'), '-DS-', trim($v, '/\\')); $list[$k] = array('attr' => array('rel' => 'folder', 'id' => $id), 'data' => $v, 'state' => 'closed');
public function upload_base64() { // Check for request forgeries JSession::checkToken('request') or jexit(JText::_('JINVALID_TOKEN')); $params = JComponentHelper::getParams('com_media'); // Get data from the request $data = $this->input->get('base64str', null, null); $name = $this->input->get('base64name', null, 'STRING'); $return = JFactory::getSession()->get('com_media.return_url'); $this->folder = $this->input->get('folder', '', 'path'); // Don't redirect to an external URL. if (!JUri::isInternal($return)) { $return = ''; } // Set the redirect if ($return) { $this->setRedirect($return . '&folder=' . $this->folder); } else { $this->setRedirect('index.php?option=com_media&folder=' . $this->folder); } // Authorize the user if (!$this->authoriseUser('create')) { return false; } // Total length of post back data in bytes. $contentLength = (int) $_SERVER['CONTENT_LENGTH']; // Instantiate the media helper $mediaHelper = new JHelperMedia(); // Maximum allowed size of post back data in MB. $postMaxSize = $mediaHelper->toBytes(ini_get('post_max_size')); // Maximum allowed size of script execution in MB. $memoryLimit = $mediaHelper->toBytes(ini_get('memory_limit')); // Check for the total size of post back data. if ($postMaxSize > 0 && $contentLength > $postMaxSize || $memoryLimit != -1 && $contentLength > $memoryLimit) { JError::raiseWarning(100, JText::_('COM_MEDIA_MCM_ERROR_WARNUPLOADTOOLARGE')); return false; } $file = []; $file['content'] = $this->decode_base64($data); // validate the decoded base64 string if (!$this->validate_base64($file['content'], 'image/jpeg')) { // invalid base64 'image/jpeg' JError::raiseWarning(100, JText::_('COM_MEDIA_MCM_INVALID_REQUEST')); return false; } // Perform basic checks on file info before attempting anything $file['name'] = JFile::makeSafe($name); $file['filepath'] = JPath::clean(implode(DIRECTORY_SEPARATOR, array(COM_MEDIA_MCM_BASE, $this->folder, $file['name']))); $file['size'] = strlen($file['content']); $uploadMaxSize = $params->get('upload_maxsize', 0) * 1024 * 1024; $uploadMaxFileSize = $mediaHelper->toBytes(ini_get('upload_max_filesize')); if ($uploadMaxSize > 0 && $file['size'] > $uploadMaxSize || $uploadMaxFileSize > 0 && $file['size'] > $uploadMaxFileSize) { // File size exceed either 'upload_max_filesize' or 'upload_maxsize'. JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE')); return false; } if (JFile::exists($file['filepath'])) { // A file with this name already exists JError::raiseWarning(100, JText::_('COM_MEDIA_MCM_ERROR_FILE_EXISTS')); return false; } if (!isset($file['name'])) { // No filename (after the name was cleaned by JFile::makeSafe) $this->setRedirect('index.php', JText::_('COM_MEDIA_MCM_INVALID_REQUEST'), 'error'); return false; } $this->uploadFile($file); return true; }
/** * @param $file * @param $uploadfolder * @param $format * * @return boolean */ public static function upload($file, $uploadfolder, $format) { jimport('joomla.filesystem.folder'); require_once JPATH_ADMINISTRATOR . '/components/com_media/helpers/media.php'; $err = null; // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe jimport('joomla.filesystem.file'); $file['name'] = JFile::makeSafe($file['name']); if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name']) || !empty($file['error'])) { return false; } if (!JFolder::exists($uploadfolder)) { return false; } if (isset($file['name'])) { $filepath = JPath::clean($uploadfolder . '/' . strtolower($file['name'])); if (!JHelperMedia::canUpload($file, $err)) { if ($format == 'json') { //jimport('joomla.error.log'); //$log = JLog::getInstance('upload.error.php'); //$log->addEntry(array('comment' => 'Invalid: '.$filepath.': '.$err)); header('HTTP/1.0 415 Unsupported Media Type'); jexit('Error. Unsupported Media Type!'); } else { return false; } } if (JFile::exists($filepath)) { if ($format == 'json') { //jimport('joomla.error.log'); //$log = JLog::getInstance('upload.error.php'); //$log->addEntry(array('comment' => 'File already exists: '.$filepath)); header('HTTP/1.0 409 Conflict'); jexit('Error. File already exists'); } else { $ext = JFile::getExt($file['name']); $name = JFile::stripExt($file['name']); $newFileName = ''; for ($i = 2; file_exists("{$uploadfolder}/{$newFileName}"); $i++) { $newFileName = $name . "-{$i}." . $ext; } $filepath = $uploadfolder . '/' . $newFileName; } } if (!JFile::upload($file['tmp_name'], $filepath)) { if ($format == 'json') { //jimport('joomla.error.log'); //$log = JLog::getInstance('upload.error.php'); //$log->addEntry(array('comment' => 'Cannot upload: '.$filepath)); header('HTTP/1.0 400 Bad Request'); jexit('Error. Unable to upload file'); } else { return false; } } else { if ($format == 'json') { //jimport('joomla.error.log'); //$log = JLog::getInstance(); //$log->addEntry(array('comment' => $uploadfolder)); jexit('Upload complete'); } else { return true; } } } else { return false; } }
/** * Handles the file uploads */ function upload() { $this->checkUserPrivileges(); $this->csrfProtection(); // Get the user $user = $this->container->platform->getUser(); // Get some data from the request $categoryId = $this->input->getInt('id', 0); $folder = $this->input->getString('folder', ''); $file = $this->input->files->get('upload'); // Get output directory /** @var \Akeeba\ReleaseSystem\Admin\Model\Upload $model */ $model = $this->getModel(); $model->setState('category', (int) $categoryId); $model->setState('folder', $folder); $targetDirectory = $model->getCategoryFolder(); $potentialPrefix = substr($targetDirectory, 0, 5); $potentialPrefix = strtolower($potentialPrefix); $useS3 = $potentialPrefix == 's3://'; if ($useS3) { // When using S3, we are uploading to the temporary directory so that // we can then upload to S3 and remove from our server. $jConfig = \JFactory::getConfig(); $s3Dir = $targetDirectory; $targetDirectory = $jConfig->get('tmp_path', ''); } if (empty($targetDirectory) || !\JFolder::exists($targetDirectory)) { throw new \RuntimeException('Output directory not found', 500); } // Set FTP credentials, if given \JLoader::import('joomla.client.helper'); \JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe $file['name'] = \JFile::makeSafe($file['name']); if (!isset($file['name'])) { $url = 'index.php?option=com_ars&view=upload&task=category&id=' . (int) $categoryId . '&folder=' . urlencode($folder) . '&' . \JFactory::getSession()->getFormToken(true) . '=1'; $this->setRedirect($url, \JText::_('MSG_UPLOAD_INVALID_REQUEST'), 'error'); return; } // The request is valid $err = null; \JLoader::import('cms.helper.media'); $mediaHelper = new \JHelperMedia(); \JFactory::getLanguage()->load('com_media', JPATH_ADMINISTRATOR); if (!$mediaHelper->canUpload($file)) { // The file can't be upload $url = 'index.php?option=com_ars&view=upload&task=category&id=' . (int) $categoryId . '&folder=' . urlencode($folder) . '&' . \JFactory::getSession()->getFormToken(true) . '=1'; $this->setRedirect($url); return; } $filePath = \JPath::clean($targetDirectory . '/' . strtolower($file['name'])); if (\JFile::exists($filePath)) { // File exists; delete before upload \JFile::delete($filePath); } // ACL check for Joomla! 1.6.x if (!$user->authorise('core.create', 'com_media')) { // File does not exist and user is not authorised to create throw new \RuntimeException(\JText::_('MSG_NO_UPLOAD_RIGHT'), 403); } if (!\JFile::upload($file['tmp_name'], $filePath, false, true)) { throw new \RuntimeException(\JText::_('MSG_FILE_NOT_UPLOADED'), 403); } if ($useS3) { $s3 = AmazonS3::getInstance(); $s3TargetDir = trim(substr($s3Dir, 5), '/'); if (!empty($s3TargetDir)) { $s3TargetDir .= '/'; } $success = $s3->putObject($filePath, $s3TargetDir . $file['name']); if (!@unlink($filePath)) { \JFile::delete($filePath); } if (!$success) { $url = 'index.php?option=com_ars&view=Upload&task=category&id=' . (int) $categoryId . '&folder=' . urlencode($this->input->getString('folder')) . '&' . \JFactory::getSession()->getFormToken(true) . '=1'; $this->setRedirect($url, $s3->getError(), 'error'); return; } } $url = 'index.php?option=com_ars&view=upload&task=category&id=' . (int) $categoryId . '&folder=' . urlencode($this->input->getString('folder')) . '&' . \JFactory::getSession()->getFormToken(true) . '=1'; $this->setRedirect($url, \JText::_('MSG_ALL_FILES_UPLOADED')); }