Exemplo n.º 1
0
 public function buildThumb($mediaID, $thumbURL)
 {
     $targetLoc = XenForo_Helper_File::getExternalDataPath() . '/media/' . $mediaID . '.jpg';
     $thumbLoc = XenForo_Helper_File::getTempDir() . '/media' . $mediaID;
     if (substr($thumbURL, 0, 7) == 'http://') {
         $client = new Zend_Http_Client($thumbURL);
         $response = $client->request();
         $image = $response->getBody();
         file_put_contents($thumbLoc, $image);
     } else {
         copy($thumbURL, $thumbLoc);
     }
     $imageInfo = getimagesize($thumbLoc);
     if ($image = XenForo_Image_Abstract::createFromFile($thumbLoc, $imageInfo[2])) {
         $ratio = 160 / 90;
         $width = $image->getWidth();
         $height = $image->getHeight();
         if ($width / $height > $ratio) {
             $image->thumbnail($width, '90');
         } else {
             $image->thumbnail('160', $height);
         }
         $width = $image->getWidth();
         $height = $image->getHeight();
         $offWidth = ($width - 160) / 2;
         $offHeight = ($height - 90) / 2;
         $image->crop($offWidth, $offHeight, '160', '90');
         $image->output(IMAGETYPE_JPEG, $targetLoc);
     }
     if (file_exists($thumbLoc)) {
         unlink($thumbLoc);
     }
 }
Exemplo n.º 2
0
 public function renderRaw()
 {
     $url = $this->_params['url'];
     $width = $this->_params['width'];
     $height = $this->_params['height'];
     $crop = $this->_params['crop'];
     $extension = XenForo_Helper_File::getFileExtension($url);
     $imageInfo = @getimagesize($url);
     if (!$imageInfo || !in_array($imageInfo[2], array_values(sonnb_XenGallery_Model_PhotoData::$typeMap)) || !in_array(strtolower($extension), array_keys(sonnb_XenGallery_Model_PhotoData::$imageMimes))) {
         $url = XenForo_Template_Helper_Core::getAvatarUrl(array(), 'l');
         $extension = XenForo_Helper_File::getFileExtension($url);
         $imageInfo = @getimagesize($url);
     }
     $this->_response->setHeader('Content-type', sonnb_XenGallery_Model_PhotoData::$imageMimes[$extension], true);
     $this->_response->setHeader('ETag', XenForo_Application::$time, true);
     $this->_response->setHeader('X-Content-Type-Options', 'nosniff');
     $this->setDownloadFileName($url, true);
     $image = XenForo_Image_Abstract::createFromFile($url, sonnb_XenGallery_Model_PhotoData::$typeMap[$extension]);
     if ($image) {
         if (XenForo_Image_Abstract::canResize($width, $height)) {
             if ($crop) {
                 $image->thumbnail($width * 2, $height * 2);
                 $image->crop(0, 0, $width, $height);
             } else {
                 $image->thumbnail($width, $height);
             }
         } else {
             $image->output(sonnb_XenGallery_Model_PhotoData::$typeMap[$extension]);
         }
     }
 }
Exemplo n.º 3
0
 protected static function _applyIcon($node, $upload, $number, $size, $nodeType)
 {
     if (!$upload->isValid()) {
         throw new XenForo_Exception($upload->getErrors(), true);
     }
     if (!$upload->isImage()) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     $imageType = $upload->getImageInfoField('type');
     if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     $outputFiles = array();
     $fileName = $upload->getTempFile();
     $imageType = $upload->getImageInfoField('type');
     $outputType = $imageType;
     $width = $upload->getImageInfoField('width');
     $height = $upload->getImageInfoField('height');
     $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfa');
     $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
     if (!$image) {
         continue;
     }
     if ($size > 0) {
         $image->thumbnailFixedShorterSide($size);
         if ($image->getOrientation() != XenForo_Image_Abstract::ORIENTATION_SQUARE) {
             $x = floor(($image->getWidth() - $size) / 2);
             $y = floor(($image->getHeight() - $size) / 2);
             $image->crop($x, $y, $size, $size);
         }
     }
     $image->output($outputType, $newTempFile, self::$imageQuality);
     unset($image);
     $icons = $newTempFile;
     switch ($nodeType) {
         case 'forum':
             $dw = XenForo_DataWriter::create('XenForo_DataWriter_Forum');
             $dwData = array('brcns_pixel_' . $number => $size, 'brcns_icon_date_' . $number => XenForo_Application::$time, 'brcns_select' => 'file');
             break;
         case 'page':
             $dw = XenForo_DataWriter::create('XenForo_DataWriter_Page');
             $dwData = array('brcns_pixel' => $size, 'brcns_icon_date' => XenForo_Application::$time, 'brcns_select' => 'file');
             break;
         case 'link':
             $dw = XenForo_DataWriter::create('XenForo_DataWriter_LinkForum');
             $dwData = array('brcns_pixel' => $size, 'brcns_icon_date' => XenForo_Application::$time, 'brcns_select' => 'file');
             break;
         case 'category':
             $dw = XenForo_DataWriter::create('XenForo_DataWriter_Category');
             $dwData = array('brcns_pixel' => $size, 'brcns_icon_date' => XenForo_Application::$time, 'brcns_select' => 'file');
             break;
     }
     $dw->setExistingData($node['node_id']);
     $dw->bulkSet($dwData);
     $dw->save();
     return $icons;
 }
 public function execute(array $deferred, array $data, $targetRunTime, &$status)
 {
     $data = array_merge(array('batch' => 100, 'position' => 0), $data);
     /* @var $attachmentModel XenForo_Model_Attachment */
     $attachmentModel = XenForo_Model::create('XenForo_Model_Attachment');
     $s = microtime(true);
     $dataIds = $attachmentModel->getAttachmentDataIdsInRange($data['position'], $data['batch']);
     if (sizeof($dataIds) == 0) {
         return false;
     }
     foreach ($dataIds as $dataId) {
         $data['position'] = $dataId;
         $dw = XenForo_DataWriter::create('XenForo_DataWriter_AttachmentData', XenForo_DataWriter::ERROR_SILENT);
         if ($dw->setExistingData($dataId) && $dw->get('width') && XenForo_Image_Abstract::canResize($dw->get('width'), $dw->get('height'))) {
             $attach = $dw->getMergedData();
             $attachFile = $attachmentModel->getAttachmentDataFilePath($attach);
             $imageInfo = @getimagesize($attachFile);
             if ($imageInfo) {
                 try {
                     $image = XenForo_Image_Abstract::createFromFile($attachFile, $imageInfo[2]);
                 } catch (Exception $e) {
                     XenForo_Error::logException($e, false, "Thumbnail rebuild error {$attachFile}: ");
                     continue;
                 }
                 if ($image) {
                     if ($image->thumbnail(XenForo_Application::get('options')->attachmentThumbnailDimensions)) {
                         ob_start();
                         $image->output($imageInfo[2]);
                         $thumbData = ob_get_contents();
                         ob_end_clean();
                     } else {
                         // no resize necessary, use the original
                         $thumbData = file_get_contents($attachFile);
                     }
                     $dw->set('thumbnail_width', $image->getWidth());
                     $dw->set('thumbnail_height', $image->getHeight());
                     $dw->setExtraData(XenForo_DataWriter_AttachmentData::DATA_THUMB_DATA, $thumbData);
                     try {
                         $dw->save();
                     } catch (Exception $e) {
                         XenForo_Error::logException($e, false, "Thumb rebuild for #{$dataId}: ");
                     }
                     unset($image);
                 }
             }
         }
         if ($targetRunTime && microtime(true) - $s > $targetRunTime) {
             break;
         }
     }
     $actionPhrase = new XenForo_Phrase('rebuilding');
     $typePhrase = new XenForo_Phrase('attachment_thumbnails');
     $status = sprintf('%s... %s (%s)', $actionPhrase, $typePhrase, XenForo_Locale::numberFormat($data['position']));
     return $data;
 }
