validateUpload() 공개 메소드

Validates the uploaded image. Returns the temporary name of the uploaded file.
public validateUpload ( $InputName, $ThrowError = true )
예제 #1
0
 /**
  * Save an image from a field and delete any old image that's been uploaded.
  *
  * @param string $Field The name of the field. The image will be uploaded with the _New extension while the current image will be just the field name.
  * @param array $Options
  */
 public function saveImage($Field, $Options = array())
 {
     $Upload = new Gdn_UploadImage();
     $FileField = str_replace('.', '_', $Field);
     if (!getValueR("{$FileField}_New.name", $_FILES)) {
         trace("{$Field} not uploaded, returning.");
         return false;
     }
     // First make sure the file is valid.
     try {
         $TmpName = $Upload->validateUpload($FileField . '_New', true);
         if (!$TmpName) {
             return false;
             // no file uploaded.
         }
     } catch (Exception $Ex) {
         $this->addError($Ex);
         return false;
     }
     // Get the file extension of the file.
     $Ext = val('OutputType', $Options, trim($Upload->getUploadedFileExtension(), '.'));
     if ($Ext == 'jpeg') {
         $Ext = 'jpg';
     }
     Trace($Ext, 'Ext');
     // The file is valid so let's come up with its new name.
     if (isset($Options['Name'])) {
         $Name = $Options['Name'];
     } elseif (isset($Options['Prefix'])) {
         $Name = $Options['Prefix'] . md5(microtime()) . '.' . $Ext;
     } else {
         $Name = md5(microtime()) . '.' . $Ext;
     }
     // We need to parse out the size.
     $Size = val('Size', $Options);
     if ($Size) {
         if (is_numeric($Size)) {
             touchValue('Width', $Options, $Size);
             touchValue('Height', $Options, $Size);
         } elseif (preg_match('`(\\d+)x(\\d+)`i', $Size, $M)) {
             touchValue('Width', $Options, $M[1]);
             touchValue('Height', $Options, $M[2]);
         }
     }
     trace($Options, "Saving image {$Name}.");
     try {
         $Parsed = $Upload->saveImageAs($TmpName, $Name, val('Height', $Options, ''), val('Width', $Options, ''), $Options);
         trace($Parsed, 'Saved Image');
         $Current = $this->getFormValue($Field);
         if ($Current && val('DeleteOriginal', $Options, true)) {
             // Delete the current image.
             trace("Deleting original image: {$Current}.");
             if ($Current) {
                 $Upload->delete($Current);
             }
         }
         // Set the current value.
         $this->setFormValue($Field, $Parsed['SaveName']);
     } catch (Exception $Ex) {
         $this->addError($Ex);
     }
 }
 /**
  * Banner management screen.
  *
  * @since 2.0.0
  * @access public
  */
 public function banner()
 {
     $this->permission('Garden.Community.Manage');
     $this->addSideMenu('dashboard/settings/banner');
     $this->title(t('Banner'));
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigurationModel->setField(array('Garden.HomepageTitle' => c('Garden.Title'), 'Garden.Title', 'Garden.Description'));
     // Set the model on the form.
     $this->Form->setModel($ConfigurationModel);
     // Get the current logo.
     $Logo = c('Garden.Logo');
     if ($Logo) {
         $Logo = ltrim($Logo, '/');
         // Fix the logo path.
         if (stringBeginsWith($Logo, 'uploads/')) {
             $Logo = substr($Logo, strlen('uploads/'));
         }
         $this->setData('Logo', $Logo);
     }
     // Get the current mobile logo.
     $MobileLogo = c('Garden.MobileLogo');
     if ($MobileLogo) {
         $MobileLogo = ltrim($MobileLogo, '/');
         // Fix the logo path.
         if (stringBeginsWith($MobileLogo, 'uploads/')) {
             $MobileLogo = substr($MobileLogo, strlen('uploads/'));
         }
         $this->setData('MobileLogo', $MobileLogo);
     }
     // Get the current favicon.
     $Favicon = c('Garden.FavIcon');
     $this->setData('Favicon', $Favicon);
     $ShareImage = c('Garden.ShareImage');
     $this->setData('ShareImage', $ShareImage);
     // If seeing the form for the first time...
     if (!$this->Form->authenticatedPostBack()) {
         // Apply the config settings to the form.
         $this->Form->setData($ConfigurationModel->Data);
     } else {
         $SaveData = array();
         if ($this->Form->save() !== false) {
             $Upload = new Gdn_Upload();
             try {
                 // Validate the upload
                 $TmpImage = $Upload->validateUpload('Logo', false);
                 if ($TmpImage) {
                     // Generate the target image name
                     $TargetImage = $Upload->generateTargetName(PATH_UPLOADS);
                     $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
                     // Delete any previously uploaded images.
                     if ($Logo) {
                         $Upload->delete($Logo);
                     }
                     // Save the uploaded image
                     $Parts = $Upload->SaveAs($TmpImage, $ImageBaseName);
                     $ImageBaseName = $Parts['SaveName'];
                     $SaveData['Garden.Logo'] = $ImageBaseName;
                     $this->setData('Logo', $ImageBaseName);
                 }
                 $TmpMobileImage = $Upload->validateUpload('MobileLogo', false);
                 if ($TmpMobileImage) {
                     // Generate the target image name
                     $TargetImage = $Upload->generateTargetName(PATH_UPLOADS);
                     $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
                     // Delete any previously uploaded images.
                     if ($MobileLogo) {
                         $Upload->delete($MobileLogo);
                     }
                     // Save the uploaded image
                     $Parts = $Upload->saveAs($TmpMobileImage, $ImageBaseName);
                     $ImageBaseName = $Parts['SaveName'];
                     $SaveData['Garden.MobileLogo'] = $ImageBaseName;
                     $this->setData('MobileLogo', $ImageBaseName);
                 }
                 $ImgUpload = new Gdn_UploadImage();
                 $TmpFavicon = $ImgUpload->validateUpload('Favicon', false);
                 if ($TmpFavicon) {
                     $ICOName = 'favicon_' . substr(md5(microtime()), 16) . '.ico';
                     if ($Favicon) {
                         $Upload->delete($Favicon);
                     }
                     // Resize the to a png.
                     $Parts = $ImgUpload->SaveImageAs($TmpFavicon, $ICOName, 16, 16, array('OutputType' => 'ico', 'Crop' => true));
                     $SaveData['Garden.FavIcon'] = $Parts['SaveName'];
                     $this->setData('Favicon', $Parts['SaveName']);
                 }
                 $TmpShareImage = $Upload->ValidateUpload('ShareImage', false);
                 if ($TmpShareImage) {
                     $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS, false);
                     $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
                     if ($ShareImage) {
                         $Upload->delete($ShareImage);
                     }
                     $Parts = $Upload->SaveAs($TmpShareImage, $ImageBaseName);
                     $SaveData['Garden.ShareImage'] = $Parts['SaveName'];
                     $this->setData('ShareImage', $Parts['SaveName']);
                 }
             } catch (Exception $ex) {
                 $this->Form->addError($ex);
             }
             // If there were no errors, save the path to the logo in the config
             if ($this->Form->errorCount() == 0) {
                 saveToConfig($SaveData);
             }
             $this->informMessage(t("Your settings have been saved."));
         }
     }
     $this->render();
 }
