Inheritance: extends Gdn_Upload
 /**
  * Create different sizes of user photos.
  */
 public function processAvatars()
 {
     $UploadImage = new Gdn_UploadImage();
     $UserData = $this->SQL->select('u.Photo')->from('User u')->where('u.Photo is not null')->get();
     // Make sure the avatars folder exists.
     if (!file_exists(PATH_UPLOADS . '/userpics')) {
         mkdir(PATH_UPLOADS . '/userpics');
     }
     // Get sizes
     $ProfileHeight = c('Garden.Profile.MaxHeight', 1000);
     $ProfileWidth = c('Garden.Profile.MaxWidth', 250);
     $ThumbSize = c('Garden.Thumbnail.Size', 40);
     // Temporarily set maximum quality
     saveToConfig('Garden.UploadImage.Quality', 100, false);
     // Create profile and thumbnail sizes
     foreach ($UserData->result() as $User) {
         try {
             $Image = PATH_ROOT . DS . 'uploads' . DS . GetValue('Photo', $User);
             $ImageBaseName = pathinfo($Image, PATHINFO_BASENAME);
             // Save profile size
             $UploadImage->SaveImageAs($Image, PATH_UPLOADS . '/userpics/p' . $ImageBaseName, $ProfileHeight, $ProfileWidth);
             // Save thumbnail size
             $UploadImage->SaveImageAs($Image, PATH_UPLOADS . '/userpics/n' . $ImageBaseName, $ThumbSize, $ThumbSize, true);
         } catch (Exception $ex) {
         }
     }
 }
 /**
  * Create different sizes of user photos.
  */
 public function ProcessAvatars()
 {
     $UploadImage = new Gdn_UploadImage();
     $UserData = $this->SQL->Select('u.Photo')->From('User u')->Where('u.Photo is not null')->Get();
     // Make sure the avatars folder exists.
     if (!file_exists(PATH_UPLOADS . '/userpics')) {
         mkdir(PATH_UPLOADS . '/userpics');
     }
     $ProfileHeight = C('Garden.Profile.MaxHeight', 1000);
     $ProfileWidth = C('Garden.Profile.MaxWidth', 250);
     $PreviewHeight = C('Garden.Preview.MaxHeight', 100);
     $PreviewWidth = C('Garden.Preview.MaxWidth', 75);
     $ThumbSize = C('Garden.Thumbnail.Size', 50);
     foreach ($UserData->Result() as $User) {
         try {
             $Image = PATH_ROOT . DS . 'uploads' . DS . $User->Photo;
             $ImageBaseName = pathinfo($Image, PATHINFO_BASENAME);
             // Save profile size
             $UploadImage->SaveImageAs($Image, PATH_UPLOADS . '/userpics/p' . $ImageBaseName, $ProfileHeight, $ProfileWidth);
             // Save thumbnail size
             $UploadImage->SaveImageAs($Image, PATH_UPLOADS . '/userpics/n' . $ImageBaseName, $ThumbSize, $ThumbSize, TRUE);
         } catch (Exception $ex) {
         }
     }
 }
Example #3
0
 public function PostController_Imageupload_create()
 {
     try {
         $UploadImage = new Gdn_UploadImage();
         $TmpImage = $UploadImage->ValidateUpload('image_file');
         // Generate the target image name.
         $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS . '/imageupload', '', TRUE);
         $Props = $UploadImage->SaveImageAs($TmpImage, $TargetImage, C('Plugins.UploadImage.MaxHeight', ''), C('Plugins.UploadImage.MaxWidth', 650));
         echo json_encode(array('url' => $Props['Url'], 'name' => $UploadImage->GetUploadedFileName()));
     } catch (Exception $e) {
         header('HTTP/1.0 400', TRUE, 400);
         echo $e;
     }
 }
 /**
  * Create different sizes of user photos.
  */
 public function processAvatars()
 {
     $UploadImage = new Gdn_UploadImage();
     $UserData = $this->SQL->select('u.Photo')->from('User u')->get();
     foreach ($UserData->result() as $User) {
         try {
             $Image = PATH_ROOT . DS . 'uploads' . DS . str_replace('userpics', 'attachments', $User->Photo);
             // Check extension length
             $ImageExtension = strlen(pathinfo($Image, PATHINFO_EXTENSION));
             $ImageBaseName = pathinfo($Image, PATHINFO_BASENAME) + 1;
             if (!file_exists($Image)) {
                 rename(substr($Image, 0, -$ImageExtension), $Image);
             }
             // Make sure the avatars folder exists.
             if (!file_exists(PATH_ROOT . '/uploads/userpics')) {
                 mkdir(PATH_ROOT . '/uploads/userpics');
             }
             // Save the uploaded image in profile size
             if (!file_exists(PATH_ROOT . '/uploads/userpics/p' . $ImageBaseName)) {
                 $UploadImage->SaveImageAs($Image, PATH_ROOT . '/uploads/userpics/p' . $ImageBaseName, Gdn::config('Garden.Profile.MaxHeight', 1000), Gdn::config('Garden.Profile.MaxWidth', 250));
             }
             // Save the uploaded image in preview size
             /*if (!file_exists(PATH_ROOT.'/uploads/userpics/t'.$ImageBaseName))
               $UploadImage->SaveImageAs(
                  $Image,
                  PATH_ROOT.'/uploads/userpics/t'.$ImageBaseName,
                  Gdn::config('Garden.Preview.MaxHeight', 100),
                  Gdn::config('Garden.Preview.MaxWidth', 75)
               );*/
             // Save the uploaded image in thumbnail size
             $ThumbSize = Gdn::config('Garden.Thumbnail.Size', 40);
             if (!file_exists(PATH_ROOT . '/uploads/userpics/n' . $ImageBaseName)) {
                 $UploadImage->SaveImageAs($Image, PATH_ROOT . '/uploads/userpics/n' . $ImageBaseName, $ThumbSize, $ThumbSize, true);
             }
         } catch (Exception $ex) {
         }
     }
 }
 /**
  * Touch icon management screen.
  *
  * @since 1.0
  * @access public
  */
 public function SettingsController_TouchIcon_Create($Sender)
 {
     $Sender->Permission('Garden.Settings.Manage');
     $Sender->AddSideMenu('settings/touchicon');
     $Sender->Title(T('Touch Icon'));
     if ($Sender->Form->AuthenticatedPostBack()) {
         $Upload = new Gdn_UploadImage();
         try {
             // Validate the upload
             $TmpImage = $Upload->ValidateUpload('TouchIcon', FALSE);
             if ($TmpImage) {
                 // Save the uploaded image.
                 $TouchIconPath = 'banner/touchicon_' . substr(md5(microtime()), 16) . '.png';
                 $ImageInfo = $Upload->SaveImageAs($TmpImage, $TouchIconPath, 114, 114, array('OutputType' => 'png', 'ImageQuality' => '8'));
                 SaveToConfig('Garden.TouchIcon', $ImageInfo['SaveName']);
             }
         } catch (Exception $ex) {
             $Sender->Form->AddError($ex->getMessage());
         }
         $Sender->InformMessage(T("Your icon has been saved."));
     }
     $Sender->SetData('Path', $this->getIconUrl());
     $Sender->Render($this->GetView('touchicon.php'));
 }
