public function renderRaw()
 {
     $attachment = $this->_params['attachment'];
     if (!headers_sent() && function_exists('header_remove')) {
         header_remove('Expires');
         header('Cache-control: private');
     }
     $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
     $imageTypes = array('svg' => 'image/svg+xml', 'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png');
     if (isset($imageTypes[$extension]) && ($attachment['width'] && $attachment['height'])) {
         $this->_response->setHeader('Content-type', $imageTypes[$extension], true);
         $this->setDownloadFileName($attachment['filename'], true);
     } 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', $attachment['file_size'], true);
     $this->_response->setHeader('X-Content-Type-Options', 'nosniff');
     $attachmentFile = $this->_params['attachmentFile'];
     $options = XenForo_Application::getOptions();
     if ($options->SV_AttachImpro_XAR) {
         if (SV_AttachmentImprovements_AttachmentHelper::ConvertFilename($attachmentFile)) {
             if (XenForo_Application::debugMode() && $options->SV_AttachImpro_log) {
                 XenForo_Error::debug('X-Accel-Redirect:' . $attachmentFile);
             }
             $this->_response->setHeader('X-Accel-Redirect', $attachmentFile);
             return '';
         }
         if (XenForo_Application::debugMode() && $options->SV_AttachImpro_log) {
             XenForo_Error::debug('X-Accel-Redirect skipped');
         }
     }
     return new XenForo_FileOutput($attachmentFile);
 }
Exemple #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]);
         }
     }
 }
Exemple #3
0
 public function actionIndex()
 {
     $attachmentId = $this->_input->filterSingle('attachment_id', XenForo_Input::UINT);
     $cache = XenForo_Application::getCache();
     $imageTypes = array('gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png');
     if ($cache) {
         $attachment = unserialize($cache->load('attachment_cache_' . md5($attachmentId)));
         if (!$attachment) {
             $attachment = $this->_getAttachmentOrError($attachmentId);
             $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
             if (isset($imageTypes[$extension])) {
                 $cache->save(serialize($attachment), 'attachment_cache_' . md5($attachmentId), array(), 3600);
             }
         }
     } else {
         $attachment = $this->_getAttachmentOrError($attachmentId);
     }
     $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
     if (!in_array($extension, array_keys($imageTypes))) {
         return parent::actionIndex();
     }
     $attachmentModel = $this->_getAttachmentModel();
     $filePath = $attachmentModel->getAttachmentDataFilePath($attachment);
     if (!file_exists($filePath) || !is_readable($filePath)) {
         return $this->responseError(new XenForo_Phrase('attachment_cannot_be_shown_at_this_time'));
     }
     $this->canonicalizeRequestUrl(XenForo_Link::buildPublicLink('attachments', $attachment));
     $eTag = $this->_request->getServer('HTTP_IF_NONE_MATCH');
     $this->_routeMatch->setResponseType('raw');
     if ($eTag && $eTag == $attachment['attach_date']) {
         return $this->responseView('XenForo_ViewPublic_Attachment_View304');
     }
     $viewParams = array('attachment' => $attachment, 'attachmentFile' => $filePath);
     return $this->responseView('XenForo_ViewPublic_Attachment_View', '', $viewParams);
 }
Exemple #4
0
 public static function get_attach_file_name($attachmentFilename)
 {
     if ($attachmentFilename) {
         $extension = XenForo_Helper_File::getFileExtension($attachmentFilename);
         return str_replace($extension, '', $attachmentFilename);
     }
     return '';
 }
 protected function _createAddonFile()
 {
     $contents = str_replace('/>', '>', file_get_contents($this->_path . '/build-files/addon.xml'));
     $dir = new DirectoryIterator($this->_path . '/build-files');
     foreach ($dir as $file) {
         if ($file->isDot() or $file->isDir() or XenForo_Helper_File::getFileExtension($file->getFilename()) != 'xml' or $file->getFilename() == 'addon.xml') {
             continue;
         }
         $contents .= str_replace('<?xml version="1.0" encoding="utf-8"?>' . "\n", '', file_get_contents($file->getPathname()));
     }
     return $contents . '</addon>';
 }
 public function renderRaw()
 {
     $extension = XenForo_Helper_File::getFileExtension($this->_params['thumbnailPath']);
     $imageTypes = array('gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png');
     $this->_response->setHeader('Content-type', $imageTypes[$extension], true);
     $this->setDownloadFileName($this->_params['thumbnailPath'], true);
     $this->_response->setHeader('X-Content-Type-Options', 'nosniff');
     if (!is_readable($this->_params['thumbnailPath']) || !file_exists($this->_params['thumbnailPath'])) {
         $this->_params['thumbnailPath'] = XenGallery_Template_Helper_Core::helperDummyImage('visible', '', '', true);
     }
     return new XenForo_FileOutput($this->_params['thumbnailPath']);
 }
Exemple #7
0
 public function renderRaw()
 {
     $parent = parent::renderRaw();
     $attachment = $this->_params['attachment'];
     $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('Expires', gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime('+30 days')), true);
         $this->_response->setHeader('Last-Modified', gmdate('D, d M Y H:i:s \\G\\M\\T', $attachment['attach_date']), true);
         $this->_response->setHeader('Cache-Control', 'public, max-age=2592000', true);
     }
     return $parent;
 }
Exemple #8
0
 public function actionAddOnsServerFile()
 {
     $q = $this->_input->filterSingle('q', XenForo_Input::STRING);
     $paths = array();
     /** @var XenForo_Application $app */
     $app = XenForo_Application::getInstance();
     $libraryPath = sprintf('%s/library', $app->getRootDir());
     $library = 'library';
     $libraryLength = min(strlen($library), strlen($q));
     if (strlen($q) > 0 && strpos($q, '.') === false && substr($q, 0, $libraryLength) === substr($library, 0, $libraryLength)) {
         if (strlen($q) < 7) {
             $q = 'library/';
             $paths[] = 'library';
         }
         $parts = explode('/', $q);
         array_shift($parts);
         $prefix = '';
         if (count($parts) > 0) {
             $prefix = array_pop($parts);
         }
         $path = rtrim(sprintf('%s/%s', $libraryPath, implode('/', $parts)), '/');
         if (is_dir($path)) {
             $contents = scandir($path);
             foreach ($contents as $content) {
                 if (substr($content, 0, 1) === '.') {
                     continue;
                 }
                 if ($prefix !== '' && substr($content, 0, strlen($prefix)) !== $prefix) {
                     continue;
                 }
                 $contentPath = sprintf('%s/%s', $path, $content);
                 if (is_dir($contentPath)) {
                     $paths[] = $contentPath;
                 } else {
                     $ext = XenForo_Helper_File::getFileExtension($contentPath);
                     if ($ext === 'xml') {
                         array_unshift($paths, $contentPath);
                     }
                 }
             }
         }
     }
     $results = array();
     foreach ($paths as $path) {
         $relativePath = preg_replace('#^' . preg_quote($app->getRootDir()) . '/#', '', $path);
         $results[$relativePath] = basename($path);
     }
     $view = $this->responseView();
     $view->jsonParams = array('results' => $results);
     return $view;
 }