Exemplo n.º 5
0
 /**
  *
  * @see XenResource_Model_Resource::applyResourceIcon()
  *
  */
 public function applyResourceIcon($resourceId, $fileName, $imageType = false, $width = false, $height = false)
 {
     if (!$imageType || !$width || !$height) {
         $imageInfo = getimagesize($fileName);
         if (!$imageInfo) {
             return parent::applyResourceIcon($resourceId, $fileName, $imageType, $width, $height);
         }
         $width = $imageInfo[0];
         $height = $imageInfo[1];
         $imageType = $imageInfo[2];
     }
     if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
         return parent::applyResourceIcon($resourceId, $fileName, $imageType, $width, $height);
     }
     if (!XenForo_Image_Abstract::canResize($width, $height)) {
         return parent::applyResourceIcon($resourceId, $fileName, $imageType, $width, $height);
     }
     $imageQuality = self::$iconQuality;
     $outputType = $imageType;
     $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
     if (!$image) {
         return false;
     }
     $maxDimensions = max(array($image->getWidth(), $image->getHeight()));
     if ($image->getOrientation() != XenForo_Image_Abstract::ORIENTATION_SQUARE) {
         $x = floor(($maxDimensions - $image->getWidth()) / 2);
         $y = floor(($maxDimensions - $image->getHeight()) / 2);
         $image->resizeCanvas($x, $y, $maxDimensions, $maxDimensions);
     }
     $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     if (!$newTempFile) {
         return false;
     }
     $image->output($outputType, $newTempFile, $imageQuality);
     unset($image);
     $returnValue = parent::applyResourceIcon($resourceId, $newTempFile, $imageType, $width, $height);
     if ($returnValue) {
         $filePath = $this->getResourceIconFilePath($resourceId);
         $image = XenForo_Image_Abstract::createFromFile($filePath, $imageType);
         if (!$image) {
             return false;
         }
         $width = XenForo_Application::get('options')->th_resourceIcons_width;
         $height = XenForo_Application::get('options')->th_resourceIcons_height;
         $x = floor(($width - $image->getWidth()) / 2);
         $y = floor(($height - $image->getHeight()) / 2);
         $image->resizeCanvas($x, $y, $width, $height);
         $image->output($outputType, $filePath, $imageQuality);
         unset($image);
     }
 }
Exemplo n.º 6
0
 public function applyCoverCrop($teamId, $coverDate, array $crops)
 {
     $filePath = $this->getCoverPhotoFilePath($teamId);
     $imageInfo = @getimagesize($filePath);
     $team = $this->getModelFromCache('Nobita_Teams_Model_Team')->getFullTeamById($teamId);
     if (!$team) {
         throw new Nobita_Teams_Exception_Abstract("Invalid team ID.");
         return false;
     }
     $outputFile = $this->getCoverCropFilePath($teamId, $coverDate);
     $imageType = $imageInfo[2];
     $image = XenForo_Image_Abstract::createFromFile($filePath, $imageType);
     if (!$image) {
         return false;
     }
     $relativeWidth = $crops['crop_w'];
     $relativeHeight = $crops['crop_h'];
     $image->thumbnail($relativeWidth);
     if ($image->getHeight() > $relativeHeight) {
         $cropWidth = $relativeWidth;
         $cropHeight = $relativeHeight;
         $image->crop($crops['crop_x'], $crops['crop_y'], $cropWidth, $cropHeight);
     }
     $coverQuality = intval(Nobita_Teams_Setup::getInstance()->getOption('coverQuality'));
     $success = $image->output($imageType, $outputFile, $coverQuality);
     $data = @unserialize($team['cover_crop_details']);
     if ($imageInfo) {
         if (!isset($crops['height'])) {
             $crops['height'] = $imageInfo[1];
         }
         if (!isset($crops['width'])) {
             $crops['width'] = $imageInfo[0];
         }
     } else {
         $crops['height'] = $data['height'];
         $crops['width'] = $data['width'];
     }
     $dw = XenForo_DataWriter::create('Nobita_Teams_DataWriter_Team');
     $dw->setExistingData($teamId);
     $dw->set('cover_crop_details', $crops);
     $dw->save();
     return $crops;
 }
Exemplo n.º 7
0
 public function insertAvatar($filePath, $userId, $permissions)
 {
     if (!$userId) {
         throw new XenForo_Exception('Missing user ID.');
     }
     if ($permissions !== false && !is_array($permissions)) {
         throw new XenForo_Exception('Invalid permission set.');
     }
     $data = getimagesize($filePath);
     $imageType = $data[2];
     $image = XenForo_Image_Abstract::createFromFile($filePath, $imageType);
     if (!$image) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     $width = $image->getWidth();
     $height = $image->getHeight();
     return $this->applyAvatar($userId, $filePath, $imageType, $width, $height, $permissions);
 }
Exemplo n.º 8
0
 /**
  * Checks the state of the upload to determine if it's
  * a valid image.
  */
 protected function _checkImageState()
 {
     if ($this->_imageInfo !== null) {
         return;
     }
     $this->_imageInfo = false;
     // default to not an image
     if (!$this->_tempFile) {
         return;
     }
     $imageInfo = @getimagesize($this->_tempFile);
     if (!$imageInfo) {
         return;
     }
     $imageInfo['width'] = $imageInfo[0];
     $imageInfo['height'] = $imageInfo[1];
     $imageInfo['type'] = $imageInfo[2];
     $type = $imageInfo['type'];
     $extensionMap = array(IMAGETYPE_GIF => array('gif'), IMAGETYPE_JPEG => array('jpg', 'jpeg', 'jpe'), IMAGETYPE_PNG => array('png'));
     if (!isset($extensionMap[$type])) {
         return;
         // only consider gif, jpeg, png to be images in this system
     }
     if (!in_array($this->_extension, $extensionMap[$type])) {
         $this->_errors['extension'] = new XenForo_Phrase('contents_of_uploaded_image_do_not_match_files_extension');
         return;
     }
     $this->_imageInfo = $imageInfo;
     if ($this->_maxWidth && $imageInfo['width'] > $this->_maxWidth || $this->_maxHeight && $imageInfo['height'] > $this->_maxHeight) {
         $image = XenForo_Image_Abstract::createFromFile($this->_tempFile, $type);
         if ($image) {
             $image->thumbnail($this->_maxWidth, $this->_maxHeight);
             $thumbSuccess = $image->output($type, $this->_tempFile);
             if (!$thumbSuccess) {
                 $this->_errors['dimensions'] = new XenForo_Phrase('uploaded_image_is_too_big');
             }
             // TODO: doesn't resize if the file size is too big (and fails if resizes but still too big)
         } else {
             // error thumbnailing, treat as non-image
             $this->_imageInfo = false;
         }
     }
 }
