示例#1
0
文件: AddOn.php 项目: Sywooch/forums
 /**
  * Exports an add-on's XML data.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionZip()
 {
     $addOnId = $this->_input->filterSingle('addon_id', XenForo_Input::STRING);
     $addOn = $this->_getAddOnOrError($addOnId);
     $rootDir = XenForo_Application::getInstance()->getRootDir();
     $zipPath = XenForo_Helper_File::getTempDir() . '/addon-' . $addOnId . '.zip';
     if (file_exists($zipPath)) {
         unlink($zipPath);
     }
     $zip = new ZipArchive();
     $res = $zip->open($zipPath, ZipArchive::CREATE);
     if ($res === TRUE) {
         $zip->addFromString('addon-' . $addOnId . '.xml', $this->_getAddOnModel()->getAddOnXml($addOn)->saveXml());
         if (is_dir($rootDir . '/library/' . $addOnId)) {
             $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootDir . '/library/' . $addOnId));
             foreach ($iterator as $key => $value) {
                 $zip->addFile(realpath($key), str_replace($rootDir . '/', '', $key));
             }
         }
         if (is_dir($rootDir . '/js/' . strtolower($addOnId))) {
             $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootDir . '/js/' . strtolower($addOnId)));
             foreach ($iterator as $key => $value) {
                 $zip->addFile(realpath($key), str_replace($rootDir . '/', '', $key));
             }
         }
         $zip->close();
     }
     if (!file_exists($zipPath) || !is_readable($zipPath)) {
         return $this->responseError(new XenForo_Phrase('devkit_error_while_creating_zip'));
     }
     $this->_routeMatch->setResponseType('raw');
     $attachment = array('filename' => 'addon-' . $addOnId . '_' . $addOn['version_string'] . '.zip', 'file_size' => filesize($zipPath), 'attach_date' => XenForo_Application::$time);
     $viewParams = array('attachment' => $attachment, 'attachmentFile' => $zipPath);
     return $this->responseView('XenForo_ViewAdmin_Attachment_View', '', $viewParams);
 }
示例#2
0
 protected function _createFiles(sonnb_XenGallery_Model_ContentData $model, $filePath, $contentData, $useTemp = true, $isVideo = false)
 {
     $smallThumbFile = $model->getContentDataSmallThumbnailFile($contentData);
     $mediumThumbFile = $model->getContentDataMediumThumbnailFile($contentData);
     $largeThumbFile = $model->getContentDataLargeThumbnailFile($contentData);
     $originalFile = $model->getContentDataFile($contentData);
     if ($useTemp) {
         $filename = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         @copy($filePath, $filename);
     } else {
         $filename = $filePath;
     }
     if ($isVideo === false && $originalFile) {
         $directory = dirname($originalFile);
         if (XenForo_Helper_File::createDirectory($directory, true)) {
             @copy($filename, $originalFile);
             XenForo_Helper_File::makeWritableByFtpUser($originalFile);
         } else {
             return false;
         }
     }
     if ($isVideo === false) {
         $ext = sonnb_XenGallery_Model_ContentData::$typeMap[$contentData['extension']];
     } else {
         $ext = sonnb_XenGallery_Model_ContentData::$typeMap[sonnb_XenGallery_Model_VideoData::$videoEmbedExtension];
     }
     $model->createContentDataThumbnailFile($filename, $largeThumbFile, $ext, sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_LARGE);
     $model->createContentDataThumbnailFile($largeThumbFile, $mediumThumbFile, $ext, sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_MEDIUM);
     $model->createContentDataThumbnailFile($largeThumbFile, $smallThumbFile, $ext, sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_SMALL);
     @unlink($filename);
     return true;
 }
示例#3
0
文件: Thumbs.php 项目: Sywooch/forums
 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);
     }
 }
示例#4
0
 public static function download($url)
 {
     if (isset(self::$_cached[$url]) and file_exists(self::$_cached[$url])) {
         // use cached temp file, no need to re-download
         return self::$_cached[$url];
     }
     $tempFile = tempnam(XenForo_Helper_File::getTempDir(), self::_getPrefix());
     self::cache($url, $tempFile);
     $fh = fopen($tempFile, 'wb');
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_FILE, $fh);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
     curl_exec($ch);
     $downloaded = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE)) == 200;
     curl_close($ch);
     fclose($fh);
     if (XenForo_Application::debugMode()) {
         $fileSize = filesize($tempFile);
         XenForo_Helper_File::log(__CLASS__, call_user_func_array('sprintf', array('download %s -> %s, %s, %d bytes%s', $url, $tempFile, $downloaded ? 'succeeded' : 'failed', $fileSize, !$downloaded && $fileSize > 0 ? "\n\t" . file_get_contents($tempFile) : '')));
     }
     if ($downloaded) {
         return $tempFile;
     } else {
         return false;
     }
 }
示例#5
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;
 }
示例#6
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);
     }
 }
 public function insertUploadedAttachmentData(XenForo_Upload $file, $userId, array $extra = array())
 {
     $filename = $file->getFileName();
     $extension = XenForo_Helper_File::getFileExtension($filename);
     if ($extension == 'svg') {
         list($svgfile, $dimensions) = $this->extractDimensionsForSVG($file->getTempFile(), XenForo_Application::getOptions()->SV_RejectAttachmentWithBadTags);
         if (!empty($svgfile) && !empty($dimensions)) {
             if ($dimensions['thumbnail_width'] && $dimensions['thumbnail_height']) {
                 $tempThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
                 if ($tempThumbFile) {
                     // update the width/height attributes
                     $svgfile['width'] = (string) $dimensions['thumbnail_width'];
                     $svgfile['height'] = (string) $dimensions['thumbnail_height'];
                     $svgfile->asXML($tempThumbFile);
                     SV_AttachmentImprovements_Globals::$tempThumbFile = $tempThumbFile;
                 }
             }
             SV_AttachmentImprovements_Globals::$forcedDimensions = $dimensions;
         }
     }
     return parent::insertUploadedAttachmentData($file, $userId, $extra);
 }
示例#8
0
    public function stepAttachments($start, array $options)
    {
        $options = array_merge(array('limit' => 50, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        /* @var $model XenForo_Model_Import */
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(attach_id)
				FROM ' . $prefix . 'attachments
			');
        }
        $attachments = $sDb->fetchAll($sDb->limit('
				SELECT
					attach_id, attach_date, attach_hits,
					attach_file, attach_location,
					attach_member_id AS member_id,
					attach_rel_id AS post_id
				FROM ' . $prefix . 'attachments
				WHERE attach_id > ' . $sDb->quote($start) . '
					AND attach_rel_module = \'post\'
				ORDER BY attach_id
			', $options['limit']));
        if (!$attachments) {
            return true;
        }
        $next = 0;
        $total = 0;
        $userIdMap = $model->getUserIdsMapFromArray($attachments, 'member_id');
        $postIdMap = $model->getPostIdsMapFromArray($attachments, 'post_id');
        $posts = $model->getModelFromCache('XenForo_Model_Post')->getPostsByIds($postIdMap);
        foreach ($attachments as $attachment) {
            $next = $attachment['attach_id'];
            $newPostId = $this->_mapLookUp($postIdMap, $attachment['post_id']);
            if (!$newPostId) {
                continue;
            }
            $attachFileOrig = $this->_config['ipboard_path'] . '/uploads/' . $attachment['attach_location'];
            if (!file_exists($attachFileOrig)) {
                continue;
            }
            $attachFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
            copy($attachFileOrig, $attachFile);
            $isTemp = true;
            $success = $model->importPostAttachment($attachment['attach_id'], $this->_convertToUtf8($attachment['attach_file']), $attachFile, $this->_mapLookUp($userIdMap, $attachment['member_id'], 0), $newPostId, $attachment['attach_date'], array('view_count' => $attachment['attach_hits']), array($this, 'processAttachmentTags'), $posts[$newPostId]['message']);
            if ($success) {
                $total++;
            }
            if ($isTemp) {
                @unlink($attachFile);
            }
        }
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next, $options['max']));
    }