예제 #3
0
 /**
  * Form for adding an email image.
  * Exposes the Garden.EmailTemplate.Image setting.
  * Garden.EmailTemplate.Image must be an upload.
  *
  * Saves the image based on 2 config settings:
  * Garden.EmailTemplate.ImageMaxWidth (default 400px) and
  * Garden.EmailTemplate.ImageMaxHeight (default 300px)
  *
  * @throws Gdn_UserException
  */
 public function emailImage()
 {
     if (!Gdn::session()->checkPermission('Garden.Community.Manage')) {
         throw permissionException();
     }
     $this->addJsFile('email.js');
     $this->addSideMenu('dashboard/settings/email');
     $image = c('Garden.EmailTemplate.Image');
     $this->Form = new Gdn_Form();
     $validation = new Gdn_Validation();
     $configurationModel = new Gdn_ConfigurationModel($validation);
     // Set the model on the form.
     $this->Form->setModel($configurationModel);
     if ($this->Form->authenticatedPostBack() !== false) {
         try {
             $upload = new Gdn_UploadImage();
             // Validate the upload
             $tmpImage = $upload->validateUpload('EmailImage', false);
             if ($tmpImage) {
                 // Generate the target image name
                 $targetImage = $upload->generateTargetName(PATH_UPLOADS);
                 $imageBaseName = pathinfo($targetImage, PATHINFO_BASENAME);
                 // Delete any previously uploaded images.
                 if ($image) {
                     $upload->delete($image);
                 }
                 // Save the uploaded image
                 $parts = $upload->saveImageAs($tmpImage, $imageBaseName, c('Garden.EmailTemplate.ImageMaxWidth', 400), c('Garden.EmailTemplate.ImageMaxHeight', 300));
                 $imageBaseName = $parts['SaveName'];
                 saveToConfig('Garden.EmailTemplate.Image', $imageBaseName);
                 $this->setData('EmailImage', Gdn_UploadImage::url($imageBaseName));
             } else {
                 $this->Form->addError(t('There\'s been an error uploading the image. Your email logo can uploaded in one of the following filetypes: gif, jpg, png'));
             }
         } catch (Exception $ex) {
             $this->Form->addError($ex);
         }
     }
     $this->render();
 }
