Esempio n. 1
0
 /**
  * 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;
 }
Esempio n. 2
0
 /**
  * Checks if the file can be uploaded
  *
  * @param   array   $file   File information
  * @param   string  $error  An error message to be returned
  *
  * @return  boolean
  *
  * @since   1.5
  * @deprecated  4.0  Use JHelperMedia::canUpload instead
  */
 public static function canUpload($file, $error = '')
 {
     JLog::add('MediaHelper::canUpload() is deprecated. Use JHelperMedia::canUpload() instead.', JLog::WARNING, 'deprecated');
     $mediaHelper = new JHelperMedia();
     return $mediaHelper->canUpload($file, 'com_media');
 }
Esempio n. 3
0
 /**
  * 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;
     }
 }
Esempio n. 4
0
 /**
  * Tests the canUpload method
  *
  * @param   array    $file      File information
  * @param   boolean  $expected  Expected result
  *
  * @return  void
  *
  * @dataProvider  canUploadProvider
  * @since         3.2
  */
 public function testCanUpload($file, $expected)
 {
     $canUpload = $this->object->canUpload($file);
     $this->assertEquals($canUpload, $expected);
 }
Esempio n. 5
0
    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');
Esempio n. 6
0
 /**
  * @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;
     }
 }
Esempio n. 7
0
 /**
  * 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'));
 }
 /**
  * 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'));
     // Get some data from the request
     $files = $this->input->files->get('files', '', 'array');
     $return = JFactory::getSession()->get('com_media.return_url');
     $this->folder = $this->input->get('folder', '', 'path');
     if (empty($this->folder)) {
         $this->folder = $this->getFoldersModel()->getCurrentFolder();
     }
     // Don't redirect to an external URL.
     if (!JUri::isInternal($return)) {
         $return = '';
     }
     // Set the redirect
     $return = $return ?: 'index.php?option=com_media';
     $this->setRedirect($return . '&folder=' . $this->folder);
     // Authorize the user
     if (!$this->isUserAuthorized('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) {
         $this->setWarning(JText::_('COM_MEDIA_ERROR_WARNUPLOADTOOLARGE'));
         return false;
     }
     // Get com_config params
     $params = JComponentHelper::getParams('com_media');
     $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['name'] = str_replace(' ', '-', $file['name']);
         $file['filepath'] = JPath::clean(implode(DIRECTORY_SEPARATOR, array(COM_MEDIA_BASE, $this->folder, $file['name'])));
         // File size exceed either 'upload_max_filesize' or 'upload_maxsize'.
         if ($file['error'] == 1 || $uploadMaxSize > 0 && $file['size'] > $uploadMaxSize || $uploadMaxFileSize > 0 && $file['size'] > $uploadMaxFileSize) {
             $this->setWarning(JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE'));
             return false;
         }
         // A file with this name already exists
         if (JFile::exists($file['filepath'])) {
             $this->setWarning(JText::_('COM_MEDIA_ERROR_FILE_EXISTS'));
             return false;
         }
         // No filename (after the name was cleaned by JFile::makeSafe)
         if (!isset($file['name'])) {
             $this->setRedirect('index.php', JText::_('COM_MEDIA_INVALID_REQUEST'), 'error');
             return false;
         }
     }
     // Set FTP credentials, if given
     JClientHelper::setCredentialsFromRequest('ftp');
     $mediaHelper = new JHelperMedia();
     foreach ($files as &$file) {
         // The file can't be uploaded
         if (!$mediaHelper->canUpload($file)) {
             return false;
         }
         // Trigger the onContentBeforeSave event.
         $fileObject = new JObject($file);
         $result = $this->triggerEvent('onContentBeforeSave', array('com_media.file', &$fileObject, true));
         // There are some errors in the plugins
         if (in_array(false, $result, true)) {
             $this->setWarning(JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $fileObject->getErrors()), implode('<br />', $errors)));
             return false;
         }
         // Error in upload
         if (!JFile::upload($fileObject->tmp_name, $fileObject->filepath)) {
             $this->setWarning(JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE'));
             return false;
         }
         // Trigger the onContentAfterSave event.
         $this->triggerEvent('onContentAfterSave', array('com_media.file', &$fileObject, true));
         $this->setMessage(JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', substr($fileObject->filepath, strlen(COM_MEDIA_BASE))));
     }
     return true;
 }