示例#9
0
    /**
     * Currently handles attachments for posts and conversation messages only
     *
     * @param integer $start
     * @param array $options
     */
    public function stepAttachments($start, array $options)
    {
        $options = array_merge(array('data' => isset($this->_config['dir']['data']) ? $this->_config['dir']['data'] : '', 'internal_data' => isset($this->_config['dir']['internal_data']) ? $this->_config['dir']['internal_data'] : '', 'limit' => 50, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        /* @var $model XenForo_Model_Import */
        $model = $this->_importModel;
        $attachmentSqlContentInfo = $model->getAttachmentContentSqlInfo();
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(attachment_id)
				FROM xf_attachment
				WHERE content_type IN (' . $sDb->quote(array_keys($attachmentSqlContentInfo)) . ')
			');
        }
        $attachments = $sDb->fetchAll($sDb->limit('
				SELECT *
				FROM xf_attachment AS a
				LEFT JOIN xf_attachment_data AS ad ON (ad.data_id = a.data_id)
				WHERE a.content_type IN (' . $sDb->quote(array_keys($attachmentSqlContentInfo)) . ')
					AND a.attachment_id > ' . $sDb->quote($start) . '
				ORDER BY a.attachment_id
			', $options['limit']));
        if (!$attachments) {
            return true;
        }
        $next = 0;
        $total = 0;
        $userIdMap = $model->getUserIdsMapFromArray($attachments, 'user_id');
        $groupedAttachments = array();
        foreach ($attachments as $attachment) {
            $groupedAttachments[$attachment['content_type']][$attachment['attachment_id']] = $attachment;
        }
        $db = XenForo_Application::getDb();
        /* @var $attachModel XenForo_Model_Attachment */
        $attachModel = XenForo_Model::create('XenForo_Model_Attachment');
        foreach ($groupedAttachments as $contentType => $attachments) {
            list($sqlTableName, $sqlIdName) = $attachmentSqlContentInfo[$contentType];
            $contentIdMap = $model->getImportContentMap($contentType, XenForo_Application::arrayColumn($attachments, 'content_id'));
            if ($contentIdMap) {
                $contentItems = $db->fetchPairs("\r\r\n\t\t\t\t\tSELECT {$sqlIdName}, message\r\r\n\t\t\t\t\tFROM {$sqlTableName}\r\r\n\t\t\t\t\tWHERE {$sqlIdName} IN (" . $db->quote($contentIdMap) . ")\r\r\n\t\t\t\t");
            } else {
                $contentItems = array();
            }
            foreach ($attachments as $attachment) {
                $next = max($next, $attachment['attachment_id']);
                $contentId = $this->_mapLookUp($contentIdMap, $attachment['content_id']);
                if (!$contentId || !isset($contentItems[$contentId])) {
                    continue;
                }
                $attachFileOrig = $attachModel->getAttachmentDataFilePath($attachment, $options['internal_data']);
                if (!file_exists($attachFileOrig)) {
                    continue;
                }
                $userId = $this->_mapLookUp($userIdMap, $attachment['user_id'], 0);
                $attachFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
                copy($attachFileOrig, $attachFile);
                $success = $model->importAttachment($attachment['attachment_id'], $attachment['filename'], $attachFile, $userId, $contentType, $contentId, $attachment['upload_date'], array('view_count' => $attachment['view_count']), array($this, 'processAttachmentTags'), $contentItems[$contentId]);
                if ($success) {
                    $total++;
                }
                @unlink($attachFile);
            }
        }
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next, $options['max']));
    }
示例#10
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;
 }