Exemplo n.º 9
0
 /**
  * Applies the avatar file to the specified user.
  *
  * @param integer $teamId
  * @param string $fileName
  * @param constant|false $imageType Type of image (IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)
  * @param integer|false $width
  * @param integer|false $height
  *
  * @return array
  */
 public function applyAvatar($teamId, $fileName, $imageType = false, $width = false, $height = false)
 {
     if (!$imageType || !$width || !$height) {
         $imageInfo = getimagesize($fileName);
         if (!$imageInfo) {
             throw new Nobita_Teams_Exception_Abstract('Non-image passed in to applyAvatar');
         }
         $width = $imageInfo[0];
         $height = $imageInfo[1];
         $imageType = $imageInfo[2];
     }
     if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
         throw new Nobita_Teams_Exception_Abstract('Invalid image type passed in to applyAvatar');
     }
     if (!XenForo_Image_Abstract::canResize($width, $height)) {
         throw new Nobita_Teams_Exception_Abstract(new XenForo_Phrase('uploaded_image_is_too_big'), true);
     }
     $maxFileSize = XenForo_Application::getOptions()->Teams_avatarFileSize;
     if ($maxFileSize && filesize($fileName) > $maxFileSize) {
         @unlink($fileName);
         throw new Nobita_Teams_Exception_Abstract(new XenForo_Phrase('your_avatar_file_size_large_smaller_x', array('size' => XenForo_Locale::numberFormat($maxFileSize, 'size'))), true);
     }
     // should be use 280x280px because of grid style
     $maxDimensions = 280;
     $imageQuality = intval(Nobita_Teams_Setup::getInstance()->getOption('logoQuality'));
     $outputType = $imageType;
     $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
     if (!$image) {
         return false;
     }
     $image->thumbnailFixedShorterSide($maxDimensions);
     if ($image->getOrientation() != XenForo_Image_Abstract::ORIENTATION_SQUARE) {
         $cropX = floor(($image->getWidth() - $maxDimensions) / 2);
         $cropY = floor(($image->getHeight() - $maxDimensions) / 2);
         $image->crop($cropX, $cropY, $maxDimensions, $maxDimensions);
     }
     $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     if (!$newTempFile) {
         return false;
     }
     $image->output($outputType, $newTempFile, $imageQuality);
     unset($image);
     $filePath = $this->getAvatarFilePath($teamId);
     $directory = dirname($filePath);
     if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory)) {
         if (file_exists($filePath)) {
             @unlink($filePath);
         }
         $writeSuccess = XenForo_Helper_File::safeRename($newTempFile, $filePath);
         if ($writeSuccess && file_exists($newTempFile)) {
             @unlink($newTempFile);
         }
     } else {
         $writeSuccess = false;
     }
     $date = XenForo_Application::$time;
     if ($writeSuccess) {
         $dw = XenForo_DataWriter::create('Nobita_Teams_DataWriter_Team');
         $dw->setExistingData($teamId);
         $dw->set('team_avatar_date', $date);
         $dw->save();
     }
     return $writeSuccess ? $date : 0;
 }
Exemplo n.º 10
0
 public function applyVideoThumbnail(array $video, $fileName, $imageType = false, $width = false, $height = false)
 {
     if (!$imageType || !$width || !$height) {
         $imageInfo = getimagesize($fileName);
         if (!$imageInfo) {
             throw new XenForo_Exception('Non-image passed in to applyAvatar');
         }
         $width = $imageInfo[0];
         $height = $imageInfo[1];
         $imageType = $imageInfo[2];
     }
     if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     if (!$this->_getPhotoModel()->canResizeImage($width, $height)) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_image_is_too_big'), true);
     }
     $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
     if (!$image) {
         return false;
     }
     $dimensions = array();
     $smallThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     $mediumThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     $largeThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     $smallSize = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_SMALL);
     $mediumSize = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_MEDIUM);
     $largeSize = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_LARGE);
     if ($smallThumbFile) {
         $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
         if ($image) {
             if ($image->thumbnail($smallSize * 2, $smallSize * 2)) {
                 $x = floor(($image->getWidth() - $smallSize) / 2);
                 $y = floor(($image->getHeight() - $smallSize) / 2);
                 $image->crop($x, $y, $smallSize, $smallSize);
                 $image->output(IMAGETYPE_JPEG, $smallThumbFile, 100);
                 $dimensions['small_width'] = $image->getWidth();
                 $dimensions['small_height'] = $image->getHeight();
             } else {
                 copy($fileName, $smallThumbFile);
                 $dimensions['small_width'] = $image->getWidth();
                 $dimensions['small_height'] = $image->getHeight();
             }
             unset($image);
         }
     }
     if ($mediumThumbFile) {
         $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
         if ($image) {
             $resizeWidth = $mediumSize;
             $resizeHeight = $mediumSize * 2;
             if ($width * ($resizeHeight / $height) < $mediumSize) {
                 $resizeHeight = $height * ($resizeWidth / $width);
             }
             if ($image->thumbnail($resizeWidth, $resizeHeight)) {
                 $image->output(IMAGETYPE_JPEG, $mediumThumbFile, 100);
                 $dimensions['medium_width'] = $image->getWidth();
                 $dimensions['medium_height'] = $image->getHeight();
             } else {
                 copy($fileName, $mediumThumbFile);
                 $dimensions['medium_width'] = $image->getWidth();
                 $dimensions['medium_height'] = $image->getHeight();
             }
             unset($image);
         }
     }
     if ($largeThumbFile) {
         $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
         if ($image) {
             if ($image->thumbnail($largeSize, $largeSize)) {
                 $image->output(IMAGETYPE_JPEG, $largeThumbFile, 100);
                 $dimensions['large_width'] = $image->getWidth();
                 $dimensions['large_height'] = $image->getHeight();
             } else {
                 copy($fileName, $largeThumbFile);
                 $dimensions['large_width'] = $image->getWidth();
                 $dimensions['large_height'] = $image->getHeight();
             }
             unset($image);
         }
     }
     try {
         $dataDw = XenForo_DataWriter::create('sonnb_XenGallery_DataWriter_ContentData');
         if ($video['content_data_id']) {
             $dataDw->setExistingData($video['content_data_id']);
         } else {
             $dataDw->bulkSet(array('content_type' => sonnb_XenGallery_Model_Video::$contentType, 'temp_hash' => '', 'duration' => 0, 'unassociated' => 0, 'extension' => '', 'file_size' => 0, 'file_hash' => '0'));
         }
         if (isset($dimensions)) {
             if (!$dataDw->get('extension')) {
                 $dataDw->set('extension', sonnb_XenGallery_Model_ContentData::$extensionMap[IMAGETYPE_JPEG]);
             }
             $dataDw->bulkSet($dimensions);
             if ($smallThumbFile) {
                 $dataDw->setExtraData(sonnb_XenGallery_DataWriter_ContentData::DATA_TEMP_SMALL_THUMB_FILE, $smallThumbFile);
             }
             if ($mediumThumbFile) {
                 $dataDw->setExtraData(sonnb_XenGallery_DataWriter_ContentData::DATA_TEMP_MEDIUM_THUMB_FILE, $mediumThumbFile);
             }
             if ($largeThumbFile) {
                 $dataDw->setExtraData(sonnb_XenGallery_DataWriter_ContentData::DATA_TEMP_LARGE_THUMB_FILE, $largeThumbFile);
             }
         }
         $dataDw->save();
         $videoData = $dataDw->getMergedData();
         @unlink($fileName);
         if ($smallThumbFile) {
             @unlink($smallThumbFile);
         }
         if ($mediumThumbFile) {
             @unlink($mediumThumbFile);
         }
         if ($largeThumbFile) {
             @unlink($largeThumbFile);
         }
         $db = $this->_getDb();
         $db->update('sonnb_xengallery_content', array('content_data_id' => $videoData['content_data_id'], 'content_updated_date' => XenForo_Application::$time), 'content_id = ' . $video['content_id']);
     } catch (Exception $e) {
         @unlink($fileName);
         if ($smallThumbFile) {
             @unlink($smallThumbFile);
         }
         if ($mediumThumbFile) {
             @unlink($mediumThumbFile);
         }
         if ($largeThumbFile) {
             @unlink($largeThumbFile);
         }
         throw $e;
     }
 }