Example #6
0
 public function Picture($UserReference = '')
 {
     $this->Permission('Garden.SignIn.Allow');
     $Session = Gdn::Session();
     if (!$Session->IsValid()) {
         $this->Form->AddError('You must be authenticated in order to use this form.');
     }
     $this->GetUserInfo($UserReference);
     $this->Form->SetModel($this->UserModel);
     $this->Form->AddHidden('UserID', $this->User->UserID);
     if ($this->Form->AuthenticatedPostBack() === TRUE) {
         $UploadImage = new Gdn_UploadImage();
         try {
             // Validate the upload
             $TmpImage = $UploadImage->ValidateUpload('Picture');
             // Generate the target image name
             $TargetImage = $UploadImage->GenerateTargetName(PATH_ROOT . DS . 'uploads');
             $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
             // Save the uploaded image in large size
             $UploadImage->SaveImageAs($TmpImage, PATH_ROOT . DS . 'uploads' . DS . 'o' . $ImageBaseName, Gdn::Config('Garden.Picture.MaxHeight', 1000), Gdn::Config('Garden.Picture.MaxWidth', 1000));
             // Save the uploaded image in profile size
             $UploadImage->SaveImageAs($TmpImage, PATH_ROOT . DS . 'uploads' . DS . 'p' . $ImageBaseName, Gdn::Config('Garden.Profile.MaxHeight', 1000), Gdn::Config('Garden.Profile.MaxWidth', 250));
             // Save the uploaded image in preview size
             $UploadImage->SaveImageAs($TmpImage, PATH_ROOT . DS . 'uploads' . DS . 't' . $ImageBaseName, Gdn::Config('Garden.Preview.MaxHeight', 100), Gdn::Config('Garden.Preview.MaxWidth', 75));
             // Save the uploaded image in thumbnail size
             $ThumbSize = Gdn::Config('Garden.Thumbnail.Size', 50);
             $UploadImage->SaveImageAs($TmpImage, PATH_ROOT . DS . 'uploads' . DS . 'n' . $ImageBaseName, $ThumbSize, $ThumbSize, TRUE);
         } catch (Exception $ex) {
             $this->Form->AddError($ex->getMessage());
         }
         // If there were no errors, associate the image with the user
         if ($this->Form->ErrorCount() == 0) {
             $PhotoModel = new Model('Photo');
             $PhotoID = $PhotoModel->Insert(array('Name' => $ImageBaseName));
             if (!$this->UserModel->Save(array('UserID' => $this->User->UserID, 'PhotoID' => $PhotoID, 'Photo' => $ImageBaseName))) {
                 $this->Form->SetValidationResults($this->UserModel->ValidationResults());
             }
         }
         // If there were no problems, redirect back to the user account
         if ($this->Form->ErrorCount() == 0) {
             Redirect('garden/profile/' . $UserReference);
         }
     }
     $this->Render();
 }
Example #7
0
 /**
  * Returns the url to the default avatar for a user.
  *
  * @param array $user The user to get the default avatar for.
  * @param string $size The size of avatar to return (only respected for dashboard-uploaded default avatars).
  * @return string The url to the default avatar image.
  */
 public static function getDefaultAvatarUrl($user = [], $size = 'thumbnail')
 {
     if (!empty($user) && function_exists('UserPhotoDefaultUrl')) {
         return userPhotoDefaultUrl($user);
     }
     if ($avatar = c('Garden.DefaultAvatar', false)) {
         if (strpos($avatar, 'defaultavatar/') !== false) {
             if ($size == 'thumbnail') {
                 return Gdn_UploadImage::url(changeBasename($avatar, 'n%s'));
             } elseif ($size == 'profile') {
                 return Gdn_UploadImage::url(changeBasename($avatar, 'p%s'));
             }
         }
         return $avatar;
     }
     return asset('applications/dashboard/design/images/defaulticon.png', true);
 }
Example #8
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);
     }
 }
Example #9
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();
 }
Example #10
0
<?php