Exemple #9
0
 public function getAttachmentsForXenGalleryByAttachmentIds($attachmentIds)
 {
     $db = $this->_getDb();
     $attachments = $this->fetchAllKeyed("\n\t\t\t\tSELECT attachment.*, attachment_data.*, post.username, post.user_id\n\t\t\t\tFROM xf_attachment AS attachment\n\t\t\t\t\tLEFT JOIN xf_attachment_data AS attachment_data\n\t\t\t\t\t\tON (attachment.data_id = attachment_data.data_id)\n\t\t\t\t\tLEFT JOIN xf_post AS post\n\t\t\t\t\t\tON (attachment.content_id = post.post_id)\n\t\t\t\tWHERE attachment.attachment_id IN (" . $db->quote($attachmentIds) . ")\n\t\t\t\t\tAND attachment.content_type = 'post'\n\t\t\t\t\tAND post.message_state = 'visible'\n\t\t\t\tORDER BY attachment.attachment_id ASC", 'attachment_id');
     if ($attachments) {
         foreach ($attachments as $attachId => $attachment) {
             $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
             if (!in_array($extension, array('gif', 'png', 'jpg', 'jpeg', 'jpe'))) {
                 unset($attachments[$attachId]);
             }
         }
     }
     return $attachments;
 }
Exemple #10
0
 public static function getTemplateIdFromFilePath($filePath)
 {
     $basename = basename($filePath);
     $extension = XenForo_Helper_File::getFileExtension($basename);
     if (!in_array($extension, array('html', 'css'))) {
         return 0;
     }
     $sanExtension = substr($basename, 0, -1 * (strlen($extension) + 1));
     $parts = explode('_', $sanExtension);
     $lastPart = array_pop($parts);
     if (!is_numeric($lastPart)) {
         return 0;
     }
     return intval($lastPart);
 }
Exemple #11
0
 public function renderRaw()
 {
     $attachment = $this->_params['attachment'];
     $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);
     } else {
         $this->_response->setHeader('Content-type', 'unknown/unknown', true);
         $this->setDownloadFileName($attachment['filename']);
     }
     $this->_response->setHeader('ETag', $attachment['attach_date'], true);
     $this->_response->setHeader('Content-Length', $attachment['file_size'], true);
     return new XenForo_FileOutput($this->_params['attachmentFile']);
 }
Exemple #12
0
 public function renderRaw()
 {
     $image = $this->_params['image'];
     $filename = basename($image['url']);
     $extension = XenForo_Helper_File::getFileExtension($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($filename, true);
     } else {
         $this->_response->setHeader('Content-type', 'application/octet-stream', true);
         $this->setDownloadFileName($filename);
     }
     $this->_response->setHeader('ETag', '"' . $image['fetch_date'] . '"', true);
     $this->_response->setHeader('Content-Length', $image['file_size'], true);
     $this->_response->setHeader('X-Content-Type-Options', 'nosniff');
     return new XenForo_FileOutput($image['file_path']);
 }
Exemple #13
0
 public function renderHtml()
 {
     parent::renderHtml();
     if (isset($this->_params['editorTemplate']) && $this->_params['editorTemplate']->getParam('showWysiwyg')) {
         $attachPattern = '/\\[ATTACH(.*?)\\](.*?)\\[\\/ATTACH\\]/si';
         $count = @preg_match_all($attachPattern, $this->_params['post']['message'], $matches);
         if ($count) {
             $cache = XenForo_Application::getCache();
             $imageTypes = array('gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png');
             foreach ($matches[0] as $position => $match) {
                 if ($match && intval($matches[2][$position]) > 0) {
                     $attachmentId = intval($matches[2][$position]);
                     if ($cache) {
                         $attachment = unserialize($cache->load('attachment_cache_' . md5($attachmentId)));
                         if (!$attachment) {
                             $attachment = $this->_getAttachment($attachmentId);
                             $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
                             if (isset($imageTypes[$extension])) {
                                 $cache->save(serialize($attachment), 'attachment_cache_' . md5($attachmentId), array(), 3600);
                             }
                         }
                     } else {
                         $attachment = $this->_getAttachment($attachmentId);
                     }
                     if ($attachment && $attachment['thumbnail_width']) {
                         $attachment = $this->_getAttachmentModel()->prepareAttachment($attachment);
                         if ($matches[1][$position]) {
                             $replace = '<img class="attachFull bbCodeImage" src="' . XenForo_Link::buildPublicLink('attachments', array('attachment_id' => $attachment['attachment_id'])) . '" alt="attachFull' . $attachment['attachment_id'] . '" data-mce-src="' . XenForo_Link::buildPublicLink('attachments', array('attachment_id' => $attachment['attachment_id'])) . '" />';
                         } else {
                             $replace = '<img class="attachThumb bbCodeImage" src="' . $attachment['thumbnailUrl'] . '" alt="attachThumb' . $attachment['attachment_id'] . '" data-mce-src="' . $attachment['thumbnailUrl'] . '" />';
                         }
                     }
                     if (!empty($replace)) {
                         $htmlMessage = str_replace($match, $replace, $this->_params['editorTemplate']->getParam('messageHtml'));
                         $this->_params['editorTemplate']->setParam('messageHtml', $htmlMessage);
                     }
                 }
             }
         }
     }
 }