Exemplo n.º 11
0
 public function applyCategoryIcon($categoryId, $fileName, $imageType = false, $width = false, $height = false)
 {
     if (!$imageType || !$width || !$height) {
         $imageInfo = getimagesize($fileName);
         if (!$imageInfo) {
             throw new XenForo_Exception('Non-image passed in to applyCategoryIcon');
         }
         $width = $imageInfo[0];
         $height = $imageInfo[1];
         $imageType = $imageInfo[2];
     }
     if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     if (!XenForo_Image_Abstract::canResize($width, $height)) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_image_is_too_big'), true);
     }
     $maxDimensions = self::$iconSize;
     $imageQuality = self::$iconQuality;
     $outputType = $imageType;
     $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
     if (!$image) {
         return false;
     }
     $image->thumbnailFixedShorterSide($maxDimensions);
     if ($image->getOrientation() != XenForo_Image_Abstract::ORIENTATION_SQUARE) {
         $cropX = floor(($image->getWidth() - $maxDimensions) / 2);
         $cropY = floor(($image->getHeight() - $maxDimensions) / 2);
         $image->crop($cropX, $cropY, $maxDimensions, $maxDimensions);
     }
     $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     if (!$newTempFile) {
         return false;
     }
     $image->output($outputType, $newTempFile, $imageQuality);
     unset($image);
     $filePath = $this->getCategoryIconFilePath($categoryId);
     $directory = dirname($filePath);
     if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory)) {
         if (file_exists($filePath)) {
             @unlink($filePath);
         }
         $writeSuccess = XenForo_Helper_File::safeRename($newTempFile, $filePath);
         if ($writeSuccess && file_exists($newTempFile)) {
             @unlink($newTempFile);
         }
     } else {
         $writeSuccess = false;
     }
     if ($writeSuccess) {
         $dw = XenForo_DataWriter::create('Nobita_Teams_DataWriter_Category');
         $dw->setExistingData($categoryId);
         $dw->set('icon_date', XenForo_Application::$time);
         $dw->save();
     }
     return $writeSuccess;
 }
Exemplo n.º 12
0
 public function exifRotate($inputFile, $inputType, $outputFile)
 {
     $exif = array();
     //Compatible with XF 1.3 as it has method transformByExif
     $transforms = array(2 => 'flip-h', 3 => 180, 4 => 'flip-v', 5 => 'transpose', 6 => 90, 7 => 'transverse', 8 => 270);
     if (function_exists('exif_read_data')) {
         $exif = @exif_read_data($inputFile, 0);
     }
     if (isset($exif['Orientation']) && isset($transforms[$exif['Orientation']])) {
         $transform = $transforms[$exif['Orientation']];
         $image = XenForo_Image_Abstract::createFromFile($inputFile, $inputType);
         if ($image && is_callable(array($image, 'transformByExif'))) {
             $image->transformByExif($exif['Orientation']);
             $image->output($inputType, $outputFile, 100);
         } elseif (is_int($transform)) {
             //TODO: Refactor code.
             if (XenForo_Application::getOptions()->imageLibrary['class'] === 'imPecl') {
                 $class = new Imagick($inputFile);
                 foreach ($class->coalesceImages() as $frame) {
                     $frame->rotateImage(new ImagickPixel('none'), $transform);
                 }
                 $class->setimageformat(self::$extensionMap[$inputType]);
                 $class->writeImages($outputFile, true);
                 $class->destroy();
             } else {
                 $gd = $this->createImageFromFile($inputFile, $inputType);
                 if ($gd) {
                     $rotate = imagerotate($gd, $transform * -1, imageColorAllocateAlpha($gd, 0, 0, 0, 127));
                     $this->outputImage($rotate, $inputType, $outputFile);
                     imagedestroy($rotate);
                     imagedestroy($gd);
                 }
             }
         }
         unset($image);
     }
 }
Exemplo n.º 13
0
 /**
  * Re-crops an existing avatar with a square, starting at the specified coordinates
  *
  * @param integer $userId
  * @param integer $x
  * @param integer $y
  *
  * @return array Changed avatar fields
  */
 public function recropAvatar($userId, $x, $y)
 {
     $sizeList = self::$_sizes;
     // get rid of the first entry in the sizes array
     list($largeSizeCode, $largeMaxDimensions) = each($sizeList);
     $outputFiles = array();
     $avatarFile = $this->getAvatarFilePath($userId, $largeSizeCode);
     $imageInfo = getimagesize($avatarFile);
     if (!$imageInfo) {
         throw new XenForo_Exception('Non-image passed in to recropAvatar');
     }
     $imageType = $imageInfo[2];
     // now loop through the rest
     while (list($sizeCode, $maxDimensions) = each($sizeList)) {
         $image = XenForo_Image_Abstract::createFromFile($avatarFile, $imageType);
         $image->thumbnailFixedShorterSide($maxDimensions);
         if ($image->getOrientation() != XenForo_Image_Abstract::ORIENTATION_SQUARE) {
             $ratio = $maxDimensions / $sizeList['m'];
             $xCrop = floor($ratio * $x);
             $yCrop = floor($ratio * $y);
             if ($image->getWidth() > $maxDimensions && $image->getWidth() - $xCrop < $maxDimensions) {
                 $xCrop = $image->getWidth() - $maxDimensions;
             }
             if ($image->getHeight() > $maxDimensions && $image->getHeight() - $yCrop < $maxDimensions) {
                 $yCrop = $image->getHeight() - $maxDimensions;
             }
             $image->crop($xCrop, $yCrop, $maxDimensions, $maxDimensions);
         }
         $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         $image->output($imageType, $newTempFile, self::$imageQuality);
         unset($image);
         $outputFiles[$sizeCode] = $newTempFile;
     }
     foreach ($outputFiles as $sizeCode => $tempFile) {
         $this->_writeAvatar($userId, $sizeCode, $tempFile);
     }
     foreach ($outputFiles as $tempFile) {
         @unlink($tempFile);
     }
     $dwData = array('avatar_date' => XenForo_Application::$time, 'avatar_crop_x' => $x, 'avatar_crop_y' => $y, 'gravatar' => '');
     $dw = XenForo_DataWriter::create('XenForo_DataWriter_User');
     $dw->setExistingData($userId);
     $dw->bulkSet($dwData);
     $dw->save();
     return $dwData;
 }