예제 #4
0
 /**
  * Set the icon for an addon.
  *
  * @param int $AddonID Specified addon id.
  * @throws Exception Addon not found.
  */
 public function icon($AddonID = '')
 {
     $Session = Gdn::session();
     if (!$Session->isValid()) {
         $this->Form->addError('You must be authenticated in order to use this form.');
     }
     $Addon = $this->AddonModel->getID($AddonID);
     if (!$Addon) {
         throw notFoundException('Addon');
     }
     if ($Session->UserID != $Addon['InsertUserID']) {
         $this->permission('Addons.Addon.Manage');
     }
     $this->addModule('AddonHelpModule', 'Panel');
     $this->Form->setModel($this->AddonModel);
     $this->Form->addHidden('AddonID', $AddonID);
     if ($this->Form->authenticatedPostBack()) {
         $UploadImage = new Gdn_UploadImage();
         try {
             // Validate the upload
             $imageLocation = $UploadImage->validateUpload('Icon');
             $TargetImage = $this->saveIcon($imageLocation);
         } catch (Exception $ex) {
             $this->Form->addError($ex);
         }
         // If there were no errors, remove the old picture and insert the picture
         if ($this->Form->errorCount() == 0) {
             if ($Addon['Icon']) {
                 $UploadImage->delete($Addon['Icon']);
             }
             $this->AddonModel->save(array('AddonID' => $AddonID, 'Icon' => $TargetImage));
         }
         // If there were no problems, redirect back to the addon
         if ($this->Form->errorCount() == 0) {
             $this->RedirectUrl = Url('/addon/' . AddonModel::slug($Addon));
         }
     }
     $this->render();
 }