示例#11
0
    public function stepAttachments($start, array $options)
    {
        $options = array_merge(array('path' => isset($this->_config['attachmentPath']) ? $this->_config['attachmentPath'] : '', 'limit' => 50, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        /* @var $model XenForo_Model_Import */
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(attach_id)
				FROM ' . $prefix . 'attachments
			');
        }
        $attachments = $sDb->fetchAll($sDb->limit('
				SELECT *
				FROM ' . $prefix . 'attachments
				WHERE attach_id > ' . $sDb->quote($start) . '
					AND is_orphan = 0
					AND post_msg_id > 0
				ORDER BY attach_id
			', $options['limit']));
        if (!$attachments) {
            return true;
        }
        $next = 0;
        $total = 0;
        $userIdMap = $model->getUserIdsMapFromArray($attachments, 'poster_id');
        $postIdMap = $model->getPostIdsMapFromArray($attachments, 'post_msg_id');
        foreach ($attachments as $attachment) {
            $next = $attachment['attach_id'];
            $newPostId = $this->_mapLookUp($postIdMap, $attachment['post_msg_id']);
            if (!$newPostId) {
                continue;
            }
            $attachFileOrig = "{$options['path']}/{$attachment['physical_filename']}";
            if (!file_exists($attachFileOrig) || !is_file($attachFileOrig)) {
                continue;
            }
            $attachFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
            copy($attachFileOrig, $attachFile);
            $success = $model->importPostAttachment($attachment['attach_id'], $this->_convertToUtf8($attachment['real_filename'], true), $attachFile, $this->_mapLookUp($userIdMap, $attachment['poster_id'], 0), $newPostId, $attachment['filetime'], array('view_count' => $attachment['download_count']));
            if ($success) {
                $total++;
            }
            @unlink($attachFile);
        }
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next, $options['max']));
    }
示例#12
0
 /**
  * Registers a new account (or associates with an existing one) using Facebook.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionFacebookRegister()
 {
     $this->_assertPostOnly();
     $fbToken = $this->_input->filterSingle('fb_token', XenForo_Input::STRING);
     $fbUser = XenForo_Helper_Facebook::getUserInfo($fbToken);
     if (empty($fbUser['id'])) {
         return $this->responseError(new XenForo_Phrase('error_occurred_while_connecting_with_facebook'));
     }
     $userModel = $this->_getUserModel();
     $userExternalModel = $this->_getUserExternalModel();
     $doAssoc = $this->_input->filterSingle('associate', XenForo_Input::STRING) || $this->_input->filterSingle('force_assoc', XenForo_Input::UINT);
     if ($doAssoc) {
         $associate = $this->_input->filter(array('associate_login' => XenForo_Input::STRING, 'associate_password' => XenForo_Input::STRING));
         $loginModel = $this->_getLoginModel();
         if ($loginModel->requireLoginCaptcha($associate['associate_login'])) {
             return $this->responseError(new XenForo_Phrase('your_account_has_temporarily_been_locked_due_to_failed_login_attempts'));
         }
         $userId = $userModel->validateAuthentication($associate['associate_login'], $associate['associate_password'], $error);
         if (!$userId) {
             $loginModel->logLoginAttempt($associate['associate_login']);
             return $this->responseError($error);
         }
         $userExternalModel->updateExternalAuthAssociation('facebook', $fbUser['id'], $userId);
         XenForo_Helper_Facebook::setUidCookie($fbUser['id']);
         XenForo_Application::get('session')->changeUserId($userId);
         XenForo_Visitor::setup($userId);
         $redirect = XenForo_Application::get('session')->get('fbRedirect');
         XenForo_Application::get('session')->remove('fbRedirect');
         if (!$redirect) {
             $redirect = $this->getDynamicRedirect(false, false);
         }
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
     }
     $this->_assertRegistrationActive();
     $data = $this->_input->filter(array('username' => XenForo_Input::STRING, 'timezone' => XenForo_Input::STRING));
     if (XenForo_Dependencies_Public::getTosUrl() && !$this->_input->filterSingle('agree', XenForo_Input::UINT)) {
         return $this->responseError(new XenForo_Phrase('you_must_agree_to_terms_of_service'));
     }
     $options = XenForo_Application::get('options');
     $gender = '';
     if (isset($fbUser['gender'])) {
         switch ($fbUser['gender']) {
             case 'man':
             case 'male':
                 $gender = 'male';
                 break;
             case 'woman':
             case 'female':
                 $gender = 'female';
                 break;
         }
     }
     $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
     if ($options->registrationDefaults) {
         $writer->bulkSet($options->registrationDefaults, array('ignoreInvalidFields' => true));
     }
     $writer->bulkSet($data);
     $writer->bulkSet(array('gender' => $gender, 'email' => $fbUser['email'], 'location' => isset($fbUser['location']['name']) ? $fbUser['location']['name'] : ''));
     if (!empty($fbUser['birthday'])) {
         $birthdayParts = explode('/', $fbUser['birthday']);
         if (count($birthdayParts) == 3) {
             list($month, $day, $year) = $birthdayParts;
             $userAge = $this->_getUserProfileModel()->calculateAge($year, $month, $day);
             if ($userAge < intval($options->get('registrationSetup', 'minimumAge'))) {
                 // TODO: set a cookie to prevent re-registration attempts
                 return $this->responseError(new XenForo_Phrase('sorry_you_too_young_to_create_an_account'));
             }
             $writer->bulkSet(array('dob_year' => $year, 'dob_month' => $month, 'dob_day' => $day));
         }
     }
     if (!empty($fbUser['website'])) {
         list($website) = preg_split('/\\r?\\n/', $fbUser['website']);
         if ($website && Zend_Uri::check($website)) {
             $writer->set('homepage', $website);
         }
     }
     $auth = XenForo_Authentication_Abstract::create('XenForo_Authentication_NoPassword');
     $writer->set('scheme_class', $auth->getClassName());
     $writer->set('data', $auth->generate(''), 'xf_user_authenticate');
     $writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
     $writer->set('language_id', XenForo_Visitor::getInstance()->get('language_id'));
     $writer->advanceRegistrationUserState(false);
     $writer->preSave();
     // TODO: option for extra user group
     $writer->save();
     $user = $writer->getMergedData();
     $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     if ($avatarFile) {
         $data = XenForo_Helper_Facebook::getUserPicture($fbToken);
         if ($data && $data[0] != '{') {
             file_put_contents($avatarFile, $data);
             try {
                 $user = array_merge($user, $this->getModelFromCache('XenForo_Model_Avatar')->applyAvatar($user['user_id'], $avatarFile));
             } catch (XenForo_Exception $e) {
             }
         }
         @unlink($avatarFile);
     }
     $userExternalModel->updateExternalAuthAssociation('facebook', $fbUser['id'], $user['user_id']);
     XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'register');
     XenForo_Helper_Facebook::setUidCookie($fbUser['id']);
     XenForo_Application::get('session')->changeUserId($user['user_id']);
     XenForo_Visitor::setup($user['user_id']);
     $redirect = $this->_input->filterSingle('redirect', XenForo_Input::STRING);
     $viewParams = array('user' => $user, 'redirect' => $redirect ? XenForo_Link::convertUriToAbsoluteUri($redirect) : '', 'facebook' => true);
     return $this->responseView('XenForo_ViewPublic_Register_Process', 'register_process', $viewParams, $this->_getRegistrationContainerParams());
 }
 /**
  * Gets the path to the written file for a stream URI
  *
  * @param string $path
  *
  * @return string
  */
 public static function getTempFile($path)
 {
     $path = preg_replace('#^[a-z0-9_-]+://#i', '', $path);
     return XenForo_Helper_File::getTempDir() . '/' . strtr($path, '/\\.', '---') . '.temp';
 }
示例#14
0
    public function stepAttachments($start, array $options)
    {
        $options = array_merge(array('attachmentPaths' => isset($this->_config['attachmentPaths']) ? $this->_config['attachmentPaths'] : '', 'limit' => 50, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        /* @var $model XenForo_Model_Import */
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(id_attach)
				FROM ' . $prefix . 'attachments
			');
        }
        $attachments = $sDb->fetchAll($sDb->limit('
				SELECT attachments.*, messages.id_member, messages.poster_time
				FROM ' . $prefix . 'attachments AS attachments
				INNER JOIN ' . $prefix . 'messages AS messages ON
				 	(messages.id_msg = attachments.id_msg)
				WHERE attachments.id_attach > ' . $sDb->quote($start) . '
					AND attachments.id_msg > 0
					AND attachments.id_member = 0
					AND attachments.attachment_type = 0
				ORDER BY attachments.id_attach
			', $options['limit']));
        if (!$attachments) {
            return true;
        }
        $next = 0;
        $total = 0;
        $userIdMap = $model->getUserIdsMapFromArray($attachments, 'id_member');
        $postIdMap = $model->getPostIdsMapFromArray($attachments, 'id_msg');
        foreach ($attachments as $attachment) {
            $next = $attachment['id_attach'];
            $newPostId = $this->_mapLookUp($postIdMap, $attachment['id_msg']);
            if (!$newPostId) {
                continue;
            }
            if (!isset($options['attachmentPaths'][$attachment['id_folder']])) {
                // Single attachment folder environment.
                $attachmentPath = $options['attachmentPaths'][0];
            } else {
                $attachmentPath = $options['attachmentPaths'][$attachment['id_folder']];
            }
            $filePath = "{$attachmentPath}/{$attachment['id_attach']}_{$attachment['file_hash']}";
            if (!file_exists($filePath)) {
                continue;
            }
            $attachFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
            copy($filePath, $attachFile);
            $success = $model->importPostAttachment($attachment['id_attach'], $this->_convertToUtf8($attachment['filename'], true), $attachFile, $this->_mapLookUp($userIdMap, $attachment['id_member'], 0), $newPostId, $attachment['poster_time'], array('view_count' => $attachment['downloads']));
            if ($success) {
                $total++;
            }
            @unlink($attachFile);
        }
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next, $options['max']));
    }
示例#15
0
文件: Avatar.php 项目: Sywooch/forums
 /**
  * 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;
 }
示例#16
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;
 }
示例#17
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;
 }
示例#18
0
 public function insertUploadedPhotoData(XenForo_Upload $file, array $extra = array(), &$errorPhraseKey = '')
 {
     $return = false;
     if ($this->_getPhotoModel()->canResizeImage($file->getImageInfoField('width'), $file->getImageInfoField('height'))) {
         $xenOptions = XenForo_Application::getOptions();
         $tempFile = $file->getTempFile();
         $tempType = $file->getImageInfoField('type');
         $dimensions = array('width' => $file->getImageInfoField('width'), 'height' => $file->getImageInfoField('height'), 'is_animated' => $this->_getPhotoModel()->isAnimatedGif($tempFile) ? 1 : 0);
         $smallThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         $mediumThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         $largeThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
         $originalFile = false;
         $successCount = 0;
         if ($xenOptions->sonnbXG_enableResize) {
             $photoConstraints = $this->_getPhotoModel()->getPhotoDataConstraints();
             //Resize original image if it excess user's limit.
             if ($dimensions['width'] > $photoConstraints['width'] || $dimensions['height'] > $photoConstraints['height']) {
                 $image = XenForo_Image_Abstract::createFromFile($tempFile, $tempType);
                 if ($image) {
                     if ($image->thumbnail($photoConstraints['width'], $photoConstraints['height'])) {
                         $image->output($tempType, $tempFile, 100);
                         $dimensions['width'] = $image->getWidth();
                         $dimensions['height'] = $image->getHeight();
                     }
                     unset($image);
                 }
             }
         }
         if (!$xenOptions->sonnbXG_disableOriginal) {
             $originalFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
             if ($this->_getContentDataModel()->copyFile($tempFile, $originalFile)) {
                 $successCount++;
             }
         }
         $this->exifRotate($tempFile, $tempType, $tempFile);
         if ($largeThumbFile) {
             if ($this->createContentDataThumbnailFile($tempFile, $largeThumbFile, $tempType, sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_LARGE, $fallback, $dimensions)) {
                 $successCount++;
             }
             if ($fallback === true) {
                 $dimensions['large_width'] = $file->getImageInfoField('width');
                 $dimensions['large_height'] = $file->getImageInfoField('height');
             }
         }
         if ($mediumThumbFile) {
             if ($this->createContentDataThumbnailFile($largeThumbFile, $mediumThumbFile, $tempType, sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_MEDIUM, $fallback)) {
                 $successCount++;
             }
             if ($fallback === true) {
                 $dimensions['medium_width'] = $file->getImageInfoField('width');
                 $dimensions['medium_height'] = $file->getImageInfoField('height');
             }
         }
         if ($smallThumbFile) {
             if ($this->createContentDataThumbnailFile($largeThumbFile, $smallThumbFile, $tempType, sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_SMALL, $fallback)) {
                 $successCount++;
             }
             if ($fallback === true) {
                 $dimensions['small_width'] = $file->getImageInfoField('width');
                 $dimensions['small_height'] = $file->getImageInfoField('height');
             }
         }
         if ($xenOptions->sonnbXG_disableOriginal) {
             if ($successCount !== 3) {
                 return $return;
             }
             $dimensions['width'] = $dimensions['large_width'];
             $dimensions['height'] = $dimensions['large_height'];
             $dimensions['is_animated'] = $this->_getPhotoModel()->isAnimatedGif($largeThumbFile) ? 1 : 0;
         } else {
             if ($successCount !== 4) {
                 return $return;
             }
         }
         try {
             /** @var sonnb_XenGallery_DataWriter_ContentData $dataDw */
             $dataDw = XenForo_DataWriter::create('sonnb_XenGallery_DataWriter_ContentData');
             $dataDw->bulkSet($extra);
             $dataDw->bulkSet($dimensions);
             $dataDw->set('extension', sonnb_XenGallery_Model_ContentData::$extensionMap[$tempType]);
             if (!$xenOptions->sonnbXG_disableOriginal && $originalFile) {
                 $dataDw->setExtraData(sonnb_XenGallery_DataWriter_ContentData::DATA_TEMP_FILE, $originalFile);
             }
             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();
             $return = $dataDw->getMergedData();
             $exif = $this->_getPhotoModel()->getPhotoExif($return, $tempFile);
             $return['title'] = isset($exif['title']) ? trim($exif['title']) : ($xenOptions->sonnbXG_useFileName ? trim(pathinfo($file->getFileName(), PATHINFO_FILENAME)) : '');
             $return['description'] = isset($exif['description']) ? trim($exif['description']) : '';
             $return['location_lat'] = isset($exif['latitude']) ? $exif['latitude'] : '';
             $return['location_lng'] = isset($exif['longitude']) ? $exif['longitude'] : '';
             $return['content_location'] = isset($exif['address']) ? $exif['address'] : '';
         } catch (Exception $e) {
             if ($smallThumbFile) {
                 @unlink($smallThumbFile);
             }
             if ($mediumThumbFile) {
                 @unlink($mediumThumbFile);
             }
             if ($largeThumbFile) {
                 @unlink($largeThumbFile);
             }
             if (!$xenOptions->sonnbXG_disableOriginal && $originalFile) {
                 @unlink($originalFile);
             }
             throw $e;
         }
         if ($smallThumbFile) {
             @unlink($smallThumbFile);
         }
         if ($mediumThumbFile) {
             @unlink($mediumThumbFile);
         }
         if ($largeThumbFile) {
             @unlink($largeThumbFile);
         }
         if (!$xenOptions->sonnbXG_disableOriginal && $originalFile) {
             @unlink($originalFile);
         }
     }
     unset($tempFile);
     return $return;
 }
 protected function _importMedia(array $item, array $options)
 {
     $originalFilePath = sprintf('%s/%d/%d-%s.data', $options['path'], floor($item['data_id'] / 1000), $item['data_id'], $item['file_hash']);
     if (!file_exists($originalFilePath)) {
         return false;
     }
     $tempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
     copy($originalFilePath, $tempFile);
     $model = $this->_getMediaGalleryImportersModel();
     $categoryId = 0;
     $albumId = $model->mapAlbumId($item['album_id']);
     if (strstr($albumId, 'category_')) {
         $categoryId = str_replace('category_', '', $albumId);
         $albumId = 0;
     }
     $mediaPrivacy = $item['album_type'] == 'global' ? 'public' : $item['album_type'];
     if ($mediaPrivacy == 'selected') {
         $mediaPrivacy = 'shared';
     }
     $noTitle = new XenForo_Phrase('xengallery_imported_item');
     $lastCommentDate = $model->getLastCommentDateFromImageIdXFRUA($item['image_id']);
     $xengalleryMedia = array('media_title' => $item['filename'] ? $item['filename'] : $noTitle->render(), 'media_description' => $item['description'], 'media_date' => $item['upload_date'], 'last_edit_date' => XenForo_Application::$time, 'last_comment_date' => $lastCommentDate ? $lastCommentDate : 0, 'media_type' => 'image_upload', 'media_state' => $item['moderation'] ? 'moderated' : 'visible', 'album_id' => $albumId, 'category_id' => $categoryId, 'media_privacy' => $mediaPrivacy, 'attachment_id' => 0, 'user_id' => $item['user_id'], 'username' => $model->getUsernameByUserId($item['user_id']), 'ip_id' => $model->getLatestIpIdFromUserId($item['user_id']), 'likes' => $item['likes'], 'like_users' => unserialize($item['like_users']), 'comment_count' => $item['comment_count'], 'rating_count' => 0, 'media_view_count' => $item['view_count']);
     $xfAttachment = array('data_id' => 0, 'content_type' => 'xengallery_media', 'content_id' => 0, 'attach_date' => $item['upload_date'], 'temp_hash' => '', 'unassociated' => 0, 'view_count' => $item['view_count']);
     $xfAttachmentData = array('user_id' => $item['user_id'], 'upload_date' => $item['upload_date'], 'filename' => $item['filename'], 'attach_count' => $item['attach_count']);
     $importedMediaId = $model->importMedia($item['image_id'], $tempFile, 'xfr_useralbum_image', $xengalleryMedia, $xfAttachment, $xfAttachmentData);
     @unlink($tempFile);
     return $importedMediaId;
 }