Exemple #14
0
 public function renderTagAttach(array $tag, array $rendererStates)
 {
     $imageTypes = array('gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png');
     if (empty($rendererStates['viewAttachments'])) {
         $rendererStates['viewAttachments'] = true;
     }
     $attachmentId = intval($this->stringifyTree($tag['children']));
     if (!empty($rendererStates['attachments'][$attachmentId])) {
         $extension = XenForo_Helper_File::getFileExtension($rendererStates['attachments'][$attachmentId]['filename']);
         if (!empty($rendererStates['attachments'][$attachmentId]['temp_hash'])) {
             $rendererStates['attachments'][$attachmentId]['temp_hash'] = '';
         }
         if (in_array($extension, array_keys($imageTypes))) {
             $rendererStates['viewAttachments'] = true;
         }
     } else {
         if ($tag['option'] == 'full' && $tag['children'] && $rendererStates['viewAttachments'] && $rendererStates['lightBox'] && $attachmentId) {
             $cache = XenForo_Application::getCache();
             if ($cache) {
                 $attachment_check = unserialize($cache->load('attachment_cache_' . md5($attachmentId)));
                 if (!$attachment_check) {
                     $attachment_check = $this->_getAttachmentModel()->getAttachmentById($attachmentId);
                     $cache->save(serialize($attachment_check), 'attachment_cache_' . md5($attachmentId), array(), 3600);
                 }
             } else {
                 $attachment_check = $this->_getAttachmentModel()->getAttachmentById($attachmentId);
             }
             if ($attachment_check && in_array(XenForo_Helper_File::getFileExtension($attachment_check['filename']), array_keys($imageTypes))) {
                 $attachment = $this->_getAttachmentModel()->prepareAttachment($attachment_check);
                 if (!empty($attachment['temp_hash'])) {
                     $attachment['temp_hash'] = '';
                 }
                 $rendererStates['canView'] = true;
                 $rendererStates['validAttachment'] = true;
                 $rendererStates['viewAttachments'] = true;
                 $rendererStates['attachments'][$attachment['attachment_id']] = $attachment;
             }
         }
     }
     return parent::renderTagAttach($tag, $rendererStates);
 }
Exemple #15
0
 public function renderRaw()
 {
     $attachment = $this->_params['attachment'];
     if (!headers_sent() && function_exists('header_remove')) {
         header_remove('Expires');
         header('Cache-control: private');
     }
     $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);
     } 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', $attachment['file_size'], true);
     $this->_response->setHeader('X-Content-Type-Options', 'nosniff');
     return new XenForo_FileOutput($this->_params['attachmentFile']);
 }
Exemple #16
0
 /**
  * Constructor.
  *
  * @param string $fileName User-supplied file name
  * @param string $tempFile Upload temporary file name; this can be an empty string to account for uploads that are too large
  */
 public function __construct($fileName, $tempFile)
 {
     if ($tempFile && !file_exists($tempFile) && !is_readable($tempFile)) {
         throw new XenForo_Exception('The temporary file for the upload cannot be found.');
     }
     $this->_fileName = $fileName;
     $this->_extension = XenForo_Helper_File::getFileExtension($fileName);
     $this->_tempFile = $tempFile;
     // TODO: clean up internal files on shut down (can't use destruct as files may still be used)
 }
Exemple #17
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);
 }
Exemple #18
0
 /**
  * Fetches the image at the specified URL using the standard proxy config.
  *
  * @param string $url
  *
  * @return array
  */
 protected function _fetchImageForProxy($url)
 {
     $urlHash = md5($url);
     $urlParts = parse_url($url);
     XenForo_ImageProxyStream::register();
     // convert kilobytes to bytes
     XenForo_ImageProxyStream::setMaxSize(XenForo_Application::getOptions()->imageProxyMaxSize * 1024);
     $streamUri = 'xf-image-proxy://' . $urlHash . '-' . uniqid();
     $streamFile = XenForo_ImageProxyStream::getTempFile($streamUri);
     $requestFailed = true;
     $error = false;
     $imageMeta = null;
     $fileName = !empty($urlParts['path']) ? basename($urlParts['path']) : '';
     $mimeType = '';
     $fileSize = 0;
     $image = false;
     $requestUrl = strtr($url, array(' ' => '+'));
     if (preg_match_all('/[^A-Za-z0-9._~:\\/?#\\[\\]@!$&\'()*+,;=%-]/', $requestUrl, $matches)) {
         foreach ($matches[0] as $match) {
             $requestUrl = str_replace($match[0], '%' . strtoupper(dechex(ord($match[0]))), $requestUrl);
         }
     }
     try {
         $response = XenForo_Helper_Http::getClient($requestUrl, array('output_stream' => $streamUri, 'timeout' => 10))->setHeaders('Accept-encoding', 'identity')->request('GET');
         if ($response->isSuccessful()) {
             $disposition = $response->getHeader('Content-Disposition');
             if (is_array($disposition)) {
                 $disposition = end($disposition);
             }
             if ($disposition && preg_match('/filename=(\'|"|)(.+)\\1/siU', $disposition, $match)) {
                 $fileName = $match[2];
             }
             if (!$fileName) {
                 $fileName = 'image';
             }
             $mimeHeader = $response->getHeader('Content-Type');
             if (is_array($mimeHeader)) {
                 $mimeHeader = end($mimeHeader);
             }
             $mimeType = $mimeHeader ? $mimeHeader : 'unknown/unknown';
             $imageMeta = XenForo_ImageProxyStream::getMetaData($streamUri);
             if (!empty($imageMeta['error'])) {
                 switch ($imageMeta['error']) {
                     case 'not_image':
                         $error = new XenForo_Phrase('file_not_an_image');
                         break;
                     case 'too_large':
                         $error = new XenForo_Phrase('file_is_too_large');
                         break;
                     case 'invalid_type':
                         $error = new XenForo_Phrase('image_is_invalid_type');
                         break;
                     default:
                         $error = $imageMeta['error'];
                 }
             } else {
                 $requestFailed = false;
                 $image = $imageMeta['image'];
                 $mimeType = $image['mime'];
                 $fileSize = $imageMeta['length'];
                 $extension = XenForo_Helper_File::getFileExtension($fileName);
                 $extensionMap = array(IMAGETYPE_GIF => array('gif'), IMAGETYPE_JPEG => array('jpg', 'jpeg', 'jpe'), IMAGETYPE_PNG => array('png'));
                 $validExtensions = $extensionMap[$image[2]];
                 if (!in_array($extension, $validExtensions)) {
                     $extensionStart = strrpos($fileName, '.');
                     $fileName = ($extensionStart ? substr($fileName, 0, $extensionStart) : $fileName) . '.' . $validExtensions[0];
                 }
             }
         } else {
             $error = new XenForo_Phrase('received_unexpected_response_code_x_message_y', array('code' => $response->getStatus(), 'message' => $response->getMessage()));
         }
     } catch (Exception $e) {
         $error = $e->getMessage();
         $response = null;
     }
     $response = null;
     return array('url' => $url, 'failed' => $requestFailed, 'error' => $error, 'image' => $image, 'fileName' => $fileName, 'mimeType' => $mimeType, 'fileSize' => $fileSize, 'tempFile' => $streamFile);
 }