if (!defined('APPLICATION')) {
    exit;
}
$Session = Gdn::session();
// Check that we have the necessary tools to allow image uploading
$AllowImages = Gdn_UploadImage::CanUploadImages();
// Is the photo hosted remotely?
$RemotePhoto = IsUrl($this->User->Photo, 0, 7);
// Define the current profile picture
$Picture = '';
if ($this->User->Photo != '') {
    if (IsUrl($this->User->Photo)) {
        $Picture = img($this->User->Photo, array('class' => 'ProfilePhotoLarge'));
    } else {
        $Picture = img(Gdn_Upload::url(changeBasename($this->User->Photo, 'p%s')), array('class' => 'ProfilePhotoLarge'));
    }
}
// Define the current thumbnail icon
$Thumbnail = $this->User->Photo;
if (!$Thumbnail && function_exists('UserPhotoDefaultUrl')) {
    $Thumbnail = UserPhotoDefaultUrl($this->User);
}
if ($Thumbnail && !isUrl($Thumbnail)) {
    $Thumbnail = Gdn_Upload::url(changeBasename($Thumbnail, 'n%s'));
}
$Thumbnail = img($Thumbnail, array('alt' => t('Thumbnail')));
?>
<div class="SmallPopup FormTitleWrapper">
    <h1 class="H"><?php 
 /**
  * Allows plugin to handle ajax file uploads.
  *
  * @access public
  * @param object $Sender
  */
 public function postController_upload_create($Sender)
 {
     list($FieldName) = $Sender->RequestArgs;
     $Sender->deliveryMethod(DELIVERY_METHOD_JSON);
     $Sender->deliveryType(DELIVERY_TYPE_VIEW);
     include_once $Sender->fetchViewLocation('fileupload_functions', '', 'plugins/FileUpload');
     $Sender->FieldName = $FieldName;
     $Sender->ApcKey = Gdn::request()->getValueFrom(Gdn_Request::INPUT_POST, 'APC_UPLOAD_PROGRESS');
     $FileData = Gdn::request()->getValueFrom(Gdn_Request::INPUT_FILES, $FieldName, false);
     try {
         if (!$this->CanUpload) {
             throw new FileUploadPluginUploadErrorException("You do not have permission to upload files", 11, '???');
         }
         if (!$Sender->Form->isPostBack()) {
             $PostMaxSize = ini_get('post_max_size');
             throw new FileUploadPluginUploadErrorException("The post data was too big (max {$PostMaxSize})", 10, '???');
         }
         if (!$FileData) {
             throw new FileUploadPluginUploadErrorException("No file data could be found in your post", 10, '???');
         }
         // Validate the file upload now.
         $FileErr = $FileData['error'];
         $FileType = $FileData['type'];
         $FileName = $FileData['name'];
         $FileTemp = $FileData['tmp_name'];
         $FileSize = $FileData['size'];
         $FileKey = $Sender->ApcKey ? $Sender->ApcKey : '';
         if ($FileErr != UPLOAD_ERR_OK) {
             $ErrorString = '';
             switch ($FileErr) {
                 case UPLOAD_ERR_INI_SIZE:
                     $MaxUploadSize = ini_get('upload_max_filesize');
                     $ErrorString = sprintf(t('The uploaded file was too big (max %s).'), $MaxUploadSize);
                     break;
                 case UPLOAD_ERR_FORM_SIZE:
                     $ErrorString = 'The uploaded file was too big';
                     break;
                 case UPLOAD_ERR_PARTIAL:
                     $ErrorString = 'The uploaded file was only partially uploaded';
                     break;
                 case UPLOAD_ERR_NO_FILE:
                     $ErrorString = 'No file was uploaded';
                     break;
                 case UPLOAD_ERR_NO_TMP_DIR:
                     $ErrorString = 'Missing a temporary folder';
                     break;
                 case UPLOAD_ERR_CANT_WRITE:
                     $ErrorString = 'Failed to write file to disk';
                     break;
                 case UPLOAD_ERR_EXTENSION:
                     $ErrorString = 'A PHP extension stopped the file upload';
                     break;
             }
             throw new FileUploadPluginUploadErrorException($ErrorString, $FileErr, $FileName, $FileKey);
         }
         // Analyze file extension
         $FileNameParts = pathinfo($FileName);
         $Extension = strtolower($FileNameParts['extension']);
         $AllowedExtensions = C('Garden.Upload.AllowedFileExtensions', array("*"));
         if (!in_array($Extension, $AllowedExtensions) && !in_array('*', $AllowedExtensions)) {
             throw new FileUploadPluginUploadErrorException("Uploaded file type is not allowed.", 11, $FileName, $FileKey);
         }
         // Check upload size
         $MaxUploadSize = Gdn_Upload::unformatFileSize(c('Garden.Upload.MaxFileSize', '1G'));
         if ($FileSize > $MaxUploadSize) {
             $Message = sprintf(t('The uploaded file was too big (max %s).'), Gdn_Upload::formatFileSize($MaxUploadSize));
             throw new FileUploadPluginUploadErrorException($Message, 11, $FileName, $FileKey);
         }
         // Build filename
         $SaveFilename = md5(microtime()) . '.' . strtolower($Extension);
         $SaveFilename = '/FileUpload/' . substr($SaveFilename, 0, 2) . '/' . substr($SaveFilename, 2);
         // Get the image size before doing anything.
         list($ImageWidth, $ImageHeight, $ImageType) = Gdn_UploadImage::imageSize($FileTemp, $FileName);
         // Fire event for hooking save location
         $this->EventArguments['Path'] = $FileTemp;
         $Parsed = Gdn_Upload::parse($SaveFilename);
         $this->EventArguments['Parsed'] =& $Parsed;
         $this->EventArguments['OriginalFilename'] = $FileName;
         $Handled = false;
         $this->EventArguments['Handled'] =& $Handled;
         $this->EventArguments['ImageType'] = $ImageType;
         $this->fireAs('Gdn_Upload')->fireEvent('SaveAs');
         if (!$Handled) {
             // Build save location
             $SavePath = MediaModel::pathUploads() . $SaveFilename;
             if (!is_dir(dirname($SavePath))) {
                 @mkdir(dirname($SavePath), 0777, true);
             }
             if (!is_dir(dirname($SavePath))) {
                 throw new FileUploadPluginUploadErrorException("Internal error, could not save the file.", 9, $FileName);
             }
             // Move to permanent location
             // Use SaveImageAs so that image is rotated if necessary
             if ($ImageType !== false) {
                 try {
                     $ImgParsed = Gdn_UploadImage::saveImageAs($FileTemp, $SavePath);
                     $MoveSuccess = true;
                     // In case image got rotated
                     $ImageWidth = $ImgParsed['Width'];
                     $ImageHeight = $ImgParsed['Height'];
                 } catch (Exception $Ex) {
                     // In case it was an image, but not a supported type - still upload
                     $MoveSuccess = @move_uploaded_file($FileTemp, $SavePath);
                 }
             } else {
                 // If not an image, just upload it
                 $MoveSuccess = @move_uploaded_file($FileTemp, $SavePath);
             }
             if (!$MoveSuccess) {
                 throw new FileUploadPluginUploadErrorException("Internal error, could not move the file.", 9, $FileName);
             }
         } else {
             $SaveFilename = $Parsed['SaveName'];
         }
         // Save Media data
         $Media = array('Name' => $FileName, 'Type' => $FileType, 'Size' => $FileSize, 'ImageWidth' => $ImageWidth, 'ImageHeight' => $ImageHeight, 'InsertUserID' => Gdn::session()->UserID, 'DateInserted' => date('Y-m-d H:i:s'), 'StorageMethod' => 'local', 'Path' => $SaveFilename);
         $MediaID = $this->mediaModel()->save($Media);
         $Media['MediaID'] = $MediaID;
         $MediaResponse = array('Status' => 'success', 'MediaID' => $MediaID, 'Filename' => $FileName, 'Filesize' => $FileSize, 'FormatFilesize' => Gdn_Format::bytes($FileSize, 1), 'ProgressKey' => $Sender->ApcKey ? $Sender->ApcKey : '', 'Thumbnail' => base64_encode(MediaThumbnail($Media)), 'FinalImageLocation' => Url(MediaModel::url($Media)), 'Parsed' => $Parsed);
     } catch (FileUploadPluginUploadErrorException $e) {
         $MediaResponse = array('Status' => 'failed', 'ErrorCode' => $e->getCode(), 'Filename' => $e->getFilename(), 'StrError' => $e->getMessage());
         if (!is_null($e->getApcKey())) {
             $MediaResponse['ProgressKey'] = $e->getApcKey();
         }
         if ($e->getFilename() != '???') {
             $MediaResponse['StrError'] = '(' . $e->getFilename() . ') ' . $MediaResponse['StrError'];
         }
     } catch (Exception $Ex) {
         $MediaResponse = array('Status' => 'failed', 'ErrorCode' => $Ex->getCode(), 'StrError' => $Ex->getMessage());
     }
     $Sender->setJSON('MediaResponse', $MediaResponse);
     // Kludge: This needs to have a content type of text/* because it's in an iframe.
     ob_clean();
     header('Content-Type: text/html');
     echo json_encode($Sender->getJson());
     die;
 }