Exemplo n.º 14
0
 public function renderRaw()
 {
     $attachment = $this->_params['attachment'];
     $attachmentFile = $this->_params['attachmentFile'];
     $attachmentFileSize = $attachment['file_size'];
     $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
     $imageTypes = array('gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png');
     if (in_array($extension, array_keys($imageTypes))) {
         $this->_response->setHeader('Content-type', $imageTypes[$extension], true);
         $this->setDownloadFileName($attachment['filename'], true);
         $resize = $this->_params['resize'];
         switch ($extension) {
             case 'gif':
                 $imageType = IMAGETYPE_GIF;
                 break;
             case 'jpg':
             case 'jpeg':
             case 'jpe':
                 $imageType = IMAGETYPE_JPEG;
                 break;
             case 'png':
                 $imageType = IMAGETYPE_PNG;
                 break;
         }
         if ((!empty($resize['max_width']) or !empty($resize['max_height'])) and !empty($imageType)) {
             // start resizing...
             $image = XenForo_Image_Abstract::createFromFile($attachmentFile, $imageType);
             if (empty($image)) {
                 throw new XenForo_Exception('Unable to read attachment as image');
             }
             $tempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
             if (empty($tempFile)) {
                 throw new XenForo_Exception('Unable to create temp file to resize attachment');
             }
             if (!empty($resize['keep_ratio'])) {
                 $image->thumbnail($resize['max_width'], $resize['max_height']);
             } elseif (!empty($resize['max_width']) and !empty($resize['max_height'])) {
                 $image->thumbnailFixedShorterSide(max($resize['max_width'], $resize['max_height']));
                 if ($image->getWidth() >= $resize['max_width'] and $image->getHeight() >= $resize['max_height']) {
                     $x = ($image->getWidth() - $resize['max_width']) / 2;
                     $y = ($image->getHeight() - $resize['max_height']) / 2;
                     $image->crop($x, $y, $resize['max_width'], $resize['max_height']);
                 }
             }
             $image->output($imageType, $tempFile);
             $attachmentFile = $tempFile;
             $attachmentFileSize = filesize($tempFile);
             unset($image);
         }
     } else {
         $this->_response->setHeader('Content-type', 'application/octet-stream', true);
         $this->setDownloadFileName($attachment['filename']);
     }
     $this->_response->setHeader('ETag', $attachment['attach_date'], true);
     $this->_response->setHeader('Content-Length', $attachmentFileSize, true);
     $this->_response->setHeader('X-Content-Type-Options', 'nosniff');
     if (!empty($this->_params['skipFileOutput'])) {
         $this->_response->setHeader('X-SKIP-FILE-OUTPUT', '1');
         return '';
     }
     return new XenForo_FileOutput($attachmentFile);
 }
Exemplo n.º 15
0
 /**
  * Applies the image file to the specified user.
  *
  * @param integer $contentId
  * @param string $fileName
  * @param constant|false $imageType Type of image (IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)
  * @param integer|false $width
  * @param integer|false $height
  * @param array|false $permissions
  *
  * @return array
  */
 public function applyImage($contentId, $fileName, $imageType = false, $width = false, $height = false, $permissions = false)
 {
     if (!$imageType || !$width || !$height) {
         $imageInfo = getimagesize($fileName);
         if (!$imageInfo) {
             throw new XenForo_Exception('Non-image passed in to applyImage');
         }
         $width = $imageInfo[0];
         $height = $imageInfo[1];
         $imageType = $imageInfo[2];
     }
     if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
         throw new XenForo_Exception('Invalid image type passed in to applyImage');
     }
     if (!XenForo_Image_Abstract::canResize($width, $height)) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_image_is_too_big'), true);
     }
     $outputFiles = array();
     $outputType = $imageType;
     reset(self::$_sizes);
     list($sizeCode, $maxDimensions) = each(self::$_sizes);
     $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     //print_r($newTempFile);die;
     $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
     if (!$image) {
         throw new XenForo_Exception(new XenForo_Phrase('image_could_be_processed_try_another_contact_owner'), true);
     }
     $image->thumbnailFixedShorterSide(280);
     if ($image->getOrientation() != XenForo_Image_Abstract::ORIENTATION_SQUARE) {
         $cropX = floor(($image->getWidth() - 280) / 2);
         $cropY = floor(($image->getHeight() - 250) / 2);
         $image->crop($cropX, $cropY, 280, 250);
     }
     $image->output($outputType, $newTempFile, self::$imageQuality);
     $outputFiles[$sizeCode] = $newTempFile;
     list($sizeCode, $maxDimensions) = each(self::$_sizes);
     $shortSide = $width > $height ? $height : $width;
     if ($shortSide > $maxDimensions) {
         $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         //print_r($newTempFile);die;
         $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
         if (!$image) {
             throw new XenForo_Exception(new XenForo_Phrase('image_could_be_processed_try_another_contact_owner'), true);
         }
         $image->thumbnailFixedShorterSide($maxDimensions);
         $image->output($outputType, $newTempFile, self::$imageQuality);
         $width = $image->getWidth();
         $height = $image->getHeight();
         $outputFiles[$sizeCode] = $newTempFile;
     } else {
         $outputFiles[$sizeCode] = $fileName;
     }
     $crop = array('x' => array('m' => 0), 'y' => array('m' => 0));
     while (list($sizeCode, $maxDimensions) = each(self::$_sizes)) {
         $newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         $image = XenForo_Image_Abstract::createFromFile($fileName, $imageType);
         if (!$image) {
             continue;
         }
         if ($maxDimensions) {
             $image->thumbnailFixedShorterSide($maxDimensions);
         }
         if ($image->getOrientation() != XenForo_Image_Abstract::ORIENTATION_SQUARE) {
             $crop['x'][$sizeCode] = floor(($image->getWidth() - $maxDimensions) / 2);
             $crop['y'][$sizeCode] = floor(($image->getHeight() - $maxDimensions) / 2);
             $image->crop($crop['x'][$sizeCode], $crop['y'][$sizeCode], $maxDimensions, $maxDimensions);
         }
         $image->output($outputType, $newTempFile, self::$imageQuality);
         unset($image);
         $outputFiles[$sizeCode] = $newTempFile;
     }
     if (count($outputFiles) != count(self::$_sizes)) {
         foreach ($outputFiles as $tempFile) {
             if ($tempFile != $fileName) {
                 @unlink($tempFile);
             }
         }
         throw new XenForo_Exception(new XenForo_Phrase('image_could_be_processed_try_another_contact_owner'), true);
     }
     // done in 2 loops as multiple items may point to same file
     foreach ($outputFiles as $sizeCode => $tempFile) {
         $this->_writeImage($contentId, $sizeCode, $tempFile);
     }
     foreach ($outputFiles as $tempFile) {
         if ($tempFile != $fileName) {
             @unlink($tempFile);
         }
     }
     $dwData = array('image_date' => XenForo_Application::$time);
     $this->getModelFromCache('XenForo_Model_Thread')->upgradeThreadImageDate($contentId, XenForo_Application::$time);
     return $dwData;
 }