Exemple #19
0
 protected function _importXenGalleryPhoto($attachment, sonnb_XenGallery_Model_Import $importModel, $albumId)
 {
     $attachmentModel = $this->_getAttachmentModel();
     if (is_callable(array($attachmentModel, 'bdAttachmentStore_useTempFile'))) {
         $bdAttachmentStore_useTempFile = true;
         $attachmentModel->bdAttachmentStore_useTempFile(true);
     }
     $imagePath = $this->_getAttachmentModel()->getAttachmentDataFilePath($attachment);
     if (!empty($bdAttachmentStore_useTempFile)) {
         $attachmentModel->bdAttachmentStore_useTempFile(false);
     }
     $photoData = array('file_size' => $attachment['file_size'], 'width' => $attachment['width'], 'height' => $attachment['height'], 'file_hash' => $attachment['file_hash'], 'upload_date' => $attachment['upload_date'], 'extension' => XenForo_Helper_File::getFileExtension($attachment['filename']));
     $importToStore = false;
     if (XenForo_Application::getOptions()->sonnbXG_importThreadStore) {
         $importToStore = true;
     }
     $photoDataNew = $importModel->importXenGalleryPhotoData($attachment['attachment_id'], $photoData);
     $importModel->createPhotoThumbnails($imagePath, $photoDataNew, $importToStore);
     $imagePrivacy = array('allow_view' => 'everyone', 'allow_view_data' => array(), 'allow_comment' => 'everyone', 'allow_comment_data' => array());
     $title = @pathinfo($attachment['filename'], PATHINFO_FILENAME);
     $photo = array('album_id' => $albumId, 'content_data_id' => $photoDataNew['content_data_id'], 'title' => $title ? $title : $photoDataNew['content_data_id'], 'description' => '', 'user_id' => $attachment['user_id'], 'username' => $attachment['username'], 'content_privacy' => @serialize($imagePrivacy), 'comment_count' => 0, 'view_count' => $attachment['view_count'], 'content_date' => $attachment['attach_date'], 'content_updated_date' => $attachment['attach_date'], 'position' => 0, 'content_state' => 'visible');
     $photoId = $importModel->importXenGalleryPhoto($attachment['attachment_id'], $photo, false);
     return $photoId;
 }
Exemple #20
0
    public function stepPhotos($start, array $options)
    {
        $options = array_merge(array('limit' => 10, 'processed' => 0, 'max' => false), $options);
        $db = $this->_db;
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $data = $db->fetchRow('
                SELECT MAX(attachment.attachment_id) AS max, COUNT(attachment.attachment_id) AS rows
                FROM xf_attachment AS attachment
					LEFT JOIN xf_post AS post
						ON (attachment.content_id = post.post_id)
					LEFT JOIN xf_thread AS thread
						ON (thread.thread_id = post.thread_id)
				WHERE thread.node_id = ?
					AND thread.discussion_state = \'visible\'
					AND attachment.content_type = \'post\'
					AND post.message_state = \'visible\'
			', $this->_config['node_id']);
            $options = array_merge($options, $data);
            return array(0, $options, "Processing Photos ...");
        }
        $images = $db->fetchAll($db->limit("\n    \t\t\t\tSELECT attachment.*, attachment_data.*, post.username, post.user_id, post.thread_id\n\t\t\t\t\tFROM xf_attachment AS attachment\n\t\t\t\t\t\tLEFT JOIN xf_attachment_data AS attachment_data\n\t\t\t\t\t\t\tON (attachment.data_id = attachment_data.data_id)\n\t\t\t\t\t\tLEFT JOIN xf_post AS post\n\t\t\t\t\t\t\tON (attachment.content_id = post.post_id)\n\t\t\t\t\t\tLEFT JOIN xf_thread AS thread\n\t\t\t\t\t\t\tON (thread.thread_id = post.thread_id)\n\t\t\t\t\tWHERE thread.node_id = ?\n\t\t\t\t\t\tAND thread.discussion_state = 'visible'\n\t\t\t\t\t\tAND attachment.attachment_id > ?\n\t\t\t\t\t\tAND attachment.content_type = 'post'\n\t\t\t\t\t\tAND post.message_state = 'visible'\n\t\t\t\t\tORDER BY attachment.attachment_id ASC\n    \t\t\t", $options['limit']), array($this->_config['node_id'], $start));
        if (!$images) {
            return true;
        }
        $next = 0;
        $last = 0;
        $total = 0;
        $position = 0;
        $albumIdMap = $model->getAlbumIdsMapFromArray($images, 'thread_id');
        foreach ($images as $image) {
            $next = $image['attachment_id'];
            if (empty($albumIdMap[$image['thread_id']])) {
                continue;
            }
            if (empty($image['user_id'])) {
                continue;
            }
            if ($last != $next) {
                $last = $next;
                $importPhotoData = array('file_size' => $image['file_size'], 'width' => $image['width'], 'height' => $image['height'], 'file_hash' => $image['file_hash'], 'upload_date' => $image['upload_date'], 'unassociated' => 0, 'extension' => XenForo_Helper_File::getFileExtension($image['filename']));
                if (!isset(sonnb_XenGallery_Model_ContentData::$typeMap[$importPhotoData['extension']])) {
                    continue;
                }
                $photoData = $model->importXenGalleryPhotoData($image['attachment_id'], $importPhotoData);
                $model->logImportData('sonnb_xengallery_data', $image['attachment_id'], $photoData['content_data_id']);
                $success = $this->_createPhotoData($image, $photoData);
                if ($success === false) {
                    continue;
                }
                $model->importXenGalleryContentDataConfirm($photoData);
                $title = @pathinfo($image['filename']);
                $import = array('album_id' => $albumIdMap[$image['thread_id']], 'content_data_id' => $photoData['content_data_id'], 'title' => $title ? $title['filename'] : $photoData['content_data_id'], 'description' => '', 'user_id' => $image['user_id'], 'username' => $image['username'], 'content_privacy' => array('allow_view' => 'everyone', 'allow_view_data' => array(), 'allow_comment' => 'everyone', 'allow_comment_data' => array()), 'comment_count' => 0, 'view_count' => $image['view_count'], 'content_date' => $image['attach_date'], 'content_updated_date' => $image['attach_date'], 'likes' => 0, 'like_users' => 'a:0:{}', 'position' => $position, 'content_state' => 'visible');
                if ($this->_config['retainKeys']) {
                    $import['content_id'] = $image['attachment_id'];
                }
                $photoId = $model->importXenGalleryPhoto($image['attachment_id'], $import);
                $model->logImportData('sonnb_xengallery_photo', $image['attachment_id'], $photoId);
                $position++;
            }
            $total++;
        }
        $options['processed'] += $total;
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($options['processed'], $options['rows']));
    }