Example #12
0
 /**
  * Create and display a thumbnail of an uploaded file.
  */
 public function utilityController_mediaThumbnail_create($sender, $media_id)
 {
     // When it makes it into core, it will be available in
     // functions.general.php
     require 'generate_thumbnail.php';
     $model = new Gdn_Model('Media');
     $media = $model->getID($media_id, DATASET_TYPE_ARRAY);
     if (!$media) {
         throw notFoundException('File');
     }
     // Get actual path to the file.
     $upload = new Gdn_UploadImage();
     $local_path = $upload->copyLocal(val('Path', $media));
     if (!file_exists($local_path)) {
         throw notFoundException('File');
     }
     $file_extension = pathinfo($local_path, PATHINFO_EXTENSION);
     // Generate new path for thumbnail
     $thumb_path = $this->getBaseUploadDestinationDir() . '/' . 'thumb';
     // Grab full path with filename, and validate it.
     $thumb_destination_path = $this->getAbsoluteDestinationFilePath($local_path, $file_extension, $thumb_path);
     // Create thumbnail, and grab debug data from whole process.
     $thumb_payload = generate_thumbnail($local_path, $thumb_destination_path, array('height' => c('Plugins.FileUpload.ThumbnailHeight', 128)));
     if ($thumb_payload['success'] === true) {
         // Thumbnail dimensions
         $thumb_height = round($thumb_payload['result_height']);
         $thumb_width = round($thumb_payload['result_width']);
         // Move the thumbnail to its proper location. Calling SaveAs with
         // cloudfiles enabled will trigger the move to cloudfiles, so use
         // same path for each arg in SaveAs. The file will be removed from the local filesystem.
         $parsed = Gdn_Upload::parse($thumb_destination_path);
         $target = $thumb_destination_path;
         // $parsed['Name'];
         $Upload = new Gdn_Upload();
         $filepath_parsed = $Upload->saveAs($thumb_destination_path, $target, array('source' => 'content'));
         // Save thumbnail information to DB.
         $model->save(array('MediaID' => $media_id, 'ThumbWidth' => $thumb_width, 'ThumbHeight' => $thumb_height, 'ThumbPath' => $filepath_parsed['SaveName']));
         // Remove cf scratch copy, typically in cftemp, if there was actually a file pulled in from CF.
         if (strpos($local_path, 'cftemp') !== false) {
             if (!unlink($local_path)) {
                 // Maybe add logging for local cf copies not deleted.
             }
         }
         $url = $filepath_parsed['Url'];
     } else {
         // Fix the thumbnail information so this isn't requested again and again.
         $model->save(array('MediaID' => $media_id, 'ImageWidth' => 0, 'ImageHeight' => 0, 'ThumbPath' => ''));
         $url = asset('/plugins/FileUpload/images/file.png');
     }
     redirect($url, 301);
 }
 /**
  * Adds the option menu to the panel asset.
  *
  * @since 2.0.0
  * @access public
  * @param string $CurrentUrl Path to highlight.
  */
 public function AddSideMenu($CurrentUrl = '')
 {
     if ($this->User !== FALSE) {
         $SideMenu = new SideMenuModule($this);
         $SideMenu->HtmlId = 'UserOptions';
         $SideMenu->AutoLinkGroups = FALSE;
         $Session = Gdn::Session();
         $ViewingUserID = $Session->UserID;
         $SideMenu->AddItem('Options', '');
         // Check that we have the necessary tools to allow image uploading
         $AllowImages = Gdn_UploadImage::CanUploadImages();
         // Is the photo hosted remotely?
         $RemotePhoto = in_array(substr($this->User->Photo, 0, 7), array('http://', 'https:/'));
         if ($this->User->UserID != $ViewingUserID) {
             // Include user js files for people with edit users permissions
             if ($Session->CheckPermission('Garden.Users.Edit')) {
                 //              $this->AddJsFile('jquery.gardenmorepager.js');
                 $this->AddJsFile('user.js');
             }
             // Add profile options for everyone
             $SideMenu->AddLink('Options', T('Change Picture'), '/profile/picture/' . $this->User->UserID . '/' . Gdn_Format::Url($this->User->Name), 'Garden.Users.Edit', array('class' => 'PictureLink'));
             if ($this->User->Photo != '' && $AllowImages && !$RemotePhoto) {
                 $SideMenu->AddLink('Options', T('Edit Thumbnail'), '/profile/thumbnail/' . $this->User->UserID . '/' . Gdn_Format::Url($this->User->Name), 'Garden.Users.Edit', array('class' => 'ThumbnailLink'));
                 $SideMenu->AddLink('Options', T('Remove Picture'), '/profile/removepicture/' . $this->User->UserID . '/' . Gdn_Format::Url($this->User->Name) . '/' . $Session->TransientKey(), 'Garden.Users.Edit', array('class' => 'RemovePictureLink'));
             }
             $SideMenu->AddLink('Options', T('Edit Account'), '/user/edit/' . $this->User->UserID, 'Garden.Users.Edit', array('class' => 'Popup EditAccountLink'));
             $SideMenu->AddLink('Options', T('Delete Account'), '/user/delete/' . $this->User->UserID, 'Garden.Users.Delete', array('class' => 'Popup DeleteAccountLink'));
             if ($this->User->Photo != '' && $AllowImages) {
                 $SideMenu->AddLink('Options', T('Remove Picture'), '/profile/removepicture/' . $this->User->UserID . '/' . Gdn_Format::Url($this->User->Name) . '/' . $Session->TransientKey(), 'Garden.Users.Edit', array('class' => 'RemovePictureLink'));
             }
             $SideMenu->AddLink('Options', T('Edit Preferences'), '/profile/preferences/' . $this->User->UserID . '/' . Gdn_Format::Url($this->User->Name), 'Garden.Users.Edit', array('class' => 'Popup PreferencesLink'));
         } else {
             // Add profile options for the profile owner
             if ($AllowImages) {
                 $SideMenu->AddLink('Options', T('Change My Picture'), '/profile/picture', 'Garden.Profiles.Edit', array('class' => 'PictureLink'));
             }
             if ($this->User->Photo != '' && $AllowImages && !$RemotePhoto) {
                 $SideMenu->AddLink('Options', T('Edit My Thumbnail'), '/profile/thumbnail', 'Garden.Profiles.Edit', array('class' => 'ThumbnailLink'));
                 $SideMenu->AddLink('Options', T('Remove My Picture'), '/profile/removepicture/' . $Session->UserID . '/' . Gdn_Format::Url($Session->User->Name) . '/' . $Session->TransientKey(), 'Garden.Profiles.Edit', array('class' => 'RemovePictureLink'));
             }
             // Don't allow account editing if it has been turned off.
             if (Gdn::Config('Garden.UserAccount.AllowEdit')) {
                 $SideMenu->AddLink('Options', T('Edit My Account'), '/profile/edit', FALSE, array('class' => 'Popup EditAccountLink'));
                 // No password may have been set if they have only signed in with a connect plugin
                 $passwordLabel = T('Change My Password');
                 if ($this->User->HashMethod && $this->User->HashMethod != "Vanilla") {
                     $passwordLabel = T('Set A Password');
                 }
                 $SideMenu->AddLink('Options', $passwordLabel, '/profile/password', FALSE, array('class' => 'Popup PasswordLink'));
             }
             if (Gdn::Config('Garden.Registration.Method') == 'Invitation') {
                 $SideMenu->AddLink('Options', T('My Invitations'), '/profile/invitations', FALSE, array('class' => 'Popup InvitationsLink'));
             }
             $SideMenu->AddLink('Options', T('My Preferences'), '/profile/preferences/' . $this->User->UserID . '/' . Gdn_Format::Url($this->User->Name), FALSE, array('class' => 'Popup PreferencesLink'));
         }
         $this->EventArguments['SideMenu'] =& $SideMenu;
         $this->FireEvent('AfterAddSideMenu');
         $this->AddModule($SideMenu, 'Panel');
     }
 }
 /**
  * Adds the option menu to the panel asset.
  */
 public function AddSideMenu($CurrentUrl = '')
 {
     if ($this->User !== FALSE) {
         $SideMenu = new SideMenuModule($this);
         $SideMenu->HtmlId = 'UserOptions';
         $SideMenu->AutoLinkGroups = FALSE;
         $Session = Gdn::Session();
         $ViewingUserID = $Session->UserID;
         $SideMenu->AddItem('Options', '');
         // Check that we have the necessary tools to allow image uploading
         $AllowImages = Gdn_UploadImage::CanUploadImages();
         if ($this->User->UserID != $ViewingUserID) {
             // Include user js files for people with edit users permissions
             if ($Session->CheckPermission('Garden.Users.Edit')) {
                 $this->AddJsFile('jquery.gardenmorepager.js');
                 $this->AddJsFile('user.js');
             }
             // Add profile options for everyone
             //$SideMenu->AddLink('Options', T('Change Picture'), '/profile/picture/'.$this->User->UserID.'/'.Gdn_Format::Url($this->User->Name), 'Garden.Users.Edit', array('class' => 'PictureLink'));
             /*if ($this->User->Photo != '' && $AllowImages) {
                  $SideMenu->AddLink('Options', T('Edit Thumbnail'), '/profile/thumbnail/'.$this->User->UserID.'/'.Gdn_Format::Url($this->User->Name), 'Garden.Users.Edit', array('class' => 'ThumbnailLink'));
                  $SideMenu->AddLink('Options', T('Remove Picture'), '/profile/removepicture/'.$this->User->UserID.'/'.Gdn_Format::Url($this->User->Name).'/'.$Session->TransientKey(), 'Garden.Users.Edit', array('class' => 'RemovePictureLink'));
               }*/
             //$SideMenu->AddLink('Options', T('Edit Account'), '/user/edit/'.$this->User->UserID, 'Garden.Users.Edit', array('class' => 'Popup'));
             //$SideMenu->AddLink('Options', T('Delete Account'), '/user/delete/'.$this->User->UserID, 'Garden.Users.Delete');
             //if ($this->User->Photo != '' && $AllowImages)
             //$SideMenu->AddLink('Options', T('Remove Picture'), '/profile/removepicture/'.$this->User->UserID.'/'.Gdn_Format::Url($this->User->Name).'/'.$Session->TransientKey(), 'Garden.Users.Edit', array('class' => 'RemovePictureLink'));
             //$SideMenu->AddLink('Options', T('Edit Preferences'), '/profile/preferences/'.$this->User->UserID.'/'.Gdn_Format::Url($this->User->Name), 'Garden.Users.Edit', array('class' => 'Popup'));
         } else {
             // Add profile options for the profile owner
             //if ($AllowImages)
             //$SideMenu->AddLink('Options', T('Change My Picture'), '/profile/picture', FALSE, array('class' => 'PictureLink'));
             if ($this->User->Photo != '' && $AllowImages) {
                 //$SideMenu->AddLink('Options', T('Edit My Thumbnail'), '/profile/thumbnail', FALSE, array('class' => 'ThumbnailLink'));
                 //$SideMenu->AddLink('Options', T('Remove My Picture'), '/profile/removepicture/'.$Session->UserID.'/'.Gdn_Format::Url($Session->User->Name).'/'.$Session->TransientKey(), FALSE, array('class' => 'RemovePictureLink'));
             }
             // Don't allow account editing if it has been turned off.
             if (Gdn::Config('Garden.UserAccount.AllowEdit')) {
                 //$SideMenu->AddLink('Options', T('Edit My Account'), '/profile/edit', FALSE, array('class' => 'Popup'));
                 //$SideMenu->AddLink('Options', T('Change My Password'), '/profile/password', FALSE, array('class' => 'Popup'));
             }
             //if (Gdn::Config('Garden.Registration.Method') == 'Invitation')
             //$SideMenu->AddLink('Options', T('My Invitations'), '/profile/invitations', FALSE, array('class' => 'Popup'));
             $SideMenu->AddLink('Options', T('My Preferences'), '/profile/preferences/' . $this->User->UserID . '/' . Gdn_Format::Url($this->User->Name), FALSE, array('class' => 'Popup'));
         }
         $this->EventArguments['SideMenu'] =& $SideMenu;
         $this->FireEvent('AfterAddSideMenu');
         $this->AddModule($SideMenu, 'Panel');
     }
 }
 /**
  * Save an icon image file.
  *
  * @param string $imageLocation Where to save the icon to file.
  * @return mixed
  * @throws Exception Unable to save icon or GD is not installed.
  */
 protected function saveIcon($imageLocation)
 {
     $uploadImage = new Gdn_UploadImage();
     // Generate the target image name
     $extension = val('extension', pathinfo($imageLocation), '');
     $targetLocation = $uploadImage->generateTargetName('addons/icons', $extension);
     // Save the uploaded icon
     $parsed = $uploadImage->saveImageAs($imageLocation, $targetLocation, 256, 256, false, false);
     return $parsed['SaveName'];
 }
 /**
  * Endpoint for retrieving current email image url.
  */
 public function emailImageUrl()
 {
     $this->deliveryMethod(DELIVERY_METHOD_JSON);
     $this->deliveryType(DELIVERY_TYPE_DATA);
     $image = c('Garden.EmailTemplate.Image');
     if ($image) {
         $image = Gdn_UploadImage::url($image);
     }
     $this->setData('EmailImage', $image);
     $this->render();
 }