Exemplo n.º 16
0
 /**
  * Checks the state of the upload to determine if it's
  * a valid image.
  */
 protected function _checkImageState()
 {
     if ($this->_imageInfo !== null) {
         return;
     }
     $this->_imageInfo = false;
     // default to not an image
     if (!$this->_tempFile) {
         return;
     }
     $imageInfo = @getimagesize($this->_tempFile);
     if (!$imageInfo) {
         if (in_array($this->_extension, array('gif', 'jpg', 'jpe', 'jpeg', 'png'))) {
             $this->_errors['extension'] = new XenForo_Phrase('the_uploaded_file_was_not_an_image_as_expected');
         }
         return;
     }
     $imageInfo['width'] = $imageInfo[0];
     $imageInfo['height'] = $imageInfo[1];
     $imageInfo['type'] = $imageInfo[2];
     $type = $imageInfo['type'];
     $extensionMap = array(IMAGETYPE_GIF => array('gif'), IMAGETYPE_JPEG => array('jpg', 'jpeg', 'jpe'), IMAGETYPE_PNG => array('png'));
     if (!isset($extensionMap[$type])) {
         return;
         // only consider gif, jpeg, png to be images in this system
     }
     if (!in_array($this->_extension, $extensionMap[$type])) {
         $this->_errors['extension'] = new XenForo_Phrase('contents_of_uploaded_image_do_not_match_files_extension');
         return;
     }
     $fp = @fopen($this->_tempFile, 'rb');
     if ($fp) {
         $previous = '';
         while (!@feof($fp)) {
             $content = fread($fp, 256000);
             $test = $previous . $content;
             $exists = strpos($test, '<?php') !== false || preg_match('/<script\\s+language\\s*=\\s*(php|"php"|\'php\')\\s*>/i', $test);
             if ($exists) {
                 @fclose($fp);
                 $this->_errors['content'] = new XenForo_Phrase('uploaded_image_contains_invalid_content');
                 return;
             }
             $previous = $content;
         }
         @fclose($fp);
     }
     $orientation = 0;
     if ($imageInfo['type'] == IMAGETYPE_JPEG && function_exists('exif_read_data')) {
         $exif = @exif_read_data($this->_tempFile, 'EXIF');
         if ($exif && !empty($exif['Orientation']) && $exif['Orientation'] > 1) {
             $orientation = $exif['Orientation'];
         }
     }
     $transformRequired = $orientation > 1;
     $maxWidth = $this->_maxWidth;
     $maxHeight = $this->_maxHeight;
     if ($orientation >= 5 && $orientation <= 8) {
         // after rotation the X and Y coords will be reversed,
         // so flip the limits to reflect the "after" value
         $maxHeight = $this->_maxWidth;
         $maxWidth = $this->_maxHeight;
     }
     $resizeRequired = $maxWidth && $imageInfo['width'] > $maxWidth || $maxHeight && $imageInfo['height'] > $maxHeight;
     if (XenForo_Image_Abstract::canResize($imageInfo['width'], $imageInfo['height']) && ($resizeRequired || $transformRequired)) {
         $image = XenForo_Image_Abstract::createFromFile($this->_tempFile, $type);
         if ($image) {
             if ($resizeRequired) {
                 $image->thumbnail($maxWidth ? $maxWidth : $maxHeight, $maxHeight);
             }
             if ($transformRequired) {
                 $image->transformByExif($orientation);
             }
             $success = $image->output($type, $this->_tempFile);
             if ($success) {
                 $imageInfo['width'] = $imageInfo[0] = $image->getWidth();
                 $imageInfo['height'] = $imageInfo[1] = $image->getHeight();
             } else {
                 if ($resizeRequired) {
                     $this->_errors['dimensions'] = new XenForo_Phrase('uploaded_image_is_too_big');
                 }
                 // ok to ignore the EXIF transform failing
             }
         } else {
             // treat as non-image
             $imageInfo = false;
         }
     } else {
         if ($resizeRequired) {
             $this->_errors['dimensions'] = new XenForo_Phrase('uploaded_image_is_too_big');
         }
     }
     $this->_imageInfo = $imageInfo;
 }
Exemplo n.º 17
0
    /**
     * Inserts uploaded attachment data.
     *
     * @param XenForo_Upload $file Uploaded attachment info. Assumed to be valid
     * @param integer $userId User ID uploading
     * @param array $exif Exif data to cache
     *
     * @return integer Attachment data ID
     */
    public function insertUploadedAttachmentData(XenForo_Upload $file, $userId, array $exif = array())
    {
        $dimensions = array();
        $fileIsVideo = false;
        $tempThumbFile = false;
        $options = XenForo_Application::getOptions();
        if ($file->isImage()) {
            $dimensions = array('width' => $file->getImageInfoField('width'), 'height' => $file->getImageInfoField('height'));
            if (XenForo_Image_Abstract::canResize($dimensions['width'], $dimensions['height'])) {
                $imageFile = $file->getTempFile();
            } else {
                $imageFile = $options->xengalleryDefaultNoThumb;
            }
            $tempThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
            if ($tempThumbFile) {
                @copy($imageFile, $tempThumbFile);
            }
        } else {
            $fileIsVideo = true;
            if ($options->get('xengalleryVideoTranscoding', 'thumbnail')) {
                try {
                    $video = new XenGallery_Helper_Video($file->getTempFile());
                    $tempThumbFile = $video->getKeyFrame();
                    list($width, $height) = $video->getVideoDimensions();
                    $dimensions['width'] = $width;
                    $dimensions['height'] = $height;
                } catch (XenForo_Exception $e) {
                }
            }
            if (!$tempThumbFile) {
                $tempThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
                if ($tempThumbFile) {
                    @copy($options->xengalleryDefaultNoThumb, $tempThumbFile);
                }
            }
        }
        if ($tempThumbFile) {
            $image = new XenGallery_Helper_Image($tempThumbFile);
            if ($image) {
                $image->resize($dimensions['thumbnail_width'] = $options->xengalleryThumbnailDimension['width'], $dimensions['thumbnail_height'] = $options->xengalleryThumbnailDimension['height'], 'crop');
                $image->saveToPath($tempThumbFile);
                unset($image);
            }
        }
        $mediaModel = $this->_getMediaModel();
        try {
            $dataDw = XenForo_DataWriter::create('XenForo_DataWriter_AttachmentData');
            $filename = $file->getFileName();
            $dataDw->set('user_id', $userId);
            if ($fileIsVideo) {
                $filename = strtr($filename, strtolower(substr(strrchr($filename, '.'), 1)), 'mp4');
                $dataDw->set('file_path', $mediaModel->getVideoFilePath());
            }
            $dataDw->set('filename', $filename);
            $dataDw->bulkSet($dimensions);
            $dataDw->setExtraData(XenForo_DataWriter_AttachmentData::DATA_TEMP_FILE, $file->getTempFile());
            if ($tempThumbFile) {
                $dataDw->setExtraData(XenForo_DataWriter_AttachmentData::DATA_TEMP_THUMB_FILE, $tempThumbFile);
            }
            $dataDw->setExtraData(XenGallery_DataWriter_AttachmentData::DATA_XMG_FILE_IS_VIDEO, $fileIsVideo);
            $dataDw->setExtraData(XenGallery_DataWriter_AttachmentData::DATA_XMG_DATA, true);
            $dataDw->save();
        } catch (Exception $e) {
            if ($tempThumbFile) {
                @unlink($tempThumbFile);
            }
            throw $e;
        }
        if ($tempThumbFile) {
            @unlink($tempThumbFile);
        }
        $exif = $this->_getMediaModel()->sanitizeExifData($exif);
        $db = $this->_getDb();
        $db->query('
			INSERT IGNORE INTO xengallery_exif_cache
				(data_id, media_exif_data_cache_full, cache_date)
			VALUES
				(?, ?, ?)
		', array($dataDw->get('data_id'), @json_encode($exif), XenForo_Application::$time));
        return $dataDw->get('data_id');
    }
Exemplo n.º 18
0
 public function createContentDataThumbnailFile($inputFile, $outputFile, $outputType, $thumbnailType, &$fallback = false, &$dimensions = array(), $isRebuild = false)
 {
     $success = false;
     $directory = dirname($outputFile);
     XenForo_Helper_File::createDirectory($directory, true);
     //TODO: Refactor the fallback.
     $image = XenForo_Image_Abstract::createFromFile($inputFile, $outputType);
     if ($image) {
         switch ($thumbnailType) {
             case self::CONTENT_FILE_TYPE_LARGE:
                 $largeSize = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_LARGE);
                 if ($image->thumbnail($largeSize, $largeSize)) {
                     $success = $image->output($outputType, $outputFile, 100);
                 } else {
                     $success = $this->copyFile($inputFile, $outputFile);
                 }
                 $dimensions[$thumbnailType . '_width'] = $image->getWidth();
                 $dimensions[$thumbnailType . '_height'] = $image->getHeight();
                 //Add watermark if enabled.
                 $this->addWatermark($outputFile, $outputType, null, $isRebuild);
                 break;
             case self::CONTENT_FILE_TYPE_MEDIUM:
                 $realWidth = $image->getWidth();
                 $realHeight = $image->getHeight();
                 $resizeWidth = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_MEDIUM);
                 $resizeHeight = $resizeWidth;
                 if ($realWidth * ($resizeHeight / $realHeight) < $resizeWidth) {
                     $resizeHeight = $realHeight * ($resizeWidth / $realWidth);
                 }
                 if ($image->thumbnail($resizeWidth, $resizeHeight)) {
                     $success = $image->output($outputType, $outputFile, 100);
                 } else {
                     $success = $this->copyFile($inputFile, $outputFile);
                 }
                 $dimensions[$thumbnailType . '_width'] = $image->getWidth();
                 $dimensions[$thumbnailType . '_height'] = $image->getHeight();
                 break;
             case self::CONTENT_FILE_TYPE_SMALL:
                 $smallSize = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_SMALL);
                 if ($image->thumbnail($smallSize * 2, $smallSize * 2)) {
                     $x = floor(($image->getWidth() - $smallSize) / 2);
                     $y = floor(($image->getHeight() - $smallSize) / 2);
                     $image->crop($x > 0 ? $x : 0, $y > 0 ? $y : 0, $smallSize, $smallSize);
                     $success = $image->output($outputType, $outputFile, 100);
                 } else {
                     $success = $this->copyFile($inputFile, $outputFile);
                 }
                 $dimensions[$thumbnailType . '_width'] = $image->getWidth();
                 $dimensions[$thumbnailType . '_height'] = $image->getHeight();
                 break;
             case self::CONTENT_FILE_TYPE_ORIGINAL:
             default:
                 $success = $this->copyFile($inputFile, $outputFile);
                 break;
         }
     } else {
         $fallback = true;
         $success = $this->copyFile($inputFile, $outputFile);
     }
     unset($image);
     return $success;
 }