Exemple #21
0
 protected function _getImageForAttachment($attachment, XenForo_Model $model)
 {
     // try to use full size link if possible
     $image = XenForo_Link::buildPublicLink('attachments', $attachment);
     if (Zend_URi::check($image) and substr($image, -1) !== '/') {
         $filename = basename($image);
         $ext = XenForo_Helper_File::getFileExtension($filename);
         if (in_array($ext, array('gif', 'jpg', 'jpeg', 'png'), true)) {
             return $image;
         }
     }
     // fallback to thumbnail
     $image = $model->getModelFromCache('XenForo_Model_Attachment')->getAttachmentThumbnailUrl($attachment);
     $image = XenForo_Link::convertUriToAbsoluteUri($image, true);
     return $image;
 }
 public function setFileName($fileName)
 {
     $this->_fileName = $fileName;
     $this->_extension = XenForo_Helper_File::getFileExtension($fileName);
 }
Exemple #23
0
 public function stepPhotos($start, array $options)
 {
     $options = array_merge(array('path' => isset($this->_config['attachmentPath']) ? trim($this->_config['attachmentPath']) : '', 'limit' => 10, 'processed' => 0, 'max' => false), $options);
     $sDb = $this->_sourceDb;
     $prefix = $this->_prefix;
     $model = $this->_importModel;
     if ($options['max'] === false) {
         $content = $sDb->fetchOne("\n    \t\t\t\tSELECT contenttypeid\n    \t\t\t\tFROM " . $prefix . "contenttype\n    \t\t\t\tWHERE class = 'Album'\n    \t\t\t");
         $options['albumType'] = intval($content);
         $data = $sDb->fetchRow("\n    \t\t\t\tSELECT MAX(attachmentid) AS max, COUNT(attachmentid) AS rows\n    \t\t\t\tFROM " . $prefix . "attachment\n    \t\t\t\tWHERE state = 'visible'\n    \t\t\t\tAND contenttypeid = ? ", $sDb->quote($options['albumType']));
         $options = array_merge($options, $data);
         return array(0, $options, "Processing Photos ...");
     }
     $attachments = $sDb->fetchAll($sDb->limit("\n    \t\t\t\tSELECT attachment.*, user.username, filedata.filesize,\n    \t\t\t\t\tfiledata.filehash, filedata.width, filedata.height, filedata.extension\n    \t\t\t\tFROM " . $prefix . "attachment AS attachment\n    \t\t\t\tLEFT JOIN " . $prefix . "filedata AS filedata ON (filedata.filedataid = attachment.filedataid)\n    \t\t\t\tLEFT JOIN " . $prefix . "user AS user ON (attachment.userid = user.userid)\n    \t\t\t\tWHERE attachment.attachmentid > " . $sDb->quote($start) . "\n    \t\t\t\tAND attachment.state = 'visible'\n    \t\t\t\tAND attachment.contenttypeid = " . $sDb->quote($options['albumType']) . "\n    \t\t\t\tORDER BY attachment.attachmentid ASC\n    \t\t\t", $options['limit']));
     if (!$attachments) {
         return true;
     }
     $next = 0;
     $last = 0;
     $total = 0;
     $position = 0;
     $userIdMap = $model->getUserIdsMapFromArray($attachments, 'userid');
     $albumIdMap = $model->getAlbumIdsMapFromArray($attachments, 'contentid');
     foreach ($attachments as $attachment) {
         $next = $attachment['attachmentid'];
         $attachment['extension'] = XenForo_Helper_File::getFileExtension($attachment['filename']);
         if (!isset($userIdMap[$attachment['userid']])) {
             continue;
         }
         if (!isset($albumIdMap[$attachment['contentid']])) {
             continue;
         }
         if (!isset(sonnb_XenGallery_Model_ContentData::$typeMap[$attachment['extension']])) {
             continue;
         }
         if ($last != $next) {
             $last = $next;
             $userId = $userIdMap[$attachment['userid']];
             $username = $this->_convertToUtf8($attachment['username'], true);
             $username = $this->_mbTrim($username, 50, $userId);
             $albumId = $albumIdMap[$attachment['contentid']];
             $importPhotoData = array('file_size' => $attachment['filesize'], 'width' => $attachment['width'], 'height' => $attachment['height'], 'file_hash' => $attachment['filehash'], 'upload_date' => $attachment['dateline'], 'unassociated' => 1, 'extension' => $attachment['extension']);
             $photoData = $model->importXenGalleryPhotoData(0, $importPhotoData);
             if ($photoData === false) {
                 continue;
             }
             $model->logImportData('sonnb_xengallery_data', $attachment['attachmentid'], $photoData['content_data_id']);
             $success = $this->_createPhotoData($options, $attachment, $photoData);
             if ($success === false) {
                 continue;
             }
             $model->importXenGalleryContentDataConfirm($photoData);
             $import = array('album_id' => $albumId, 'title' => $this->_convertToUtf8($attachment['caption'], true), 'content_data_id' => $photoData['content_data_id'], 'description' => '', 'user_id' => $userId, 'username' => $username, 'content_privacy' => array('allow_view' => 'everyone', 'allow_view_data' => array(), 'allow_comment' => 'everyone', 'allow_comment_data' => array()), 'position' => $position, 'content_state' => $attachment['state'] == 'visible' ? 'visible' : 'moderated', 'content_date' => $attachment['dateline'], 'content_updated_date' => $attachment['dateline']);
             if ($this->_config['retainKeys']) {
                 $import['content_id'] = $attachment['attachmentid'];
             }
             $photoId = $model->importXenGalleryPhoto(0, $import);
             $model->logImportData('sonnb_xengallery_photo', $attachment['attachmentid'], $photoId);
             $position++;
         }
         $total++;
     }
     $options['processed'] += $total;
     $this->_session->incrementStepImportTotal($total);
     return array($next, $options, $this->_getProgressOutput($options['processed'], $options['rows']));
 }
 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;
     }
     // don't execute if the model is not extended as expected.
     if (!method_exists($attachmentModel, 'extractDimensionsForSVG')) {
         return false;
     }
     foreach ($dataIds as $dataId) {
         $data['position'] = $dataId;
         $dw = XenForo_DataWriter::create('XenForo_DataWriter_AttachmentData', XenForo_DataWriter::ERROR_SILENT);
         if ($dw->setExistingData($dataId) && XenForo_Helper_File::getFileExtension($dw->get('filename')) == 'svg') {
             $attach = $dw->getMergedData();
             $attachFile = $attachmentModel->getAttachmentDataFilePath($attach);
             $attachThumbFile = $attachmentModel->getAttachmentThumbnailFilePath($attach);
             list($svgfile, $dimensions) = $attachmentModel->extractDimensionsForSVG($attachFile, false);
             if ($svgfile && $dimensions) {
                 if ($dw->get('width') == 0 && empty($dimensions['width'])) {
                     continue;
                 }
                 if ($dimensions['thumbnail_width'] && $dimensions['thumbnail_height']) {
                     // update the width/height attributes
                     $svgfile['width'] = (string) $dimensions['thumbnail_width'];
                     $svgfile['height'] = (string) $dimensions['thumbnail_height'];
                     $thumbData = $svgfile->asXML();
                 } else {
                     // no resize necessary, use the original
                     $thumbData = file_get_contents($attachFile);
                 }
                 $dw->set('width', $dimensions['width']);
                 $dw->set('height', $dimensions['height']);
                 $dw->set('thumbnail_width', $dimensions['thumbnail_width']);
                 $dw->set('thumbnail_height', $dimensions['thumbnail_height']);
                 $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($svgfile);
             } else {
                 if ($dw->get('width') > 0 || $dw->get('height') > 0) {
                     @unlink($attachThumbFile);
                     $dw->set('width', 0);
                     $dw->set('height', 0);
                     $dw->set('thumbnail_width', 0);
                     $dw->set('thumbnail_height', 0);
                     try {
                         $dw->save();
                     } catch (Exception $e) {
                         XenForo_Error::logException($e, false, "Thumb rebuild for #{$dataId}: ");
                     }
                 }
             }
         }
         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;
 }