Example #17
0
 public function UtilityController_Thumbnail_Create($Sender, $Args)
 {
     $SubPath = implode('/', $Args);
     $Path = MediaModel::PathUploads() . "/{$SubPath}";
     if (!file_exists($Path)) {
         throw NotFoundException('File');
     }
     // Figure out the dimensions of the upload.
     $ImageSize = getimagesize($Path);
     $SHeight = $ImageSize[1];
     $SWidth = $ImageSize[0];
     $Options = array();
     $ThumbHeight = MediaModel::ThumbnailHeight();
     $ThumbWidth = MediaModel::ThumbnailWidth();
     if (!$ThumbHeight || $SHeight < $ThumbHeight) {
         $Height = $SHeight;
         $Width = $SWidth;
     } else {
         $Height = $ThumbHeight;
         $Width = round($Height * $SWidth / $SHeight);
     }
     if ($ThumbWidth && $Width > $ThumbWidth) {
         $Width = $ThumbWidth;
         if (!$ThumbHeight) {
             $Height = round($Width * $SHeight / $SWidth);
         } else {
             $Options['Crop'] = TRUE;
         }
     }
     $TargetPath = MediaModel::PathUploads() . "/thumbnails/{$SubPath}";
     if (!file_exists(dirname($TargetPath))) {
         mkdir(dirname($TargetPath), 0777, TRUE);
     }
     Gdn_UploadImage::SaveImageAs($Path, $TargetPath, $Height, $Width, $Options);
     $Url = MediaModel::Url("/thumbnails/{$SubPath}");
     Redirect($Url, 302);
     //      Gdn_FileSystem::ServeFile($TargetPath, basename($Path), '', 'inline');
 }
 /**
  * Banner management screen.
  *
  * @since 2.0.0
  * @access public
  */
 public function Banner()
 {
     $this->Permission('Garden.Settings.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 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 {
         // Define some validation rules for the fields being saved
         $ConfigurationModel->Validation->ApplyRule('Garden.Title', 'Required');
         $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);
                 }
                 $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();
 }