示例#20
0
    protected function _importMedia(array $item, array $options)
    {
        $sDb = $this->_sourceDb;
        $xfDb = $this->_xfDb;
        if (!$this->_fileRoot) {
            $this->_fileRoot = $sDb->fetchOne('SELECT setting FROM ' . $this->_prefix . 'settings WHERE varname = \'datafull\'');
        }
        $originalFilePath = sprintf('%s/%d/%s', $this->_fileRoot, $item['cat'], $item['bigimage']);
        if (!file_exists($originalFilePath)) {
            return false;
        }
        $xenOptions = XenForo_Application::getOptions();
        $imageExtensions = preg_split('/\\s+/', trim($xenOptions->xengalleryImageExtensions));
        $videoExtensions = preg_split('/\\s+/', trim($xenOptions->xengalleryVideoExtensions));
        $extension = XenForo_Helper_File::getFileExtension($originalFilePath);
        if (in_array($extension, $imageExtensions)) {
            $mediaType = 'image_upload';
        } else {
            if (in_array($extension, $videoExtensions)) {
                $mediaType = 'video_upload';
            } else {
                return false;
            }
        }
        $tempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
        copy($originalFilePath, $tempFile);
        $model = $this->_getMediaGalleryImportersModel();
        $albumId = 0;
        $categoryId = 0;
        $privacy = 'public';
        if ($item['cattype'] == 'a') {
            $albumId = $model->mapAlbumId($item['cat']);
            $privacy = $item['private'] == 'yes' ? 'private' : 'public';
        } elseif ($item['cattype'] == 'c') {
            $categoryId = $model->mapCategoryId($item['cat']);
            $privacy = 'category';
        }
        $user = $xfDb->fetchRow('
			SELECT user_id, username
			FROM xf_user
			WHERE user_id = ?
		', $item['userid']);
        if (!$user) {
            return false;
        }
        $xengalleryMedia = array('media_title' => $this->_convertToUtf8($item['title'], true), 'media_description' => XenForo_Template_Helper_Core::helperSnippet($this->_convertToUtf8($item['description'], true), 0, array('stripHtml' => true)), 'media_date' => $item['date'], 'last_edit_date' => $item['lastpost'], 'last_comment_date' => $item['lastpost'], 'media_type' => $mediaType, 'media_state' => 'visible', 'album_id' => $albumId, 'category_id' => $categoryId, 'media_privacy' => $privacy, 'attachment_id' => 0, 'user_id' => $user['user_id'], 'username' => $user['username'], 'ip_id' => $model->getLatestIpIdFromUserId($user['user_id']), 'likes' => 0, 'like_users' => array(), 'comment_count' => $item['numcom'], 'rating_count' => 0, 'media_view_count' => $item['views']);
        $xfAttachment = array('data_id' => 0, 'content_type' => 'xengallery_media', 'content_id' => 0, 'attach_date' => $item['date'], 'temp_hash' => '', 'unassociated' => 0, 'view_count' => $item['views']);
        $xfAttachmentData = array('user_id' => $user['user_id'], 'upload_date' => $item['date'], 'filename' => $item['bigimage'], 'attach_count' => 1);
        $importedMediaId = $model->importMedia($item['id'], $tempFile, '', $xengalleryMedia, $xfAttachment, $xfAttachmentData);
        @unlink($tempFile);
        return $importedMediaId;
    }
示例#21
0
 protected function _applyAvatar($data)
 {
     $success = false;
     if (!$data) {
         return false;
     }
     $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     if ($avatarFile) {
         file_put_contents($avatarFile, $data);
         try {
             $dwData = $this->getModelFromCache('XenForo_Model_Avatar')->applyAvatar($this->get('user_id'), $avatarFile);
             if ($dwData) {
                 $this->bulkSet($dwData);
             }
             $success = true;
         } catch (XenForo_Exception $e) {
         }
         @unlink($avatarFile);
     }
     return $success;
 }
    public function stepMedia($start, array $options)
    {
        $options = array_merge(array('path' => isset($this->_config['albumPicPath']) ? $this->_config['albumPicPath'] : '', 'limit' => 5, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        $imageTypes = $sDb->quote(array_keys($this->_imageTypeMap));
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(attachment.attachmentid)
				FROM ' . $prefix . 'attachment AS attachment
				LEFT JOIN ' . $prefix . 'filedata AS filedata ON
					(attachment.filedataid = filedata.filedataid)
				WHERE filedata.extension IN (' . $imageTypes . ')
					AND attachment.state = \'visible\'
					AND attachment.contenttypeid = \'8\'
			');
        }
        $media = $sDb->fetchAll($sDb->limit('
				SELECT attachment.*, filedata.*, user.username,
					album.*, attachment.attachmentid
				FROM ' . $prefix . 'attachment AS attachment
				LEFT JOIN ' . $prefix . 'album AS album ON
					(attachment.contentid = album.albumid)
				LEFT JOIN ' . $prefix . 'filedata AS filedata ON
					(attachment.filedataid = filedata.filedataid)
				LEFT JOIN ' . $prefix . 'user AS user ON
					(attachment.userid = user.userid)
				WHERE attachment.attachmentid > ' . $sDb->quote($start) . '
					AND filedata.extension IN (' . $imageTypes . ')
					AND attachment.state = \'visible\'
					AND attachment.contenttypeid = \'8\'
				ORDER BY attachment.attachmentid
			', $options['limit']));
        if (!$media) {
            return true;
        }
        $this->_userIdMap = $this->_importModel->getUserIdsMapFromArray($media, 'userid');
        $model = $this->_getMediaGalleryImportersModel();
        $next = 0;
        $total = 0;
        foreach ($media as $item) {
            $next = $item['attachmentid'];
            if (!isset($this->_userIdMap[$item['userid']])) {
                continue;
            }
            $albumId = $model->mapAlbumId($item['albumid']);
            $userId = $this->_userIdMap[$item['userid']];
            if (!$options['path']) {
                $fData = $sDb->fetchOne('
					SELECT filedata
					FROM ' . $prefix . 'filedata
					WHERE filedataid = ' . $sDb->quote($item['filedataid']));
                if ($fData === '') {
                    continue;
                }
                $tempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
                if (!$tempFile || !@file_put_contents($tempFile, $fData)) {
                    continue;
                }
            } else {
                if ($this->_config['attachType'] == self::ATTACH_AS_FILES_NEW) {
                    $pictureFileOrig = "{$options['path']}/" . implode('/', str_split($item['userid'])) . "/{$item['filedataid']}.attach";
                } elseif ($this->_config['attachType'] == self::ATTACH_AS_FILES_OLD) {
                    $pictureFileOrig = "{$options['path']}/{$item['userid']}/{$item['filedataid']}.attach";
                }
                if (!file_exists($pictureFileOrig)) {
                    continue;
                }
                $tempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
                copy($pictureFileOrig, $tempFile);
            }
            $commentCount = $sDb->fetchOne('
				SELECT COUNT(*)
				FROM ' . $prefix . 'picturecomment
				WHERE filedataid = ?
			', $item['filedataid']);
            $titleMaxLength = XenForo_Application::getOptions()->xengalleryMaxTitleLength;
            $xengalleryMedia = array('media_title' => $item['caption'] ? utf8_substr($this->_convertToUtf8($item['caption'], true), 0, $titleMaxLength) : utf8_substr($this->_convertToUtf8($item['filename'], true), 0, $titleMaxLength), 'media_date' => $item['dateline'], 'last_edit_date' => XenForo_Application::$time, 'media_type' => 'image_upload', 'media_state' => 'visible', 'album_id' => $albumId, 'category_id' => 0, 'media_privacy' => $item['state'] == 'private' ? $item['state'] : 'public', 'attachment_id' => 0, 'user_id' => $userId, 'username' => $this->_convertToUtf8($item['username'], true), 'ip_id' => $model->getLatestIpIdFromUserId($userId), 'likes' => 0, 'like_users' => array(), 'comment_count' => $commentCount, 'rating_count' => 0, 'media_view_count' => 0);
            $xfAttachment = array('data_id' => 0, 'content_type' => 'xengallery_media', 'content_id' => 0, 'attach_date' => $item['dateline'], 'temp_hash' => '', 'unassociated' => 0, 'view_count' => 0);
            $xfAttachmentData = array('user_id' => $userId, 'upload_date' => $item['dateline'], 'filename' => $this->_convertToUtf8($item['filename']), 'attach_count' => 1);
            $imported = $model->importMedia($item['attachmentid'], $tempFile, '', $xengalleryMedia, $xfAttachment, $xfAttachmentData);
            if ($imported) {
                $total++;
            }
            @unlink($tempFile);
        }
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next, $options['max']));
    }
示例#23
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;
     }
 }
示例#24
0
 public function rebuildThumbnail(array $media, array $imageInfo, $deleteExisting = true, $skipThumbnail = 0)
 {
     $originalThumbFile = $this->getMediaThumbnailFilePath($media);
     $media['file_hash'] = $imageInfo['file_hash'];
     $options = XenForo_Application::getOptions();
     $thumbFile = $this->getMediaThumbnailFilePath($media);
     $thumbImage = false;
     if ($skipThumbnail) {
         XenForo_Helper_File::safeRename($originalThumbFile, $thumbFile);
     } else {
         if ($media['media_type'] == 'image_upload') {
             $originalFile = $this->getOriginalDataFilePath($media, true);
             $thumbImage = new XenGallery_Helper_Image($originalFile);
         } else {
             if ($media['media_type'] == 'video_upload') {
                 $originalFile = $this->getAttachmentDataFilePath($media);
                 $tempThumbFile = false;
                 if ($options->get('xengalleryVideoTranscoding', 'thumbnail')) {
                     try {
                         $video = new XenGallery_Helper_Video($originalFile);
                         $tempThumbFile = $video->getKeyFrame();
                     } catch (XenForo_Exception $e) {
                     }
                 }
                 if (!$tempThumbFile) {
                     $tempThumbFile = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
                     if ($tempThumbFile) {
                         @copy($options->xengalleryDefaultNoThumb, $tempThumbFile);
                     }
                 }
                 $thumbImage = new XenGallery_Helper_Image($tempThumbFile);
             }
         }
         if ($thumbImage) {
             $thumbImage->resize($options->xengalleryThumbnailDimension['width'], $options->xengalleryThumbnailDimension['height'], 'crop');
             $thumbnailed = $thumbImage->saveToPath($thumbFile);
             if ($thumbnailed && $deleteExisting) {
                 @unlink($originalThumbFile);
             }
         }
     }
     $mediaWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Media');
     $mediaWriter->setExistingData($media);
     $mediaWriter->bulkSet(array('last_edit_date' => XenForo_Application::$time, 'thumbnail_date' => $media['thumbnail_date']));
     $mediaWriter->save();
     if ($media['album_id']) {
         $albumWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Album');
         $albumWriter->setExistingData($media['album_id']);
         if (!$albumWriter->get('manual_media_cache') && !$albumWriter->get('album_thumbnail_date')) {
             $mediaItems = $this->getMediaForAlbumCache($media['album_id']);
             $albumWriter->bulkSet(array('last_update_date' => XenForo_Application::$time, 'media_cache' => serialize($mediaItems)));
             $albumWriter->save();
         }
     }
 }
示例#25
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');
 }
示例#26
0
 public function addWatermark($inputImage, $fileType = null, $viewingUser = null, $isRebuild = false)
 {
     $this->standardizeViewingUserReference($viewingUser);
     $fileType = $this->getImageFileType($inputImage, $fileType);
     if ($fileType === null) {
         return false;
     }
     $xenOptions = XenForo_Application::getOptions();
     if (empty($xenOptions->sonnbXG_watermark['enabled'])) {
         return false;
     }
     $isImagick = $xenOptions->imageLibrary['class'] === 'imPecl';
     $watermarkOptions = $this->getWatermarkSettings($isRebuild);
     try {
         switch ($watermarkOptions['overlay']) {
             case 'image':
                 $watermarkFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
                 if (Zend_Uri::check($watermarkOptions['url'])) {
                     $client = XenForo_Helper_Http::getClient($watermarkOptions['url']);
                     $response = $client->request('GET');
                     if ($response->isSuccessful()) {
                         @file_put_contents($watermarkFile, $response->getBody());
                     } else {
                         return false;
                     }
                 } elseif (is_file($watermarkOptions['url'])) {
                     $this->copyFile($watermarkOptions['url'], $watermarkFile);
                 } else {
                     return false;
                 }
                 if (!($watermarkFileInfo = @getimagesize($watermarkFile))) {
                     return false;
                 }
                 if ($isImagick) {
                     $srcResource = new Imagick($inputImage);
                     $wtmResource = new Imagick($watermarkFile);
                 } else {
                     $srcResource = $this->createImageFromFile($inputImage, $fileType);
                     //TODO: Check watermark image size against input image.
                     $wtmResource = $this->createImageFromFile($watermarkFile, $watermarkFileInfo[2]);
                 }
                 $this->addWatermarkBySource($srcResource, $wtmResource, $watermarkOptions['position'], $watermarkOptions['margin'], $inputImage, $fileType);
                 @unlink($watermarkFile);
                 break;
             case 'text':
             default:
                 $findArray = array('{username}', '{user_id}', '{email}');
                 $replaceArray = array($viewingUser['username'], $viewingUser['user_id'], $viewingUser['email']);
                 $watermarkOptions['text'] = str_replace($findArray, $replaceArray, $watermarkOptions['text']);
                 if (empty($watermarkOptions['text'])) {
                     return false;
                 }
                 if ($isImagick) {
                     $wtmResource = new Imagick();
                     $draw = new ImagickDraw();
                     $color = new ImagickPixel($watermarkOptions['textColor']);
                     $background = new ImagickPixel('none');
                     $draw->setFontSize($watermarkOptions['textSize']);
                     $draw->setFillColor($color);
                     $draw->setStrokeAntialias(true);
                     $draw->setTextAntialias(true);
                     $metrics = $wtmResource->queryFontMetrics($draw, $watermarkOptions['text']);
                     $draw->annotation(0, $metrics['ascender'], $watermarkOptions['text']);
                     $wtmResource->newImage($metrics['textWidth'], $metrics['textHeight'], $background);
                     $wtmResource->setImageFormat('png');
                     $wtmResource->drawImage($draw);
                     $srcResource = new Imagick($inputImage);
                 } else {
                     $padding = 10;
                     $font = 'styles/sonnb/XenGallery/watermark.ttf';
                     if (!empty($watermarkOptions['font']) && is_file($watermarkOptions['font'])) {
                         $font = $watermarkOptions['font'];
                     }
                     if (function_exists('imagettfbbox')) {
                         $textDimension = imagettfbbox($watermarkOptions['textSize'], 0, $font, $watermarkOptions['text']);
                         $width = abs($textDimension[4] - $textDimension[0]) + $padding;
                         $height = abs($textDimension[5] - $textDimension[1]) + $padding;
                     } else {
                         $width = ImageFontWidth($watermarkOptions['textSize']) * strlen($watermarkOptions['text']);
                         $height = ImageFontHeight($watermarkOptions['textSize']);
                     }
                     $wtmResource = @imagecreatetruecolor($width, $height);
                     if (strtolower($watermarkOptions['bgColor']) === 'transparent') {
                         imagesavealpha($wtmResource, true);
                         $bgColor = imagecolorallocatealpha($wtmResource, 0, 0, 0, 127);
                         imagefill($wtmResource, 0, 0, $bgColor);
                     } else {
                         $bgColorRbg = $this->hex2rgb($watermarkOptions['bgColor']);
                         $bgColor = imagecolorallocate($wtmResource, $bgColorRbg['red'], $bgColorRbg['green'], $bgColorRbg['blue']);
                         imagefill($wtmResource, 0, 0, $bgColor);
                     }
                     $txtColorRbg = $this->hex2rgb($watermarkOptions['textColor']);
                     $txtColor = imagecolorallocate($wtmResource, $txtColorRbg['red'], $txtColorRbg['green'], $txtColorRbg['blue']);
                     imagettftext($wtmResource, $watermarkOptions['textSize'], 0, $padding / 2, $height - $padding / 2, $txtColor, $font, $watermarkOptions['text']);
                     $srcResource = $this->createImageFromFile($inputImage, $fileType);
                 }
                 $this->addWatermarkBySource($srcResource, $wtmResource, $watermarkOptions['position'], $watermarkOptions['margin'], $inputImage, $fileType);
                 break;
         }
     } catch (Exception $e) {
         XenForo_Error::logException($e);
         return false;
     }
 }
示例#27
0
 public function addToFilesFromUrl($key, $url, &$errorText)
 {
     if (!Zend_Uri::check($url)) {
         $errorText = new XenForo_Phrase('xengallery_please_enter_a_valid_url');
         return false;
     }
     $tempName = tempnam(XenForo_Helper_File::getTempDir(), 'xfmg');
     $originalName = basename(parse_url($url, PHP_URL_PATH));
     $client = XenForo_Helper_Http::getClient($url);
     $request = $client->request('GET');
     if (!$request->isSuccessful()) {
         $errorText = new XenForo_Phrase('xengallery_no_media_found_at_the_url_provided');
         return false;
     }
     $rawImage = $request->getBody();
     $fp = fopen($tempName, 'w');
     fwrite($fp, $rawImage);
     fclose($fp);
     $imageInfo = @getimagesize($rawImage);
     $mimeType = '';
     if ($imageInfo) {
         $mimeType = $imageInfo['mime'];
     }
     $_FILES[$key] = array('name' => $originalName, 'type' => $mimeType ? $mimeType : 'image/jpg', 'tmp_name' => $tempName, 'error' => 0, 'size' => strlen($rawImage));
     return $tempName;
 }
示例#28
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;
 }