Exemplo n.º 19
0
 public function cropAuthorCover(array $user, $x, $y, $relativeWidth, $relativeHeight)
 {
     if (empty($user['sonnb_xengallery_cover']['upload_date'])) {
         return;
     }
     $newUser = $user;
     $newUser['sonnb_xengallery_cover']['upload_date'] = XenForo_Application::$time;
     $outputFile = $this->_getGalleryModel()->getAuthorCoverFile($newUser);
     $file = $this->_getGalleryModel()->getAuthorCoverFile($user);
     $imageInfo = @getimagesize($file);
     if (!$imageInfo) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     $imageType = $imageInfo[2];
     if (!$this->_getPhotoModel()->canResizeImage($imageInfo[0], $imageInfo[1])) {
         throw new XenForo_Exception(new XenForo_Phrase('sonnb_xengallery_your_cover_is_too_big_cannot_crop'), true);
     }
     $image = XenForo_Image_Abstract::createFromFile($file, $imageType);
     if (!$image) {
         return false;
     }
     $image->thumbnail($relativeWidth);
     if ($image->getHeight() > $relativeHeight) {
         $cropWidth = $relativeWidth;
         if ($relativeWidth > $image->getWidth()) {
             $cropWidth = $image->getWidth();
         }
         $cropHeight = $relativeHeight;
         if ($cropHeight > $image->getWidth()) {
             $cropHeight = $image->getHeight();
         }
         $image->crop($x, $y, $cropWidth, $cropHeight);
     }
     if (isset($newUser['sonnb_xengallery_cover']['bdattachmentstore_engine'])) {
         $engine = $newUser['sonnb_xengallery_cover']['bdattachmentstore_engine'];
         $options = $newUser['sonnb_xengallery_cover']['bdattachmentstore_options'];
         $keepLocalCopy = !empty($options['keepLocalCopy']);
     } else {
         $engine = '';
         $options = array();
     }
     $success = $image->output($imageType, $outputFile, 100);
     if ($success) {
         $newData = array('bdattachmentstore_engine' => $engine, 'bdattachmentstore_options' => $options, 'upload_date' => $newUser['sonnb_xengallery_cover']['upload_date'], 'extension' => sonnb_XenGallery_Model_ContentData::$extensionMap[$imageType]);
         if (empty($engine) || !empty($engine) && $keepLocalCopy) {
             $oldLocalCover = $this->_getGalleryModel()->getAuthorCoverFile($user, true);
             @unlink($oldLocalCover);
             $newLocalCover = $this->_getGalleryModel()->getAuthorCoverFile($newUser, true);
             $directory = dirname($newLocalCover);
             if (XenForo_Helper_File::createDirectory($directory, true)) {
                 copy($outputFile, $newLocalCover);
                 if (!empty($engine)) {
                     @unlink($outputFile);
                 }
             }
         }
         if (!empty($engine)) {
             $filePath = $this->getAuthorCoverStoreFile($newUser);
             $this->_bdAttachmentStore_getFileModel()->saveFile($engine, $options, $outputFile, $filePath, basename($filePath));
             if (!$keepLocalCopy) {
                 @unlink($outputFile);
             }
         }
         $db = $this->_getDb();
         $db->update('xf_user', array('sonnb_xengallery_cover' => serialize($newData)), 'user_id = ' . $user['user_id']);
         return $newData;
     }
     unset($image);
     return false;
 }