Example #19
0
 /**
  * Retrieves default values for the email image.
  *
  * @return array An array representing an image.
  */
 public function getDefaultEmailImage()
 {
     $image = array();
     if (c('Garden.EmailTemplate.Image', '')) {
         $image['source'] = Gdn_UploadImage::url(c('Garden.EmailTemplate.Image'));
     }
     $image['link'] = url('/', true);
     $image['alt'] = c('Garden.LogoTitle', c('Garden.Title', ''));
     return $image;
 }
Example #20
0
 function ThumbnailImage($Data, $Attributes = False)
 {
     if (function_exists('Debug') && Debug()) {
         Deprecated(__FUNCTION__, 'Thumbnail');
     }
     $Width = ArrayValue('width', $Attributes, '');
     $Height = ArrayValue('height', $Attributes, '');
     if (Is_Array($Data)) {
         // group, todo
         // <ul><li><a></a></li>
     }
     $Prefix = substr($Data, 0, 7);
     //if(In_Array($Prefix, array('http://', 'https:/'))) {}
     //$bLocalImage = False;
     if ($Prefix != 'http://') {
         //$bLocalImage = True;
         $IncomingImage = $Data;
         $ImageFindPaths[] = 'uploads' . DS . $Data;
         $ImageFindPaths[] = $Data;
         foreach ($ImageFindPaths as $File) {
             if (file_exists($File) && is_file($File)) {
                 $IncomingImage = $File;
                 break;
             }
         }
     } else {
         $IncomingImage = $Data;
     }
     $CacheDirectory = 'uploads/cached';
     if (!is_writable($CacheDirectory)) {
         mkdir($CacheDirectory, 0777, True);
         if (!is_writable($CacheDirectory)) {
             $ErrorMessage = ErrorMessage(sprintf(T('Directory (%s) is not writable.'), $CacheDirectory), 'PHP', __FUNCTION__);
             trigger_error($ErrorMessage, E_USER_ERROR);
             return '';
         }
     }
     $Name = CleanupString(pathinfo($IncomingImage, PATHINFO_FILENAME) . ' ' . $Width . ' ' . $Height);
     $Extension = FileExtension($IncomingImage);
     $Target = $CacheDirectory . DS . $Name . '.' . $Extension;
     if (!file_exists($Target)) {
         Gdn_UploadImage::SaveImageAs($IncomingImage, $Target, $Height, $Width);
     }
     $Target = str_replace(DS, '/', $Target);
     if (!array_key_exists('alt', $Attributes)) {
         $Attributes['alt'] = pathinfo($Name, PATHINFO_FILENAME);
     }
     list($Width, $Height, $Type) = GetImageSize($IncomingImage);
     $Attributes['alt'] .= sprintf(' (%d×%d)', $Width, $Height);
     $Image = Img($Target, $Attributes);
     return Anchor($Image, Url($IncomingImage), '', '', True);
 }
 function FancyZoomImage($Source, $Attributes = array())
 {
     // defaults
     if (!is_array($Attributes)) {
         $Attributes = array();
     }
     $NoHiding = GetValue('NoHiding', $Attributes, '', True);
     $bSaveImage = False;
     $Hash = Crc32Value($Source, $Attributes);
     $Filename = pathinfo($Source, PATHINFO_FILENAME);
     $Extension = pathinfo($Source, PATHINFO_EXTENSION);
     if (!array_key_exists('SmallImage', $Attributes)) {
         // make directory
         $TargetFolder = 'uploads/cached';
         // cache directory
         if (!is_dir($TargetFolder)) {
             mkdir($TargetFolder, 0777, True);
         }
         $SmallImage = GenerateCleanTargetName($TargetFolder, $Filename . '-' . $Hash, $Extension, False, True);
         $Attributes['SmallImage'] = $SmallImage;
         if (!file_exists($SmallImage)) {
             $bSaveImage = True;
         }
     }
     // get attributes
     $Width = ArrayValue('width', $Attributes, '');
     $Height = ArrayValue('height', $Attributes, '');
     $Crop = GetValue('Crop', $Attributes, False, True);
     $SmallImage = GetValue('SmallImage', $Attributes, '', True);
     $ZoomAttributes = array('id' => 'p' . $Hash);
     if (!$NoHiding) {
         $ZoomAttributes['style'] = 'display:none';
     }
     //if (!array_key_exists('alt', $Attributes)) $Attributes['alt'] = $Filename;
     TouchValue('alt', $Attributes, $Filename);
     if ($bSaveImage) {
         Gdn_UploadImage::SaveImageAs($Source, $SmallImage, $Height, $Width, $Crop);
     }
     $SmallImage = Img($SmallImage, $Attributes);
     $ZoomImage = Img($Source, array('alt' => ArrayValue('alt', $Attributes, '')));
     return "\n" . Wrap($SmallImage, 'a', array('href' => '#p' . $Hash)) . Wrap($ZoomImage, 'div', $ZoomAttributes);
 }
 /**
  *
  *
  * @param PostController $Sender
  * @param array $Args
  */
 public function postController_editorUpload_create($Sender, $Args = array())
 {
     // @Todo Move to a library/functions file.
     require 'generate_thumbnail.php';
     // Grab raw upload data ($_FILES), essentially. It's only needed
     // because the methods on the Upload class do not expose all variables.
     $fileData = Gdn::request()->getValueFrom(Gdn_Request::INPUT_FILES, $this->editorFileInputName, false);
     $discussionID = $Sender->Request->post('DiscussionID') ? $Sender->Request->post('DiscussionID') : '';
     // JSON payload of media info will get sent back to the client.
     $json = array('error' => 1, 'feedback' => 'There was a problem.', 'errors' => array(), 'payload' => array());
     // New upload instance
     $Upload = new Gdn_Upload();
     // This will validate, such as size maxes, file extensions. Upon doing
     // this, $_FILES is set as a protected property, so all the other Gdn_Upload methods work on it.
     $tmpFilePath = $Upload->validateUpload($this->editorFileInputName);
     // Get base destination path for editor uploads
     $this->editorBaseUploadDestinationDir = $this->getBaseUploadDestinationDir();
     // Pass path, if doesn't exist, will create, and determine if valid.
     $canUpload = Gdn_Upload::canUpload($this->editorBaseUploadDestinationDir);
     if ($tmpFilePath && $canUpload) {
         $fileExtension = strtolower($Upload->getUploadedFileExtension());
         $fileName = $Upload->getUploadedFileName();
         list($tmpwidth, $tmpheight, $imageType) = getimagesize($tmpFilePath);
         // This will return the absolute destination path, including generated
         // filename based on md5_file, and the full path. It
         // will create a filename, with extension, and check if its dir can be writable.
         $absoluteFileDestination = $this->getAbsoluteDestinationFilePath($tmpFilePath, $fileExtension);
         // Save original file to uploads, then manipulate from this location if
         // it's a photo. This will also call events in Vanilla so other plugins can tie into this.
         if (empty($imageType)) {
             $filePathParsed = $Upload->saveAs($tmpFilePath, $absoluteFileDestination, array('source' => 'content'));
         } else {
             $filePathParsed = Gdn_UploadImage::saveImageAs($tmpFilePath, $absoluteFileDestination, '', '', array('SaveGif' => true));
             $tmpwidth = $filePathParsed['Width'];
             $tmpheight = $filePathParsed['Height'];
         }
         // Determine if image, and thus requires thumbnail generation, or simply saving the file.
         // Not all files will be images.
         $thumbHeight = '';
         $thumbWidth = '';
         $imageHeight = '';
         $imageWidth = '';
         $thumbPathParsed = array('SaveName' => '');
         $thumbUrl = '';
         // This is a redundant check, because it's in the thumbnail function,
         // but there's no point calling it blindly on every file, so just check here before calling it.
         $generate_thumbnail = false;
         if (in_array($fileExtension, array('jpg', 'jpeg', 'gif', 'png', 'bmp', 'ico'))) {
             $imageHeight = $tmpheight;
             $imageWidth = $tmpwidth;
             $generate_thumbnail = true;
         }
         // Save data to database using model with media table
         $Model = new Gdn_Model('Media');
         // Will be passed to model for database insertion/update. All thumb vars will be empty.
         $Media = array('Name' => $fileName, 'Type' => $fileData['type'], 'Size' => $fileData['size'], 'ImageWidth' => $imageWidth, 'ImageHeight' => $imageHeight, 'ThumbWidth' => $thumbWidth, 'ThumbHeight' => $thumbHeight, 'InsertUserID' => Gdn::session()->UserID, 'DateInserted' => date('Y-m-d H:i:s'), 'StorageMethod' => 'local', 'Path' => $filePathParsed['SaveName'], 'ThumbPath' => $thumbPathParsed['SaveName']);
         // Get MediaID and pass it to client in payload.
         $MediaID = $Model->save($Media);
         $Media['MediaID'] = $MediaID;
         if ($generate_thumbnail) {
             $thumbUrl = url('/utility/mediathumbnail/' . $MediaID, true);
         }
         $payload = array('MediaID' => $MediaID, 'Filename' => htmlspecialchars($fileName), 'Filesize' => $fileData['size'], 'FormatFilesize' => Gdn_Format::bytes($fileData['size'], 1), 'type' => $fileData['type'], 'Thumbnail' => '', 'FinalImageLocation' => '', 'Parsed' => $filePathParsed, 'Media' => (array) $Media, 'original_url' => $Upload->url($filePathParsed['SaveName']), 'thumbnail_url' => $thumbUrl, 'original_width' => $imageWidth, 'original_height' => $imageHeight);
         $json = array('error' => 0, 'feedback' => 'Editor received file successfully.', 'payload' => $payload);
     }
     // Return JSON payload
     echo json_encode($json);
 }
 /**
  * @param SideMenuModule $Module
  * @param string $CurrentUrl
  */
 public function BuildEditMenu(&$Module, $CurrentUrl = '')
 {
     if (!$this->User) {
         return;
     }
     $Module->HtmlId = 'UserOptions';
     $Module->AutoLinkGroups = FALSE;
     $Session = Gdn::Session();
     $ViewingUserID = $Session->UserID;
     $Module->AddItem('Options', '', FALSE, array('class' => 'SideMenu'));
     // Check that we have the necessary tools to allow image uploading
     $AllowImages = C('Garden.Profile.EditPhotos', TRUE) && Gdn_UploadImage::CanUploadImages();
     // Is the photo hosted remotely?
     $RemotePhoto = IsUrl($this->User->Photo);
     if ($this->User->UserID != $ViewingUserID) {
         // Include user js files for people with edit users permissions
         if (CheckPermission('Garden.Users.Edit') || CheckPermission('Moderation.Profiles.Edit')) {
             //              $this->AddJsFile('jquery.gardenmorepager.js');
             $this->AddJsFile('user.js');
         }
         $Module->AddLink('Options', Sprite('SpProfile') . ' ' . T('Edit Profile'), UserUrl($this->User, '', 'edit'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'Popup EditAccountLink'));
         $Module->AddLink('Options', Sprite('SpProfile') . ' ' . T('Edit Account'), '/user/edit/' . $this->User->UserID, 'Garden.Users.Edit', array('class' => 'Popup EditAccountLink'));
         $Module->AddLink('Options', Sprite('SpDelete') . ' ' . T('Delete Account'), '/user/delete/' . $this->User->UserID, 'Garden.Users.Delete', array('class' => 'Popup DeleteAccountLink'));
         if ($this->User->Photo != '' && $AllowImages) {
             $Module->AddLink('Options', Sprite('SpDelete') . ' ' . T('Remove Picture'), CombinePaths(array(UserUrl($this->User, '', 'removepicture'), $Session->TransientKey())), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'RemovePictureLink'));
         }
         $Module->AddLink('Options', Sprite('SpPreferences') . ' ' . T('Edit Preferences'), UserUrl($this->User, '', 'preferences'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'Popup PreferencesLink'));
         // Add profile options for everyone
         $Module->AddLink('Options', Sprite('SpPicture') . ' ' . T('Change Picture'), UserUrl($this->User, '', 'picture'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'PictureLink'));
         if ($this->User->Photo != '' && $AllowImages && !$RemotePhoto) {
             $Module->AddLink('Options', Sprite('SpThumbnail') . ' ' . T('Edit Thumbnail'), UserUrl($this->User, '', 'thumbnail'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'ThumbnailLink'));
         }
     } else {
         // Add profile options for the profile owner
         // Don't allow account editing if it has been turned off.
         // Don't allow password editing if using SSO Connect ONLY.
         // This is for security. We encountered the case where a customer charges
         // for membership using their external application and use SSO to let
         // their customers into Vanilla. If you allow those people to change their
         // password in Vanilla, they will then be able to log into Vanilla using
         // Vanilla's login form regardless of the state of their membership in the
         // external app.
         if (C('Garden.UserAccount.AllowEdit') && C('Garden.Registration.Method') != 'Connect') {
             $Module->AddLink('Options', Sprite('SpEdit') . ' ' . T('Edit Profile'), '/profile/edit', FALSE, array('class' => 'Popup EditAccountLink'));
             // No password may have been set if they have only signed in with a connect plugin
             $PasswordLabel = T('Change My Password');
             if ($this->User->HashMethod && $this->User->HashMethod != "Vanilla") {
                 $PasswordLabel = T('Set A Password');
             }
             $Module->AddLink('Options', Sprite('SpPassword') . ' ' . $PasswordLabel, '/profile/password', FALSE, array('class' => 'Popup PasswordLink'));
         }
         $Module->AddLink('Options', Sprite('SpPreferences') . ' ' . T('Notification Preferences'), UserUrl($this->User, '', 'preferences'), FALSE, array('class' => 'Popup PreferencesLink'));
         if ($AllowImages) {
             $Module->AddLink('Options', Sprite('SpPicture') . ' ' . T('Change My Picture'), '/profile/picture', array('Garden.Profiles.Edit', 'Garden.ProfilePicture.Edit'), array('class' => 'PictureLink'));
         }
         if ($this->User->Photo != '' && $AllowImages && !$RemotePhoto) {
             $Module->AddLink('Options', Sprite('SpThumbnail') . ' ' . T('Edit My Thumbnail'), '/profile/thumbnail', array('Garden.Profiles.Edit', 'Garden.ProfilePicture.Edit'), array('class' => 'ThumbnailLink'));
         }
     }
     if ($this->User->UserID == $ViewingUserID || $Session->CheckPermission('Garden.Users.Edit')) {
         $this->SetData('Connections', array());
         $this->EventArguments['User'] = $this->User;
         $this->FireEvent('GetConnections');
         if (count($this->Data('Connections')) > 0) {
             $Module->AddLink('Options', Sprite('SpConnection') . ' ' . T('Social'), '/profile/connections', 'Garden.SignIn.Allow');
         }
     }
 }