예제 #5
0
 /**
  * Settings page for HTML email styling.
  *
  * Exposes config settings:
  * Garden.EmailTemplate.BackgroundColor
  * Garden.EmailTemplate.ButtonBackgroundColor
  * Garden.EmailTemplate.ButtonTextColor
  * Garden.EmailTemplate.Image
  *
  * Saves the image based on 2 config settings:
  * Garden.EmailTemplate.ImageMaxWidth (default 400px) and
  * Garden.EmailTemplate.ImageMaxHeight (default 300px)
  *
  * @throws Gdn_UserException
  */
 public function emailStyles()
 {
     // Set default colors
     if (!c('Garden.EmailTemplate.TextColor')) {
         saveToConfig('Garden.EmailTemplate.TextColor', EmailTemplate::DEFAULT_TEXT_COLOR, false);
     }
     if (!c('Garden.EmailTemplate.BackgroundColor')) {
         saveToConfig('Garden.EmailTemplate.BackgroundColor', EmailTemplate::DEFAULT_BACKGROUND_COLOR, false);
     }
     if (!c('Garden.EmailTemplate.ContainerBackgroundColor')) {
         saveToConfig('Garden.EmailTemplate.ContainerBackgroundColor', EmailTemplate::DEFAULT_CONTAINER_BACKGROUND_COLOR, false);
     }
     if (!c('Garden.EmailTemplate.ButtonTextColor')) {
         saveToConfig('Garden.EmailTemplate.ButtonTextColor', EmailTemplate::DEFAULT_BUTTON_TEXT_COLOR, false);
     }
     if (!c('Garden.EmailTemplate.ButtonBackgroundColor')) {
         saveToConfig('Garden.EmailTemplate.ButtonBackgroundColor', EmailTemplate::DEFAULT_BUTTON_BACKGROUND_COLOR, false);
     }
     $this->permission('Garden.Settings.Manage');
     $this->setHighlightRoute('dashboard/settings/emailstyles');
     $this->addJsFile('email.js');
     // Get the current logo.
     $image = c('Garden.EmailTemplate.Image');
     if ($image) {
         $image = ltrim($image, '/');
         $this->setData('EmailImage', Gdn_UploadImage::url($image));
     }
     $this->Form = new Gdn_Form();
     $validation = new Gdn_Validation();
     $configurationModel = new Gdn_ConfigurationModel($validation);
     $configurationModel->setField(array('Garden.EmailTemplate.TextColor', 'Garden.EmailTemplate.BackgroundColor', 'Garden.EmailTemplate.ContainerBackgroundColor', 'Garden.EmailTemplate.ButtonTextColor', 'Garden.EmailTemplate.ButtonBackgroundColor'));
     // Set the model on the form.
     $this->Form->setModel($configurationModel);
     // If seeing the form for the first time...
     if ($this->Form->authenticatedPostBack() === false) {
         // Apply the config settings to the form.
         $this->Form->setData($configurationModel->Data);
     } else {
         $image = c('Garden.EmailTemplate.Image');
         $upload = new Gdn_UploadImage();
         if ($upload->isUpload('EmailImage')) {
             try {
                 $tmpImage = $upload->validateUpload('EmailImage');
                 if ($tmpImage) {
                     // Generate the target image name
                     $targetImage = $upload->generateTargetName(PATH_UPLOADS);
                     $imageBaseName = pathinfo($targetImage, PATHINFO_BASENAME);
                     // Delete any previously uploaded images.
                     if ($image) {
                         $upload->delete($image);
                     }
                     // Save the uploaded image
                     $parts = $upload->saveImageAs($tmpImage, $imageBaseName, c('Garden.EmailTemplate.ImageMaxWidth', 400), c('Garden.EmailTemplate.ImageMaxHeight', 300));
                     $imageBaseName = $parts['SaveName'];
                     saveToConfig('Garden.EmailTemplate.Image', $imageBaseName);
                     $this->setData('EmailImage', Gdn_UploadImage::url($imageBaseName));
                 }
             } catch (Exception $ex) {
                 $this->Form->addError($ex);
             }
         }
         if ($this->Form->save() !== false) {
             $this->informMessage(t("Your settings have been saved."));
         }
     }
     $this->render();
 }