Exemple #25
0
    public function stepPhotos($start, array $options)
    {
        $options = array_merge(array('path' => isset($this->_config['data_path']) ? trim($this->_config['data_path']) : '', 'limit' => 10, 'processed' => 0, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $data = $sDb->fetchRow('
    				SELECT MAX(id) AS max, COUNT(id) AS rows
    				FROM ' . $prefix . 'photos
			');
            $options = array_merge($options, $data);
            return array(0, $options, "Processing Photos ...");
        }
        $images = $sDb->fetchAll($sDb->limit("\n    \t\t\t\tSELECT *\n    \t\t\t\tFROM " . $prefix . "photos AS image\n    \t\t\t\tWHERE image.id > " . $sDb->quote($start) . "\n    \t\t\t\tORDER BY image.id ASC\n    \t\t\t", $options['limit']));
        if (!$images) {
            return true;
        }
        $next = 0;
        $last = 0;
        $total = 0;
        $position = 0;
        $userIdMap = $model->getUserIdsMapFromArray($images, 'userid');
        $albumIdMap = $model->getAlbumIdsMapFromArray($images, 'cat');
        $formatter = XenForo_BbCode_Formatter_Base::create('XenForo_BbCode_Formatter_Text');
        $parser = new XenForo_BbCode_Parser($formatter);
        foreach ($images as $image) {
            $next = $image['id'];
            if (!isset($userIdMap[$image['userid']])) {
                continue;
            }
            if (!isset($albumIdMap[$image['cat']])) {
                continue;
            }
            if ($last != $next) {
                $last = $next;
                $userId = $userIdMap[$image['userid']];
                $username = $this->_convertToUtf8($image['user'], true);
                $username = $this->_mbTrim($username, 50, $userId);
                $albumId = $albumIdMap[$image['cat']];
                $file = $options['path'] . DIRECTORY_SEPARATOR . $image['cat'] . DIRECTORY_SEPARATOR . $image['bigimage'];
                if (!file_exists($file)) {
                    continue;
                }
                if (!isset(sonnb_XenGallery_Model_ContentData::$typeMap[XenForo_Helper_File::getFileExtension($image['bigimage'])])) {
                    continue;
                }
                $importPhotoData = array('file_size' => $image['filesize'], 'width' => $image['width'], 'height' => $image['height'], 'file_hash' => @md5_file($file), 'upload_date' => $image['date'], 'unassociated' => 1, 'extension' => XenForo_Helper_File::getFileExtension($image['bigimage']));
                $photoData = $model->importXenGalleryPhotoData($image['id'], $importPhotoData);
                if ($photoData === false) {
                    continue;
                }
                $model->logImportData('sonnb_xengallery_data', $image['id'], $photoData['content_data_id']);
                $success = $this->_createPhotoData($options, $image, $photoData);
                if ($success === false) {
                    continue;
                }
                $model->importXenGalleryContentDataConfirm($photoData);
                $import = array('album_id' => $albumId, 'content_data_id' => $photoData['content_data_id'], 'title' => $parser->render($this->_convertToUtf8($image['title'], true)), 'description' => $parser->render($this->_convertToUtf8($image['description'], true)), 'user_id' => $userId, 'username' => $username, 'content_privacy' => array('allow_view' => 'everyone', 'allow_view_data' => array(), 'allow_comment' => $image['allowcoms'] ? 'everyone' : 'none', 'allow_comment_data' => array()), 'view_count' => $image['views'], 'comment_count' => $image['numcom'], 'position' => $position, 'content_state' => $image['approved'] ? 'visible' : 'moderated', 'content_date' => $image['date'], 'content_updated_date' => $image['date']);
                if ($this->_config['retainKeys']) {
                    $import['content_id'] = $image['id'];
                }
                $photoId = $model->importXenGalleryPhoto($image['id'], $import);
                $model->logImportData('sonnb_xengallery_photo', $image['id'], $photoId);
                $position++;
            }
            $total++;
        }
        $options['processed'] += $total;
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($options['processed'], $options['rows']));
    }
Exemple #26
0
 public function stepPhotos($start, array $options)
 {
     $options = array_merge(array('path' => isset($this->_config['attachmentPath']) ? trim($this->_config['attachmentPath']) : '', 'limit' => 10, 'processed' => 0, 'max' => false), $options);
     $sDb = $this->_sourceDb;
     $prefix = $this->_prefix;
     $prefixPhotoPlog = $this->_photoPlogPrefix;
     $model = $this->_importModel;
     if ($options['max'] === false) {
         $data = $sDb->fetchRow("\n    \t\t\t\tSELECT MAX(fileid) AS max, COUNT(fileid) AS rows\n    \t\t\t\tFROM " . $prefixPhotoPlog . "photoplog_fileuploads\n    \t\t");
         $options = array_merge($options, $data);
         return array(0, $options, "Processing Photos ...");
     }
     $attachments = $sDb->fetchAll($sDb->limit("\n    \t\t\t\tSELECT *\n    \t\t\t\tFROM " . $prefixPhotoPlog . "photoplog_fileuploads\n    \t\t\t\tWHERE fileid > " . $sDb->quote($start) . "\n    \t\t\t\tORDER BY fileid ASC\n    \t\t\t", $options['limit']));
     if (!$attachments) {
         return true;
     }
     $next = 0;
     $last = 0;
     $total = 0;
     $position = 0;
     $userIdMap = $model->getUserIdsMapFromArray($attachments, 'userid');
     $albumIdMap = $model->getAlbumIdsMapFromArray($attachments, 'catid');
     $formatter = XenForo_BbCode_Formatter_Base::create('XenForo_BbCode_Formatter_Text');
     $parser = new XenForo_BbCode_Parser($formatter);
     foreach ($attachments as $attachment) {
         $next = $attachment['fileid'];
         if (!isset($userIdMap[$attachment['userid']]) || !isset($albumIdMap[$attachment['catid']])) {
             continue;
         }
         $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
         if (!isset(sonnb_XenGallery_Model_ContentData::$typeMap[$extension])) {
             continue;
         }
         if ($last != $next) {
             $last = $next;
             $userId = $userIdMap[$attachment['userid']];
             $username = $this->_convertToUtf8($attachment['username'], true);
             $username = $this->_mbTrim($username, 50, $userId);
             $albumId = $albumIdMap[$attachment['catid']];
             $filePath = $this->_getPhotoPlogFilePath($options, $attachment);
             $fileInfo = @getimagesize($filePath);
             if (!$fileInfo) {
                 continue;
             }
             $importPhotoData = array('file_size' => $attachment['filesize'] ? $attachment['filesize'] : filesize($filePath), 'width' => $fileInfo[0], 'height' => $fileInfo[1], 'file_hash' => md5_file($filePath), 'upload_date' => $attachment['dateline'], 'unassociated' => 1, 'extension' => $extension);
             $photoData = $model->importXenGalleryPhotoData(0, $importPhotoData);
             if ($photoData === false) {
                 continue;
             }
             $model->logImportData('sonnb_xengallery_data', $attachment['fileid'], $photoData['content_data_id']);
             $success = $this->_createPhotoData($options, $attachment, $photoData);
             if ($success === false) {
                 continue;
             }
             $model->importXenGalleryContentDataConfirm($photoData);
             $import = array('album_id' => $albumId, 'content_data_id' => $photoData['content_data_id'], 'title' => $parser->render($this->_convertToUtf8($attachment['title'], true)), 'description' => $parser->render($this->_convertToUtf8($attachment['description'], true)), 'user_id' => $userId, 'username' => $username, 'content_privacy' => array('allow_view' => 'everyone', 'allow_view_data' => array(), 'allow_comment' => 'everyone', 'allow_comment_data' => array()), 'view_count' => $attachment['views'], 'position' => $position, 'content_state' => $attachment['moderate'] ? 'moderated' : 'visible', 'content_date' => $attachment['dateline'], 'content_updated_date' => $attachment['dateline']);
             if ($this->_config['retainKeys']) {
                 $import['content_id'] = $attachment['fileid'];
             }
             $photoId = $model->importXenGalleryPhoto(0, $import);
             $model->logImportData('sonnb_xengallery_photo', $attachment['fileid'], $photoId);
             $position++;
         }
         $total++;
     }
     $options['processed'] += $total;
     $this->_session->incrementStepImportTotal($total);
     return array($next, $options, $this->_getProgressOutput($options['processed'], $options['rows']));
 }
Exemple #27
0
 protected static function _fileExport($entry, &$exportPath, &$rootPath, $options)
 {
     if (empty($entry)) {
         return;
     }
     $relativePath = trim(str_replace($rootPath, '', $entry), '/');
     if (in_array($relativePath, $options['excludes'])) {
         echo "<span style='color: #ddd'>Excluded       {$relativePath}</span>\n";
         return;
     }
     foreach ($options['excludeRegExs'] as $excludeRegEx) {
         if (preg_match($excludeRegEx, $relativePath)) {
             echo "<span style='color: #ddd'>RegExcluded    {$relativePath}</span>\n";
             return;
         }
     }
     if (is_dir($entry)) {
         echo "<span style='color: #ddd'>Browsing       {$relativePath}</span>\n";
         $children = array();
         $dh = opendir($entry);
         while ($child = readdir($dh)) {
             if (substr($child, 0, 1) === '.') {
                 // ignore . (current directory)
                 // ignore .. (parent directory)
                 // ignore hidden files (dot files/directories)
                 continue;
             }
             $children[] = $child;
         }
         foreach ($children as $child) {
             if (!empty($options['force'])) {
                 $options['force'] = false;
             }
             // reset `force` option for children
             self::_fileExport($entry . '/' . $child, $exportPath, $rootPath, $options);
         }
     } elseif (is_file($entry)) {
         $ext = XenForo_Helper_File::getFileExtension($entry);
         if (!empty($options['force']) || in_array($ext, $options['extensions']) && strpos(basename($entry), '.') !== 0 || in_array(strtolower(basename($entry)), $options['filenames_lowercase'])) {
             if ($options['addon_id'] == 'devHelper') {
                 $isDevHelper = strpos($entry, 'DevHelper/DevHelper') !== false;
             } else {
                 $isDevHelper = strpos($entry, 'DevHelper') !== false;
             }
             if (!$isDevHelper) {
                 $entryExportPath = $exportPath . '/' . $relativePath;
                 if ($ext === 'php') {
                     DevHelper_Helper_ShippableHelper::checkForUpdate($entry);
                 }
                 $contents = self::fileGetContents($entry);
                 if (!empty($contents)) {
                     if ($ext === 'php') {
                         DevHelper_Helper_Phrase::parsePhpForPhraseTracking($relativePath, $contents);
                         DevHelper_Helper_Xfcp::parsePhpForXfcpClass($relativePath, $contents);
                     }
                     $result = self::writeFile($entryExportPath, $contents, false, false);
                     if ($result === true) {
                         echo "Exporting      {$relativePath} OK\n";
                     } elseif ($result === 'skip') {
                         echo "<span style='color: #ddd'>Exporting      {$relativePath} SKIPPED</span>\n";
                     }
                 }
             }
         }
     }
 }
Exemple #28
0
    public function stepPhotos($start, array $options)
    {
        $options = array_merge(array('path' => isset($this->_config['ipboard_path']) ? trim($this->_config['ipboard_path']) : '', 'limit' => 10, 'processed' => 0, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $data = $sDb->fetchRow('
    				SELECT MAX(image_id) AS max, COUNT(image_id) AS rows
    				FROM ' . $prefix . 'gallery_images
			');
            $options = array_merge($options, $data);
            return array(0, $options, "Processing Photos ...");
        }
        $images = $sDb->fetchAll($sDb->limit("\n    \t\t\t\tSELECT image.*, user.name\n    \t\t\t\tFROM " . $prefix . "gallery_images AS image\n    \t\t\t\tLEFT JOIN " . $prefix . "members AS user ON (image.image_member_id = user.member_id)\n    \t\t\t\tWHERE image.image_id > " . $sDb->quote($start) . "\n    \t\t\t\tORDER BY image.image_id ASC\n    \t\t\t", $options['limit']));
        if (!$images) {
            return true;
        }
        $next = 0;
        $last = 0;
        $total = 0;
        $position = 0;
        $userIdMap = $model->getUserIdsMapFromArray($images, 'image_member_id');
        $albumIdMap = $model->getAlbumIdsMapFromArray($images, 'image_album_id');
        $formatter = XenForo_BbCode_Formatter_Base::create('XenForo_BbCode_Formatter_Text');
        $parser = new XenForo_BbCode_Parser($formatter);
        foreach ($images as $image) {
            $next = $image['image_id'];
            if (!isset($userIdMap[$image['image_member_id']])) {
                continue;
            }
            if (!isset($albumIdMap[$image['image_album_id']])) {
                continue;
            }
            if ($last != $next) {
                $last = $next;
                $userId = $userIdMap[$image['image_member_id']];
                $username = $this->_convertToUtf8($image['name'], true);
                $username = $this->_mbTrim($username, 50, $userId);
                $albumId = $albumIdMap[$image['image_album_id']];
                $dir = $image['image_directory'] ? $image['image_directory'] . "/" : '';
                $large = $this->_config['ipboard_path'] . '/uploads/' . '/' . $dir . $image['image_masked_file_name'];
                $orig = $this->_config['ipboard_path'] . '/uploads/' . '/' . $dir . $image['image_original_file_name'];
                if ($image['image_original_file_name'] && file_exists($orig)) {
                    $file = $orig;
                } else {
                    $file = $large;
                }
                if (!$file) {
                    continue;
                }
                if (!isset(sonnb_XenGallery_Model_ContentData::$typeMap[XenForo_Helper_File::getFileExtension($file)])) {
                    continue;
                }
                $width = $height = 0;
                $imageData = @unserialize($image['image_data']);
                if ($imageData) {
                    if ($image['image_original_file_name']) {
                        $key = 'original';
                    } else {
                        $key = 'max';
                    }
                    $width = $imageData['sizes'][$key][0];
                    $height = $imageData['sizes'][$key][1];
                }
                $importPhotoData = array('file_size' => $image['image_file_size'], 'width' => $width, 'height' => $height, 'file_hash' => md5_file($file), 'upload_date' => $image['image_date'], 'unassociated' => 1, 'extension' => XenForo_Helper_File::getFileExtension($file));
                $photoData = $model->importXenGalleryPhotoData($image['image_id'], $importPhotoData);
                if ($photoData === false) {
                    continue;
                }
                $model->logImportData('sonnb_xengallery_data', $image['image_id'], $photoData['content_data_id']);
                $success = $this->_createPhotoData($options, $image, $photoData);
                if ($success === false) {
                    continue;
                }
                $model->importXenGalleryContentDataConfirm($photoData);
                $import = array('album_id' => $albumId, 'content_data_id' => $photoData['content_data_id'], 'title' => $parser->render($this->_convertToUtf8($image['image_caption'], true)), 'description' => $parser->render($this->_convertToUtf8($image['image_description'], true)), 'user_id' => $userId, 'username' => $username, 'content_privacy' => array('allow_view' => 'everyone', 'allow_view_data' => array(), 'allow_comment' => 'everyone', 'allow_comment_data' => array()), 'view_count' => $image['image_views'], 'comment_count' => $image['image_comments'], 'position' => $position, 'content_state' => $image['image_approved'] ? 'visible' : 'moderated', 'content_date' => $image['image_date'], 'content_updated_date' => $image['image_date']);
                if ($this->_config['retainKeys']) {
                    $import['content_id'] = $image['image_id'];
                }
                $photoId = $model->importXenGalleryPhoto($image['image_id'], $import);
                $model->logImportData('sonnb_xengallery_photo', $image['image_id'], $photoId);
                $position++;
            }
            $total++;
        }
        $options['processed'] += $total;
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($options['processed'], $options['rows']));
    }
    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;
    }
Exemple #30
0
 protected static function _getThumbnailRelativePath($fullPath, $width, $height, $dir)
 {
     $fileName = preg_replace('#[^a-zA-Z0-9]#', '', basename($fullPath)) . md5(serialize(array('fullPath' => $fullPath, 'width' => $width, 'height' => $height)));
     if (XenForo_Helper_File::getFileExtension($fullPath) === 'png') {
         $ext = 'png';
     } else {
         $ext = 'jpg';
     }
     $divider = substr(md5($fileName), 0, 2);
     if (empty($dir)) {
         $dir = trim(str_replace('_', '/', substr(__CLASS__, 0, strpos(__CLASS__, '_ShippableHelper_Image'))), '/');
     }
     return sprintf('/%s/%sx%s/%s/%s.%s', $dir, $width, $height, $divider, $fileName, $ext);
 }