Exemplo n.º 20
0
 /**
  * Fetches a remote thumbnail, stores it in the file system and records it
  * in the database
  *
  * @param string $url
  * @param array|null $thumbnail
  *
  * @return array
  */
 protected function _fetchAndCacheThumbnail($url, array $thumbnail = null)
 {
     $urlHash = md5($url);
     $time = XenForo_Application::$time;
     if (!$thumbnail || empty($thumbnail['thumbnail_id'])) {
         $thumbnail = array('url' => $url, 'url_hash' => $urlHash, 'fetch_date' => $time, 'file_size' => 0, 'file_name' => '', 'mime_type' => '', 'views' => 0, 'first_request_date' => $time, 'last_request_date' => $time, 'pruned' => 1, 'failed_date' => 0, 'fail_count' => 0);
     }
     $thumbnail['is_processing'] = time();
     // intentionally time() as we might have slept
     $db = $this->_getDb();
     if (empty($thumbnail['thumbnail_id'])) {
         $db->insert('xf_thumbnail_proxy_waindigo', $thumbnail);
         $thumbnail['thumbnail_id'] = $db->lastInsertId();
     } else {
         $db->query("\n\t\t\t\tUPDATE xf_thumbnail_proxy_waindigo\n\t\t\t\tSET is_processing = ?\n\t\t\t\tWHERE thumbnail_id = ?\n\t\t\t", array($thumbnail['is_processing'], $thumbnail['thumbnail_id']));
     }
     $results = $this->_fetchThumbnailForProxy($url);
     $requestFailed = $results['failed'];
     $streamFile = $results['tempFile'];
     $fileName = $results['fileName'];
     $mimeType = $results['mimeType'];
     $fileSize = $results['fileSize'];
     if (!$requestFailed) {
         $filePath = $this->getThumbnailPath($thumbnail);
         $dirName = dirname($filePath);
         @unlink($filePath);
         @unlink($filePath . '.tmp');
         if (XenForo_Helper_File::createDirectory($dirName, true) && XenForo_Helper_File::safeRename($streamFile, $filePath . '.tmp')) {
             if (function_exists('exif_imagetype')) {
                 $imageType = exif_imagetype($filePath . '.tmp');
             } else {
                 $imageSize = getimagesize($filePath . '.tmp');
                 $imageType = $imageSize[2];
             }
             $image = XenForo_Image_Abstract::createFromFile($filePath . '.tmp', $imageType);
             if ($image && $image->thumbnail(XenForo_Application::get('options')->attachmentThumbnailDimensions)) {
                 $image->output($imageType, $filePath);
                 @unlink($filePath . '.tmp');
                 $fileSize = filesize($filePath);
             } else {
                 XenForo_Helper_File::safeRename($filePath . '.tmp', $filePath);
             }
             unset($image);
             // ensure the filename fits -- if it's too long, take off from the beginning to keep extension
             $length = utf8_strlen($fileName);
             if ($length > 250) {
                 $fileName = utf8_substr($fileName, $length - 250);
             }
             $data = array('fetch_date' => time(), 'file_size' => $fileSize, 'file_name' => $fileName, 'mime_type' => $mimeType, 'pruned' => 0, 'is_processing' => 0, 'failed_date' => 0, 'fail_count' => 0);
             $thumbnail = array_merge($thumbnail, $data);
             $db->update('xf_thumbnail_proxy_waindigo', $data, 'thumbnail_id = ' . $db->quote($thumbnail['thumbnail_id']));
         }
     }
     @unlink($streamFile);
     if ($requestFailed) {
         $data = array('is_processing' => 0, 'failed_date' => time(), 'fail_count' => $thumbnail['fail_count'] + 1);
         $thumbnail = array_merge($thumbnail, $data);
         $db->update('xf_thumbnail_proxy_waindigo', $data, 'thumbnail_id = ' . $db->quote($thumbnail['thumbnail_id']));
     }
     return $thumbnail;
 }
Exemplo n.º 21
0
 /**
  * Inserts uploaded attachment data.
  *
  * @param XenForo_Upload $file Uploaded attachment info. Assumed to be valid
  * @param integer $userId User ID uploading
  * @param array $extra Extra params to set
  *
  * @return integer Attachment data ID
  */
 public function insertUploadedAttachmentData(XenForo_Upload $file, $userId, array $extra = array())
 {
     if ($file->isImage() && XenForo_Image_Abstract::canResize($file->getImageInfoField('width'), $file->getImageInfoField('height'))) {
         $dimensions = array('width' => $file->getImageInfoField('width'), 'height' => $file->getImageInfoField('height'));
         $tempThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         if ($tempThumbFile) {
             $image = XenForo_Image_Abstract::createFromFile($file->getTempFile(), $file->getImageInfoField('type'));
             if ($image) {
                 if ($image->thumbnail(XenForo_Application::get('options')->attachmentThumbnailDimensions)) {
                     $image->output($file->getImageInfoField('type'), $tempThumbFile);
                 } else {
                     copy($file->getTempFile(), $tempThumbFile);
                     // no resize necessary, use the original
                 }
                 $dimensions['thumbnail_width'] = $image->getWidth();
                 $dimensions['thumbnail_height'] = $image->getHeight();
                 unset($image);
             }
         }
     } else {
         $tempThumbFile = '';
         $dimensions = array();
     }
     try {
         $dataDw = XenForo_DataWriter::create('XenForo_DataWriter_AttachmentData');
         $dataDw->bulkSet($extra);
         $dataDw->set('user_id', $userId);
         $dataDw->set('filename', $file->getFileName());
         $dataDw->bulkSet($dimensions);
         $dataDw->setExtraData(XenForo_DataWriter_AttachmentData::DATA_TEMP_FILE, $file->getTempFile());
         if ($tempThumbFile) {
             $dataDw->setExtraData(XenForo_DataWriter_AttachmentData::DATA_TEMP_THUMB_FILE, $tempThumbFile);
         }
         $dataDw->save();
     } catch (Exception $e) {
         if ($tempThumbFile) {
             @unlink($tempThumbFile);
         }
         throw $e;
     }
     if ($tempThumbFile) {
         @unlink($tempThumbFile);
     }
     // TODO: add support for "on rollback" behavior
     return $dataDw->get('data_id');
 }
Exemplo n.º 22
0
 public static function getThumbnailUrl($fullPath, $width, $height = 0, $dir = null)
 {
     $thumbnailPath = self::getThumbnailPath($fullPath, $width, $height, $dir);
     $thumbnailUrl = XenForo_Application::$externalDataUrl . self::_getThumbnailRelativePath($fullPath, $width, $height, $dir);
     if (file_exists($thumbnailPath) && filesize($thumbnailPath) > 0) {
         return $thumbnailUrl;
     }
     $tempPath = self::_getTempPath($fullPath);
     $imageInfo = self::getImageInfo($tempPath);
     $image = null;
     if (!empty($imageInfo['typeInt'])) {
         $image = XenForo_Image_Abstract::createFromFile($tempPath, $imageInfo['typeInt']);
     }
     if (empty($image)) {
         // could not open the image, create a new image
         $longer = max($width, $height);
         $image = XenForo_Image_Abstract::createImage($longer, $longer);
         $imageInfo['typeInt'] = IMAGETYPE_PNG;
     }
     if ($width === '' && $height > 0) {
         // stretch width
         $targetHeight = $height;
         $targetWidth = $targetHeight / $image->getHeight() * $image->getWidth();
         $image->thumbnail($targetWidth, $targetHeight);
     } elseif ($height === '' && $width > 0) {
         // stretch height
         $targetWidth = $width;
         $targetHeight = $targetWidth / $image->getWidth() * $image->getHeight();
         $image->thumbnail($targetWidth, $targetHeight);
     } elseif ($width > 0 && $height > 0) {
         // exact crop
         $origRatio = $image->getWidth() / $image->getHeight();
         $cropRatio = $width / $height;
         if ($origRatio > $cropRatio) {
             $thumbnailHeight = $height;
             $thumbnailWidth = $height * $origRatio;
         } else {
             $thumbnailWidth = $width;
             $thumbnailHeight = $width / $origRatio;
         }
         if ($thumbnailWidth <= $image->getWidth() && $thumbnailHeight <= $image->getHeight()) {
             $image->thumbnail($thumbnailWidth, $thumbnailHeight);
             $image->crop(0, 0, $width, $height);
         } else {
             // thumbnail requested is larger then the image size
             if ($origRatio > $cropRatio) {
                 $image->crop(0, 0, $image->getHeight() * $cropRatio, $image->getHeight());
             } else {
                 $image->crop(0, 0, $image->getWidth(), $image->getWidth() / $cropRatio);
             }
         }
     } elseif ($width > 0) {
         // square crop
         $image->thumbnailFixedShorterSide($width);
         $image->crop(0, 0, $width, $width);
     }
     // TODO: progressive jpeg
     XenForo_Helper_File::createDirectory(dirname($thumbnailPath), true);
     $outputPath = tempnam(XenForo_Helper_File::getTempDir(), __CLASS__);
     /** @noinspection PhpParamsInspection */
     $image->output($imageInfo['typeInt'], $outputPath);
     XenForo_Helper_File::safeRename($outputPath, $thumbnailPath);
     return $thumbnailUrl;
 }