示例#29
0
 protected function _applyAvatar(array $user, $data)
 {
     $success = false;
     if (!$data || !$user['user_id']) {
         return false;
     }
     $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     if ($avatarFile) {
         file_put_contents($avatarFile, $data);
         try {
             $user = array_merge($user, $this->getModelFromCache('XenForo_Model_Avatar')->applyAvatar($user['user_id'], $avatarFile));
             $success = true;
         } catch (XenForo_Exception $e) {
         }
         @unlink($avatarFile);
     }
     return $success;
 }
示例#30
0
    public function stepAttachments($start, array $options)
    {
        $options = array_merge(array('path' => isset($this->_config['attachmentPath']) ? $this->_config['attachmentPath'] : '', 'limit' => 50, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        /* @var $model XenForo_Model_Import */
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(attachmentid)
				FROM ' . $prefix . 'attachment
			');
        }
        $attachments = $sDb->fetchAll($sDb->limit('
				SELECT attachmentid, userid, dateline, filename, counter, postid
				FROM ' . $prefix . 'attachment
				WHERE attachmentid > ' . $sDb->quote($start) . '
					AND visible = 1
				ORDER BY attachmentid
			', $options['limit']));
        if (!$attachments) {
            return true;
        }
        $next = 0;
        $total = 0;
        $userIdMap = $model->getUserIdsMapFromArray($attachments, 'userid');
        $postIdMap = $model->getPostIdsMapFromArray($attachments, 'postid');
        $posts = $model->getModelFromCache('XenForo_Model_Post')->getPostsByIds($postIdMap);
        foreach ($attachments as $attachment) {
            $next = $attachment['attachmentid'];
            $newPostId = $this->_mapLookUp($postIdMap, $attachment['postid']);
            if (!$newPostId) {
                continue;
            }
            if (!$options['path']) {
                $fData = $sDb->fetchOne('
					SELECT filedata
					FROM ' . $prefix . 'attachment
					WHERE attachmentid = ' . $sDb->quote($attachment['attachmentid']));
                if ($fData === '') {
                    continue;
                }
                $attachFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
                if (!$attachFile || !@file_put_contents($attachFile, $fData)) {
                    continue;
                }
                $isTemp = true;
            } else {
                $attachFileOrig = "{$options['path']}/" . implode('/', str_split($attachment['userid'])) . "/{$attachment['attachmentid']}.attach";
                if (!file_exists($attachFileOrig)) {
                    continue;
                }
                $attachFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
                copy($attachFileOrig, $attachFile);
                $isTemp = true;
            }
            $success = $model->importPostAttachment($attachment['attachmentid'], $this->_convertToUtf8($attachment['filename']), $attachFile, $this->_mapLookUp($userIdMap, $attachment['userid'], 0), $newPostId, $attachment['dateline'], array('view_count' => $attachment['counter']), array($this, 'processAttachmentTags'), $posts[$newPostId]['message']);
            if ($success) {
                $total++;
            }
            if ($isTemp) {
                @unlink($attachFile);
            }
        }
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next, $options['max']));
    }