예제 #6
0
 /**
  * Set user's photo (avatar).
  *
  * @since 2.0.0
  * @access public
  *
  * @param mixed $userReference Unique identifier, possible username or ID.
  * @param string $username The username.
  * @param string $userID The user's ID.
  *
  * @throws Exception
  * @throws Gdn_UserException
  */
 public function picture($userReference = '', $username = '', $userID = '')
 {
     $this->addJsFile('profile.js');
     if (!$this->CanEditPhotos) {
         throw forbiddenException('@Editing user photos has been disabled.');
     }
     // Permission checks
     $this->permission(array('Garden.Profiles.Edit', 'Moderation.Profiles.Edit', 'Garden.ProfilePicture.Edit'), false);
     $session = Gdn::session();
     if (!$session->isValid()) {
         $this->Form->addError('You must be authenticated in order to use this form.');
     }
     // Check ability to manipulate image
     if (function_exists('gd_info')) {
         $gdInfo = gd_info();
         $gdVersion = preg_replace('/[a-z ()]+/i', '', $gdInfo['GD Version']);
         if ($gdVersion < 2) {
             throw new Exception(sprintf(t("This installation of GD is too old (v%s). Vanilla requires at least version 2 or compatible."), $gdVersion));
         }
     } else {
         throw new Exception(sprintf(t("Unable to detect PHP GD installed on this system. Vanilla requires GD version 2 or better.")));
     }
     // Get user data & prep form.
     if ($this->Form->authenticatedPostBack() && $this->Form->getFormValue('UserID')) {
         $userID = $this->Form->getFormValue('UserID');
     }
     $this->getUserInfo($userReference, $username, $userID, true);
     $validation = new Gdn_Validation();
     $configurationModel = new Gdn_ConfigurationModel($validation);
     $this->Form->setModel($configurationModel);
     $avatar = $this->User->Photo;
     if ($avatar === null) {
         $avatar = UserModel::getDefaultAvatarUrl();
     }
     $source = '';
     $crop = null;
     if ($this->isUploadedAvatar($avatar)) {
         // Get the image source so we can manipulate it in the crop module.
         $upload = new Gdn_UploadImage();
         $thumbnailSize = c('Garden.Thumbnail.Size', 40);
         $basename = changeBasename($avatar, "p%s");
         $source = $upload->copyLocal($basename);
         // Set up cropping.
         $crop = new CropImageModule($this, $this->Form, $thumbnailSize, $thumbnailSize, $source);
         $crop->setExistingCropUrl(Gdn_UploadImage::url(changeBasename($avatar, "n%s")));
         $crop->setSourceImageUrl(Gdn_UploadImage::url(changeBasename($avatar, "p%s")));
         $this->setData('crop', $crop);
     } else {
         $this->setData('avatar', $avatar);
     }
     if (!$this->Form->authenticatedPostBack()) {
         $this->Form->setData($configurationModel->Data);
     } else {
         if ($this->Form->save() !== false) {
             $upload = new Gdn_UploadImage();
             $newAvatar = false;
             if ($tmpAvatar = $upload->validateUpload('Avatar', false)) {
                 // New upload
                 $thumbOptions = array('Crop' => true, 'SaveGif' => c('Garden.Thumbnail.SaveGif'));
                 $newAvatar = $this->saveAvatars($tmpAvatar, $thumbOptions, $upload);
             } else {
                 if ($avatar && $crop && $crop->isCropped()) {
                     // New thumbnail
                     $tmpAvatar = $source;
                     $thumbOptions = array('Crop' => true, 'SourceX' => $crop->getCropXValue(), 'SourceY' => $crop->getCropYValue(), 'SourceWidth' => $crop->getCropWidth(), 'SourceHeight' => $crop->getCropHeight());
                     $newAvatar = $this->saveAvatars($tmpAvatar, $thumbOptions);
                 }
             }
             if ($this->Form->errorCount() == 0) {
                 if ($newAvatar !== false) {
                     $thumbnailSize = c('Garden.Thumbnail.Size', 40);
                     // Update crop properties.
                     $basename = changeBasename($newAvatar, "p%s");
                     $source = $upload->copyLocal($basename);
                     $crop = new CropImageModule($this, $this->Form, $thumbnailSize, $thumbnailSize, $source);
                     $crop->setSize($thumbnailSize, $thumbnailSize);
                     $crop->setExistingCropUrl(Gdn_UploadImage::url(changeBasename($newAvatar, "n%s")));
                     $crop->setSourceImageUrl(Gdn_UploadImage::url(changeBasename($newAvatar, "p%s")));
                     $this->setData('crop', $crop);
                 }
             }
             if ($this->deliveryType() === DELIVERY_TYPE_VIEW) {
                 $this->jsonTarget('', '', 'Refresh');
                 $this->RedirectUrl = userUrl($this->User);
             }
             $this->informMessage(t("Your settings have been saved."));
         }
     }
     if (val('SideMenuModule', val('Panel', val('Assets', $this)))) {
         /** @var SideMenuModule $sidemenu */
         $sidemenu = $this->Assets['Panel']['SideMenuModule'];
         $sidemenu->highlightRoute('/profile/picture');
     }
     $this->title(t('Change Picture'));
     $this->_setBreadcrumbs(t('Change My Picture'), userUrl($this->User, '', 'picture'));
     $this->render('picture', 'profile', 'dashboard');
 }