예제 #1
0
 /**
  * Is used to copy an entire directory recursively.
  *
  * @param $source
  * @param $target
  * @param bool $createIndexHtml
  * @throws GFNCore_Exception
  */
 public static function copy($source, $target, $createIndexHtml = false)
 {
     if (!is_dir($source)) {
         throw new GFNCore_Exception('Source directory does not exist.');
     }
     if (!is_dir($target)) {
         XenForo_Helper_File::createDirectory($target, $createIndexHtml);
     }
     $handle = opendir($source);
     if (!$handle) {
         return;
     }
     while (($file = readdir($handle)) !== false) {
         if (in_array($file, array('.', '..'))) {
             continue;
         }
         $from = $source . '/' . $file;
         $to = $target . '/' . $file;
         if (is_dir($from)) {
             self::copy($from, $to);
         } else {
             copy($from, $to);
         }
     }
     closedir($handle);
 }
예제 #2
0
 /**
  * Saves a thumbnail locally
  *
  * @param $thumbnailUrl
  */
 public function saveThumbnail()
 {
     $this->_videoId = XenGallery_Helper_String::cleanVideoId($this->_videoId);
     $this->_mediaSiteId = preg_replace('#[^a-zA-Z0-9_]#', '', $this->_mediaSiteId);
     if (!$this->_mediaSiteId || !$this->_videoId || !$this->_thumbnailUrl) {
         return false;
     }
     $options = XenForo_Application::getOptions();
     $this->_thumbnailPath = XenForo_Application::$externalDataPath . '/xengallery/' . $this->_mediaSiteId;
     try {
         $thumbnailPath = $this->_thumbnailPath . '/' . $this->_mediaSiteId . '_' . $this->_videoId . '.jpg';
         $client = XenForo_Helper_Http::getClient($this->_thumbnailUrl);
         XenForo_Helper_File::createDirectory(dirname($thumbnailPath), true);
         $fp = @fopen($thumbnailPath, 'w');
         if (!$fp) {
             return false;
         }
         fwrite($fp, $client->request('GET')->getBody());
         fclose($fp);
     } catch (Zend_Http_Client_Exception $e) {
         return false;
     }
     $image = new XenGallery_Helper_Image($thumbnailPath);
     $image->resize($options->xengalleryThumbnailDimension['width'], $options->xengalleryThumbnailDimension['height'], 'crop');
     return $image->save($this->_mediaSiteId . '_' . $this->_videoId . '_thumb', $this->_thumbnailPath, 'jpg');
 }
예제 #3
0
파일: Abstract.php 프로젝트: Sywooch/forums
 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;
 }
예제 #4
0
 public function getSitemapFileName($setId, $counter, $compressed = false)
 {
     $path = XenForo_Helper_File::getInternalDataPath() . '/sitemaps';
     if (!XenForo_Helper_File::createDirectory($path, true)) {
         throw new XenForo_Exception("Sitemap directory {$path} could not be created");
     }
     return "{$path}/sitemap-{$setId}-{$counter}.xml" . ($compressed ? '.gz' : '');
 }
예제 #5
0
파일: Install.php 프로젝트: Sywooch/forums
 protected function _install_1()
 {
     $targetLoc = XenForo_Helper_File::getExternalDataPath() . "/sitemaps";
     if (!is_dir($targetLoc)) {
         XenForo_Helper_File::createDirectory($targetLoc);
         XenForo_Helper_File::makeWritableByFtpUser($targetLoc);
     }
 }
예제 #6
0
 /**
  * @param mixed $overrideMotd set motd pre-cache-update
  * @param mixed $unsync if not due to new message set true
  */
 public function regeneratePublicHtml($overrideMotd = false, $unsync = false)
 {
     $viewParams = array();
     $options = XenForo_Application::get('options');
     $visitor = XenForo_Visitor::getInstance();
     if ($options->dark_taigachat_speedmode == 'Disabled') {
         return;
     }
     if ($unsync) {
         /** @var XenForo_Model_DataRegistry */
         $registryModel = $this->getModelFromCache('XenForo_Model_DataRegistry');
         $lastUnsync = $registryModel->get('dark_taigachat_unsync');
         if (!empty($lastUnsync) && $lastUnsync > time() - 30) {
             return;
         }
         $registryModel->set('dark_taigachat_unsync', time());
     }
     // swap timezone to default temporarily
     $oldTimeZone = XenForo_Locale::getDefaultTimeZone()->getName();
     XenForo_Locale::setDefaultTimeZone($options->guestTimeZone);
     $messages = $this->getMessages(array("page" => 1, "perPage" => $options->dark_taigachat_fullperpage, "lastRefresh" => 0));
     $messagesMini = $this->getMessages(array("page" => 1, "perPage" => $options->dark_taigachat_sidebarperpage, "lastRefresh" => 0));
     $bbCodeParser = new XenForo_BbCode_Parser(XenForo_BbCode_Formatter_Base::create('Base'));
     $motd = new XenForo_BbCode_TextWrapper($overrideMotd !== false ? $overrideMotd : $options->dark_taigachat_motd, $bbCodeParser);
     $onlineUsersTaiga = $this->getActivityUserList($visitor->toArray());
     $viewParams = array('taigachat' => array("messages" => $messages, "sidebar" => false, "editside" => $options->dark_taigachat_editside, "timedisplay" => $options->dark_taigachat_timedisplay, "miniavatar" => $options->dark_taigachat_miniavatar, "lastrefresh" => 0, "numInChat" => $this->getActivityUserCount(), "motd" => $motd, "online" => $onlineUsersTaiga, "route" => $options->dark_taigachat_route, "publichtml" => true, 'canView' => true, 'enabled' => true));
     $dep = new Dark_TaigaChat_Dependencies();
     $dep->preLoadData();
     $viewRenderer = new Dark_TaigaChat_ViewRenderer_JsonInternal($dep, new Zend_Controller_Response_Http(), new Zend_Controller_Request_Http());
     if (!file_exists(XenForo_Helper_File::getExternalDataPath() . '/taigachat')) {
         XenForo_Helper_File::createDirectory(XenForo_Helper_File::getExternalDataPath() . '/taigachat', true);
     }
     $innerContent = $viewRenderer->renderView('Dark_TaigaChat_ViewPublic_TaigaChat_List', $viewParams, 'dark_taigachat_list');
     $filename = XenForo_Helper_File::getExternalDataPath() . '/taigachat/messages.html';
     $yayForNoLocking = mt_rand(0, 10000000);
     if (file_put_contents($filename . ".{$yayForNoLocking}.tmp", $innerContent, LOCK_EX) === false) {
         throw new XenForo_Exception("Failed writing TaigaChat messages to {$filename}.tmp.{$yayForNoLocking}.tmp");
     }
     if (!@rename($filename . ".{$yayForNoLocking}.tmp", $filename)) {
         @unlink($filename . ".{$yayForNoLocking}.tmp");
     }
     XenForo_Helper_File::makeWritableByFtpUser($filename);
     $viewParams['taigachat']['messages'] = $messagesMini;
     $viewParams['taigachat']['sidebar'] = true;
     //$viewParams['taigachat']['online'] = null;
     $innerContent = $viewRenderer->renderView('Dark_TaigaChat_ViewPublic_TaigaChat_List', $viewParams, 'dark_taigachat_list');
     $filename = XenForo_Helper_File::getExternalDataPath() . '/taigachat/messagesmini.html';
     if (file_put_contents($filename . ".{$yayForNoLocking}.tmp", $innerContent, LOCK_EX) === false) {
         throw new XenForo_Exception("Failed writing TaigaChat messages to {$filename}.{$yayForNoLocking}.tmp");
     }
     // The only reason this could fail is if the file is being hammered, hence no worries ignoring failure
     if (!@rename($filename . ".{$yayForNoLocking}.tmp", $filename)) {
         @unlink($filename . ".{$yayForNoLocking}.tmp");
     }
     XenForo_Helper_File::makeWritableByFtpUser($filename);
     // put timezone back to how it was
     XenForo_Locale::setDefaultTimeZone($oldTimeZone);
 }
예제 #7
0
 public function DevHelper_saveTemplate()
 {
     if (DevHelper_Helper_Template::autoExportImport() == false) {
         return false;
     }
     $template = $this->getMergedData();
     $filePath = DevHelper_Helper_Template::getTemplateFilePath($template);
     XenForo_Helper_File::createDirectory(dirname($filePath));
     return file_put_contents($filePath, $template['template']) > 0;
 }
예제 #8
0
 protected function _createTemplateDirectory()
 {
     if (!is_dir($this->_path)) {
         if (XenForo_Helper_File::createDirectory($this->_path)) {
             return XenForo_Helper_File::makeWritableByFtpUser($this->_path);
         } else {
             return false;
         }
     }
     return true;
 }
예제 #9
0
 public function execute(array $deferred, array $data, $targetRunTime, &$status)
 {
     $data = array_merge(array('position' => 0, 'batch' => 10), $data);
     $data['batch'] = max(1, $data['batch']);
     /* @var $mediaModel XenGallery_Model_Media */
     $mediaModel = XenForo_Model::create('XenGallery_Model_Media');
     /* @var $attachmentModel XenForo_Model_Attachment */
     $attachmentModel = XenForo_Model::create('XenForo_Model_Attachment');
     $watermarkModel = $this->_getWatermarkModel();
     if (!$this->_db) {
         $this->_db = XenForo_Application::getDb();
     }
     $mediaIds = $mediaModel->getMediaIdsInRange($data['position'], $data['batch']);
     if (sizeof($mediaIds) == 0) {
         return true;
     }
     $options = XenForo_Application::getOptions();
     $fetchOptions = array('join' => XenGallery_Model_Media::FETCH_ATTACHMENT);
     $media = $mediaModel->getMediaByIds($mediaIds, $fetchOptions);
     $media = $mediaModel->prepareMediaItems($media);
     foreach ($media as $item) {
         $data['position'] = $item['media_id'];
         if (empty($item['watermark_id'])) {
             continue;
         }
         try {
             $attachment = $attachmentModel->getAttachmentById($item['attachment_id']);
             $originalPath = $mediaModel->getOriginalDataFilePath($attachment, true);
             $filePath = $attachmentModel->getAttachmentDataFilePath($attachment);
             $watermarkPath = $watermarkModel->getWatermarkFilePath($item['watermark_id']);
             if (XenForo_Helper_File::createDirectory(dirname($originalPath), true)) {
                 $image = new XenGallery_Helper_Image($originalPath);
                 $watermark = new XenGallery_Helper_Image($watermarkPath);
                 $watermark->resize($image->getWidth() / 100 * $options->xengalleryWatermarkDimensions['width'], $image->getHeight() / 100 * $options->xengalleryWatermarkDimensions['height'], 'fit');
                 $image->addWatermark($watermark->tmpFile);
                 $image->writeWatermark($options->xengalleryWatermarkOpacity, $options->xengalleryWatermarkMargin['h'], $options->xengalleryWatermarkMargin['v'], $options->xengalleryWatermarkHPos, $options->xengalleryWatermarkVPos);
                 $image->saveToPath($filePath);
                 unset($watermark);
                 unset($image);
                 clearstatcache();
                 $this->_db->update('xf_attachment_data', array('file_size' => filesize($filePath)), 'data_id = ' . $attachment['data_id']);
                 $mediaWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Media');
                 $mediaWriter->setExistingData($item['media_id']);
                 $mediaWriter->set('last_edit_date', XenForo_Application::$time);
                 $mediaWriter->save();
             }
         } catch (Exception $e) {
         }
     }
     $actionPhrase = new XenForo_Phrase('rebuilding');
     $typePhrase = new XenForo_Phrase('xengallery_rebuild_watermarks');
     $status = sprintf('%s... %s (%s)', $actionPhrase, $typePhrase, XenForo_Locale::numberFormat($data['position']));
     return $data;
 }
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     $filePath = self::getTempFile($path);
     self::$_metadata[$path] = array('length' => 0, 'image' => null, 'start' => microtime(true));
     $fileDir = dirname($filePath);
     if (!XenForo_Helper_File::createDirectory($fileDir, true)) {
         return false;
     }
     $this->_path = $path;
     $this->_resource = fopen($filePath, $mode, false);
     return (bool) $this->_resource;
 }
예제 #11
0
 protected function _writeIcon($nodeId, $number, $tempFile)
 {
     $filePath = $this->getIconFilePath($nodeId, $number);
     $directory = dirname($filePath);
     if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory)) {
         if (file_exists($filePath)) {
             @unlink($filePath);
         }
         return XenForo_Helper_File::safeRename($tempFile, $filePath);
     } else {
         return false;
     }
 }
예제 #12
0
 public function actionXenGallerySave()
 {
     $this->_assertPostOnly();
     $input = $this->_input->filter(array('group_id' => XenForo_Input::STRING, 'options' => XenForo_Input::ARRAY_SIMPLE, 'options_listed' => array(XenForo_Input::STRING, array('array' => true))));
     $options = XenForo_Application::getOptions();
     $optionModel = $this->_getOptionModel();
     $group = $optionModel->getOptionGroupById($input['group_id']);
     foreach ($input['options_listed'] as $optionName) {
         if ($optionName == 'xengalleryUploadWatermark') {
             continue;
         }
         if (!isset($input['options'][$optionName])) {
             $input['options'][$optionName] = '';
         }
     }
     $delete = $this->_input->filterSingle('delete_watermark', XenForo_Input::BOOLEAN);
     if ($delete) {
         $existingWatermark = $options->get('xengalleryUploadWatermark');
         if ($existingWatermark) {
             $watermarkWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Watermark', XenForo_DataWriter::ERROR_SILENT);
             $watermarkWriter->setExistingData($existingWatermark);
             $watermarkWriter->delete();
             $input['options']['xengalleryUploadWatermark'] = 0;
             $optionModel->updateOptions($input['options']);
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(XenForo_Link::buildAdminLink('options/list', $group)));
         }
     }
     $fileTransfer = new Zend_File_Transfer_Adapter_Http();
     if ($fileTransfer->isUploaded('watermark')) {
         $fileInfo = $fileTransfer->getFileInfo('watermark');
         $fileName = $fileInfo['watermark']['tmp_name'];
         $watermarkWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Watermark', XenForo_DataWriter::ERROR_SILENT);
         $existingWatermark = $options->get('xengalleryUploadWatermark');
         if ($existingWatermark) {
             $watermarkWriter->setExistingData($existingWatermark);
         }
         $watermarkData = array('watermark_user_id' => XenForo_Visitor::getUserId(), 'is_site' => 1);
         $watermarkWriter->bulkSet($watermarkData);
         $watermarkWriter->save();
         $image = new XenGallery_Helper_Image($fileName);
         $image->resize($options->xengalleryWatermarkDimensions['width'], $options->xengalleryWatermarkDimensions['height'], 'fit');
         $watermarkModel = $this->_getWatermarkModel();
         $watermarkPath = $watermarkModel->getWatermarkFilePath($watermarkWriter->get('watermark_id'));
         if (XenForo_Helper_File::createDirectory(dirname($watermarkPath), true)) {
             XenForo_Helper_File::safeRename($fileName, $watermarkPath);
             $input['options']['xengalleryUploadWatermark'] = $watermarkWriter->get('watermark_id');
         }
     }
     $optionModel->updateOptions($input['options']);
     return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(XenForo_Link::buildAdminLink('options/list', $group)));
 }
예제 #13
0
 public static function createDirectory($path, $createIndexHtml = false)
 {
     $created = XenForo_Helper_File::createDirectory($path, $createIndexHtml);
     // XenForo won't create a directory in the root, manually do it here
     if (!$created) {
         $path = preg_replace('#/+$#', '', $path);
         $path = str_replace('\\', '/', $path);
         $parts = explode('/', $path);
         $checkOnRoot = implode('/', array_slice($parts, 0, count($parts) - 1));
         if (XenForo_Application::getInstance()->getRootDir() == $checkOnRoot) {
             if (!file_exists($path)) {
                 if (mkdir($path)) {
                     $created = true;
                 }
             }
         }
     }
     return $created;
 }
예제 #14
0
파일: AddOn.php 프로젝트: Rivals/XDS
 public function constructPaths($inputsXDS)
 {
     $libraryPath = XenForo_Application::getInstance()->getRootDir() . '/library';
     $addon = $inputsXDS['title'];
     if (!empty($inputsXDS['folders_cp_name']) or !empty($inputsXDS['folders_ca_name']) or !empty($inputsXDS['folders_model_name']) or !empty($inputsXDS['folders_dw_name']) or !empty($inputsXDS['folders_install_name']) or !empty($inputsXDS['xds_prefix_public_folder_name']) or !empty($inputsXDS['xds_prefix_public_file_name']) or !empty($inputsXDS['xds_prefix_admin_folder_name']) or !empty($inputsXDS['xds_prefix_admin_file_name']) or !empty($inputsXDS['xds_prefix_admin_file_name'])) {
         //main folder
         XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}");
         //ControllerAdmin Folder
         if (!empty($inputsXDS['folders_ca_name'])) {
             XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/" . $inputsXDS['folders_ca_name'] . "");
         }
         //ControllerPublic Folder
         if (!empty($inputsXDS['folders_cp_name'])) {
             XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/" . $inputsXDS['folders_cp_name'] . "");
         }
         //Model Folder
         if (!empty($inputsXDS['folders_model_name'])) {
             XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/" . $inputsXDS['folders_model_name'] . "");
         }
         //DataWriter Folder
         if (!empty($inputsXDS['folders_dw_name'])) {
             XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/" . $inputsXDS['folders_dw_name'] . "");
         }
         //Install Folder
         if (!empty($inputsXDS['folders_install_name'])) {
             XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/" . $inputsXDS['folders_install_name'] . "");
         }
         //Prefix Folders
         if (!empty($inputsXDS['xds_prefix_public_folder_name']) or !empty($inputsXDS['xds_prefix_admin_folder_name'])) {
             XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/Route");
             if (!empty($inputsXDS['xds_prefix_public_folder_name'])) {
                 XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/Route/" . $inputsXDS['xds_prefix_public_folder_name'] . "");
             }
             if (!empty($inputsXDS['xds_prefix_admin_folder_name'])) {
                 XenForo_Helper_File::createDirectory("{$libraryPath}/{$addon}/Route/" . $inputsXDS['xds_prefix_admin_folder_name'] . "");
             }
         }
     }
     //Data Folder
     if (!empty($inputsXDS['xds_input_data_name'])) {
         XenForo_Helper_File::createDirectory(XenForo_Application::getInstance()->getRootDir() . '/data/' . $inputsXDS['xds_input_data_name'] . '');
     }
 }
예제 #15
0
 /**
  * Writes out the specified attachment file. The temporary file
  * will be moved to the new position!
  *
  * @param string $tempFile Temporary (source file)
  * @param array $data Information about this attachment data (for dest path)
  * @param boolean $thumbnail True if writing out thumbnail.
  *
  * @return boolean
  */
 protected function _writeAttachmentFile($tempFile, array $data, $thumbnail = false)
 {
     if ($this->getExtraData(self::DATA_XMG_DATA)) {
         if ($tempFile && is_readable($tempFile)) {
             /** @var $mediaModel XenGallery_Model_Media */
             $mediaModel = $this->getModelFromCache('XenGallery_Model_Media');
             if ($thumbnail) {
                 $filePath = $mediaModel->getMediaThumbnailFilePath($data);
             } else {
                 $filePath = $this->_getAttachmentModel()->getAttachmentDataFilePath($data);
             }
             $directory = dirname($filePath);
             if (XenForo_Helper_File::createDirectory($directory, true)) {
                 $success = $this->_copyFile($tempFile, $filePath);
                 if ($success) {
                     return parent::_writeAttachmentFile($tempFile, $data, $thumbnail);
                 }
                 return false;
             }
         }
     }
     return parent::_writeAttachmentFile($tempFile, $data, $thumbnail);
 }
예제 #16
0
 protected function _preSave()
 {
     $class = $this->get('route_class');
     if (!XenForo_Application::autoload($class)) {
         $filename = XenForo_Autoloader::getInstance()->getRootDir() . DIRECTORY_SEPARATOR . str_replace("_", DIRECTORY_SEPARATOR, $class) . ".php";
         if (!file_exists(dirname($filename))) {
             XenForo_Helper_File::createDirectory(dirname($filename));
         }
         $options = array('title_plural' => str_replace('-', ' ', $this->get('original_prefix')));
         $phpFile = null;
         switch ($this->get('route_type')) {
             case 'public':
                 $phpFile = new ThemeHouse_RoutePrefixes_PhpFile_Route_Prefix($class, $options);
                 break;
             case 'admin':
                 $phpFile = new ThemeHouse_RoutePrefixes_PhpFile_Route_PrefixAdmin($class, $options);
                 break;
         }
         if (!is_null($phpFile)) {
             $phpFile->export(true);
         }
     }
     return parent::_preSave();
 }
예제 #17
0
 /**
  * Writes out an avatar.
  *
  * @param integer $userId
  * @param string $size Size code
  * @param string $tempFile Temporary avatar file. Will be moved.
  *
  * @return boolean
  */
 protected function _writeAvatar($userId, $size, $tempFile)
 {
     if (!in_array($size, array_keys(self::$_sizes))) {
         throw new XenForo_Exception('Invalid avatar size.');
     }
     $filePath = $this->getAvatarFilePath($userId, $size);
     $directory = dirname($filePath);
     if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory)) {
         if (file_exists($filePath)) {
             @unlink($filePath);
         }
         return XenForo_Helper_File::safeRename($tempFile, $filePath);
     } else {
         return false;
     }
 }
예제 #18
0
 protected function _createPhotoData($options, &$attachment, $data)
 {
     $photoDataModel = $this->_getPhotoDataModel();
     $smallThumbFile = $photoDataModel->getContentDataSmallThumbnailFile($data);
     $mediumThumbFile = $photoDataModel->getContentDataMediumThumbnailFile($data);
     $largeThumbFile = $photoDataModel->getContentDataLargeThumbnailFile($data);
     $originalFile = $photoDataModel->getContentDataFile($data);
     if ($smallThumbFile) {
         $directory = dirname($smallThumbFile);
         if (XenForo_Helper_File::createDirectory($directory, true)) {
             $oldSmallFile = $photoDataModel->getContentDataSmallThumbnailFile($attachment, $options['path']);
             @copy($oldSmallFile, $smallThumbFile);
             XenForo_Helper_File::makeWritableByFtpUser($smallThumbFile);
         }
     }
     if ($mediumThumbFile) {
         $directory = dirname($mediumThumbFile);
         if (XenForo_Helper_File::createDirectory($directory, true)) {
             $oldMediumFile = $photoDataModel->getContentDataMediumThumbnailFile($attachment, $options['path']);
             @copy($oldMediumFile, $mediumThumbFile);
             XenForo_Helper_File::makeWritableByFtpUser($mediumThumbFile);
         }
     }
     if ($largeThumbFile) {
         $directory = dirname($largeThumbFile);
         if (XenForo_Helper_File::createDirectory($directory, true)) {
             $oldLargeFile = $photoDataModel->getContentDataLargeThumbnailFile($attachment, $options['path']);
             @copy($oldLargeFile, $largeThumbFile);
             XenForo_Helper_File::makeWritableByFtpUser($largeThumbFile);
         }
     }
     if ($originalFile) {
         $directory = dirname($originalFile);
         if (XenForo_Helper_File::createDirectory($directory, true)) {
             $oldOriginalFile = $photoDataModel->getContentDataFile($attachment, $options['path']);
             @copy($oldOriginalFile, $originalFile);
             XenForo_Helper_File::makeWritableByFtpUser($originalFile);
         }
     }
     return true;
 }
예제 #19
0
파일: Import.php 프로젝트: Sywooch/forums
 public function createPhotoThumbnails($filename, $data, $importToStore = false)
 {
     $xenOptions = XenForo_Application::getOptions();
     $photoDataModel = $this->_getPhotoDataModel();
     $extensionType = sonnb_XenGallery_Model_ContentData::$typeMap;
     $smallThumbFile = $photoDataModel->getContentDataSmallThumbnailFile($data);
     $mediumThumbFile = $photoDataModel->getContentDataMediumThumbnailFile($data);
     $largeThumbFile = $photoDataModel->getContentDataLargeThumbnailFile($data);
     $originalFile = $photoDataModel->getContentDataFile($data);
     if ($originalFile && !$xenOptions->sonnbXG_disableOriginal) {
         $directory = dirname($originalFile);
         if (XenForo_Helper_File::createDirectory($directory, true)) {
             @copy($filename, $originalFile);
             XenForo_Helper_File::makeWritableByFtpUser($originalFile);
         }
     }
     $photoDataModel->createContentDataThumbnailFile($filename, $largeThumbFile, $extensionType[$data['extension']], sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_LARGE);
     $photoDataModel->createContentDataThumbnailFile($largeThumbFile, $mediumThumbFile, $extensionType[$data['extension']], sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_MEDIUM);
     $photoDataModel->createContentDataThumbnailFile($largeThumbFile, $smallThumbFile, $extensionType[$data['extension']], sonnb_XenGallery_Model_ContentData::CONTENT_FILE_TYPE_SMALL);
     $db = $this->_getDb();
     if ($importToStore !== false) {
         $useAttachmentStore = $xenOptions->sonnbXG_useBdStore;
         $engine = '';
         if (XenForo_Application::isRegistered('addOns')) {
             $addOns = XenForo_Application::get('addOns');
         }
         if (!class_exists('bdAttachmentStore_Option') || empty($addOns['bdAttachmentStore'])) {
             $useAttachmentStore = false;
         }
         if ($useAttachmentStore) {
             $fileModel = $this->_bdAttachmentStore_getFileModel();
             $defaultEngine = $fileModel->getDefaultEngine();
             if ($defaultEngine === bdAttachmentStore_Option::MODE_ATTACHMENT || $defaultEngine === bdAttachmentStore_Option::MODE_EXTERNAL_DATA) {
                 $defaultEngine = '';
             }
             if (!empty($defaultEngine)) {
                 $engine = $defaultEngine;
             }
         }
         if (!empty($engine)) {
             $fileModel = $this->_bdAttachmentStore_getFileModel();
             $storeOptions = $fileModel->getStorageOptions($engine);
             if (!isset($storeOptions['keepLocalCopy'])) {
                 $storeOptions['keepLocalCopy'] = bdAttachmentStore_Option::get('keepLocalCopy');
             }
             $smallThumbFileStore = $photoDataModel->getStoreContentDataSmallThumbnailFile($data);
             $mediumThumbFileStore = $photoDataModel->getStoreContentDataMediumThumbnailFile($data);
             $largeThumbFileStore = $photoDataModel->getStoreContentDataLargeThumbnailFile($data);
             $originalFileStore = $photoDataModel->getStoreContentDataFile($data);
             if (!$xenOptions->sonnbXG_disableOriginal) {
                 $fileModel->saveFile($engine, $storeOptions, $originalFile, $originalFileStore, basename($originalFileStore));
             }
             $fileModel->saveFile($engine, $storeOptions, $largeThumbFile, $largeThumbFileStore, basename($largeThumbFileStore));
             $fileModel->saveFile($engine, $storeOptions, $mediumThumbFile, $mediumThumbFileStore, basename($mediumThumbFileStore));
             $fileModel->saveFile($engine, $storeOptions, $smallThumbFile, $smallThumbFileStore, basename($smallThumbFileStore));
             $db->update('sonnb_xengallery_content_data', array('bdattachmentstore_engine' => $engine, 'bdattachmentstore_options' => serialize($storeOptions)), array('content_data_id = ?' => $data['content_data_id']));
             if (empty($storeOptions['keepLocalCopy'])) {
                 @unlink($smallThumbFile);
                 @unlink($mediumThumbFile);
                 @unlink($largeThumbFile);
                 @unlink($originalFile);
             }
         }
     }
     $db->update('sonnb_xengallery_content_data', array('unassociated' => 0), array('content_data_id = ?' => $data['content_data_id']));
 }
예제 #20
0
파일: Cover.php 프로젝트: Sywooch/forums
 protected function _witerCoverPhoto($teamId, $tempFile)
 {
     $filePath = $this->getCoverPhotoFilePath($teamId);
     $directory = dirname($filePath);
     if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory)) {
         if (file_exists($filePath)) {
             unlink($filePath);
         }
         return XenForo_Helper_File::safeRename($tempFile, $filePath);
     } else {
         return false;
     }
 }
예제 #21
0
파일: Gallery.php 프로젝트: Sywooch/forums
 public function cropAuthorCover(array $user, $x, $y, $relativeWidth, $relativeHeight)
 {
     if (empty($user['sonnb_xengallery_cover']['upload_date'])) {
         return;
     }
     $newUser = $user;
     $newUser['sonnb_xengallery_cover']['upload_date'] = XenForo_Application::$time;
     $outputFile = $this->_getGalleryModel()->getAuthorCoverFile($newUser);
     $file = $this->_getGalleryModel()->getAuthorCoverFile($user);
     $imageInfo = @getimagesize($file);
     if (!$imageInfo) {
         throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
     }
     $imageType = $imageInfo[2];
     if (!$this->_getPhotoModel()->canResizeImage($imageInfo[0], $imageInfo[1])) {
         throw new XenForo_Exception(new XenForo_Phrase('sonnb_xengallery_your_cover_is_too_big_cannot_crop'), true);
     }
     $image = XenForo_Image_Abstract::createFromFile($file, $imageType);
     if (!$image) {
         return false;
     }
     $image->thumbnail($relativeWidth);
     if ($image->getHeight() > $relativeHeight) {
         $cropWidth = $relativeWidth;
         if ($relativeWidth > $image->getWidth()) {
             $cropWidth = $image->getWidth();
         }
         $cropHeight = $relativeHeight;
         if ($cropHeight > $image->getWidth()) {
             $cropHeight = $image->getHeight();
         }
         $image->crop($x, $y, $cropWidth, $cropHeight);
     }
     if (isset($newUser['sonnb_xengallery_cover']['bdattachmentstore_engine'])) {
         $engine = $newUser['sonnb_xengallery_cover']['bdattachmentstore_engine'];
         $options = $newUser['sonnb_xengallery_cover']['bdattachmentstore_options'];
         $keepLocalCopy = !empty($options['keepLocalCopy']);
     } else {
         $engine = '';
         $options = array();
     }
     $success = $image->output($imageType, $outputFile, 100);
     if ($success) {
         $newData = array('bdattachmentstore_engine' => $engine, 'bdattachmentstore_options' => $options, 'upload_date' => $newUser['sonnb_xengallery_cover']['upload_date'], 'extension' => sonnb_XenGallery_Model_ContentData::$extensionMap[$imageType]);
         if (empty($engine) || !empty($engine) && $keepLocalCopy) {
             $oldLocalCover = $this->_getGalleryModel()->getAuthorCoverFile($user, true);
             @unlink($oldLocalCover);
             $newLocalCover = $this->_getGalleryModel()->getAuthorCoverFile($newUser, true);
             $directory = dirname($newLocalCover);
             if (XenForo_Helper_File::createDirectory($directory, true)) {
                 copy($outputFile, $newLocalCover);
                 if (!empty($engine)) {
                     @unlink($outputFile);
                 }
             }
         }
         if (!empty($engine)) {
             $filePath = $this->getAuthorCoverStoreFile($newUser);
             $this->_bdAttachmentStore_getFileModel()->saveFile($engine, $options, $outputFile, $filePath, basename($filePath));
             if (!$keepLocalCopy) {
                 @unlink($outputFile);
             }
         }
         $db = $this->_getDb();
         $db->update('xf_user', array('sonnb_xengallery_cover' => serialize($newData)), 'user_id = ' . $user['user_id']);
         return $newData;
     }
     unset($image);
     return false;
 }
예제 #22
0
파일: XenForo.php 프로젝트: Sywooch/forums
 protected function _importUser(array $user, array $options = array())
 {
     if ($this->_groupMap === null) {
         $this->_groupMap = $this->_importModel->getImportContentMap('userGroup');
     }
     $import = $this->_quickAssembleData($user, array('username', 'email', 'gender', 'custom_title', 'timezone', 'visible', 'user_group_id' => $this->_mapLookUp($this->_groupMap, $user['user_group_id'], XenForo_Model_User::$defaultRegisteredGroupId), 'secondary_group_ids' => $this->_translateUserGroupIdList($user['secondary_group_ids'], true), 'display_style_group_id' => $this->_mapLookUp($this->_groupMap, $user['display_style_group_id'], XenForo_Model_User::$defaultRegisteredGroupId), 'message_count', 'conversations_unread', 'register_date', 'last_activity', 'avatar_date', 'avatar_width', 'avatar_height', 'gravatar', 'user_state', 'is_moderator', 'is_admin', 'is_staff', 'is_banned', 'like_count', 'warning_points', 'dob_day', 'dob_month', 'dob_year', 'status', 'status_date', 'signature', 'homepage', 'location', 'occupation', 'avatar_crop_x', 'avatar_crop_y', 'about', 'show_dob_year', 'show_dob_date', 'content_show_signature', 'receive_admin_email', 'email_on_conversation', 'is_discouraged', 'default_watch_state', 'alert_optout', 'enable_rte', 'enable_flash_uploader', 'allow_view_profile', 'allow_post_profile', 'allow_send_personal_conversation', 'allow_view_identities', 'allow_receive_news_feed', 'scheme_class', 'data'));
     // custom user fields
     if ($user['custom_fields'] = unserialize($user['custom_fields'])) {
         if ($this->_userFieldMap === null) {
             $this->_userFieldMap = $this->_importModel->getImportContentMap('userField');
         }
         $userFieldDefinitions = $this->_importModel->getUserFieldDefinitions();
         foreach ($user['custom_fields'] as $oldFieldId => $customField) {
             $newFieldId = $this->_mapLookUp($this->_userFieldMap, $oldFieldId);
             if (!$newFieldId) {
                 continue;
             }
             $import[XenForo_Model_Import::USER_FIELD_KEY][$newFieldId] = $user['custom_fields'][$oldFieldId];
         }
     }
     $importedUserId = $this->_importModel->importUser($user['user_id'], $import, $failedKey, false);
     if ($importedUserId) {
         // banned users
         if ($user['is_banned']) {
             if ($ban = $this->_sourceDb->fetchRow('SELECT * FROM xf_user_ban WHERE user_id = ?', $user['user_id'])) {
                 $this->_importModel->importBan($this->_quickAssembleData($ban, array('user_id' => $importedUserId, 'ban_user_id' => $this->_importModel->mapUserId($ban['ban_user_id'], 0), 'ban_date', 'end_date', 'user_reason', 'triggered')));
             }
         }
         // handle admins in a different way from normal imports so that we get a complete data import
         if ($user['is_admin'] && (!$this->_importModel->keysRetained() || $user['user_id'] != 1)) {
             if ($admin = $this->_sourceDb->fetchRow('SELECT * FROM xf_admin WHERE user_id = ?', $user['user_id'])) {
                 $this->_importModel->importAdmin($this->_quickAssembleData($admin, array('user_id' => $importedUserId, 'extra_user_group_ids' => $this->_translateUserGroupIdList($admin['extra_user_group_ids']), 'last_login', 'permission_cache')));
             }
         }
         // avatar
         if ($user['avatar_date']) {
             /* @var $avatarModel XenForo_Model_Avatar */
             $avatarModel = XenForo_Model::create('XenForo_Model_Avatar');
             foreach (array('l', 'm', 's') as $size) {
                 $oldAvatar = $avatarModel->getAvatarFilePath($user['user_id'], $size, $this->_config['dir']['data']);
                 if (!file_exists($oldAvatar) || !is_readable($oldAvatar)) {
                     continue;
                 }
                 $newAvatar = $avatarModel->getAvatarFilePath($importedUserId, $size);
                 $directory = dirname($newAvatar);
                 if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory)) {
                     copy($oldAvatar, $newAvatar);
                 }
             }
         }
     } else {
         if ($failedKey) {
             $this->_session->setExtraData('userFailed', $user['user_id'], $failedKey);
         }
     }
     return $importedUserId;
 }
예제 #23
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;
 }
예제 #24
0
 public function createContentDataThumbnailFile($inputFile, $outputFile, $outputType, $thumbnailType, &$fallback = false, &$dimensions = array(), $isRebuild = false)
 {
     $success = false;
     $directory = dirname($outputFile);
     XenForo_Helper_File::createDirectory($directory, true);
     //TODO: Refactor the fallback.
     $image = XenForo_Image_Abstract::createFromFile($inputFile, $outputType);
     if ($image) {
         switch ($thumbnailType) {
             case self::CONTENT_FILE_TYPE_LARGE:
                 $largeSize = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_LARGE);
                 if ($image->thumbnail($largeSize, $largeSize)) {
                     $success = $image->output($outputType, $outputFile, 100);
                 } else {
                     $success = $this->copyFile($inputFile, $outputFile);
                 }
                 $dimensions[$thumbnailType . '_width'] = $image->getWidth();
                 $dimensions[$thumbnailType . '_height'] = $image->getHeight();
                 //Add watermark if enabled.
                 $this->addWatermark($outputFile, $outputType, null, $isRebuild);
                 break;
             case self::CONTENT_FILE_TYPE_MEDIUM:
                 $realWidth = $image->getWidth();
                 $realHeight = $image->getHeight();
                 $resizeWidth = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_MEDIUM);
                 $resizeHeight = $resizeWidth;
                 if ($realWidth * ($resizeHeight / $realHeight) < $resizeWidth) {
                     $resizeHeight = $realHeight * ($resizeWidth / $realWidth);
                 }
                 if ($image->thumbnail($resizeWidth, $resizeHeight)) {
                     $success = $image->output($outputType, $outputFile, 100);
                 } else {
                     $success = $this->copyFile($inputFile, $outputFile);
                 }
                 $dimensions[$thumbnailType . '_width'] = $image->getWidth();
                 $dimensions[$thumbnailType . '_height'] = $image->getHeight();
                 break;
             case self::CONTENT_FILE_TYPE_SMALL:
                 $smallSize = $this->getThumbnailSize(self::CONTENT_FILE_TYPE_SMALL);
                 if ($image->thumbnail($smallSize * 2, $smallSize * 2)) {
                     $x = floor(($image->getWidth() - $smallSize) / 2);
                     $y = floor(($image->getHeight() - $smallSize) / 2);
                     $image->crop($x > 0 ? $x : 0, $y > 0 ? $y : 0, $smallSize, $smallSize);
                     $success = $image->output($outputType, $outputFile, 100);
                 } else {
                     $success = $this->copyFile($inputFile, $outputFile);
                 }
                 $dimensions[$thumbnailType . '_width'] = $image->getWidth();
                 $dimensions[$thumbnailType . '_height'] = $image->getHeight();
                 break;
             case self::CONTENT_FILE_TYPE_ORIGINAL:
             default:
                 $success = $this->copyFile($inputFile, $outputFile);
                 break;
         }
     } else {
         $fallback = true;
         $success = $this->copyFile($inputFile, $outputFile);
     }
     unset($image);
     return $success;
 }
예제 #25
0
파일: Category.php 프로젝트: Sywooch/forums
 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;
 }
예제 #26
0
 /**
  * Fetches a remote image, stores it in the file system and records it in the database
  *
  * @param string $url
  * @param array|null $image
  *
  * @return array
  */
 protected function _fetchAndCacheImage($url, array $image = null)
 {
     $urlHash = md5($url);
     $time = XenForo_Application::$time;
     if (!$image || empty($image['image_id'])) {
         $image = array('url' => $url, 'url_hash' => $urlHash, 'fetch_date' => $time, 'file_size' => 0, 'file_name' => '', 'mime_type' => '', 'views' => 0, 'first_request_date' => $time, 'last_request_date' => $time, 'pruned' => 1, 'failed_date' => 0, 'fail_count' => 0);
     }
     $image['is_processing'] = time();
     // intentionally time() as we might have slept
     $db = $this->_getDb();
     if (empty($image['image_id'])) {
         try {
             $db->insert('xf_image_proxy', $image);
             $image['image_id'] = $db->lastInsertId();
         } catch (Exception $e) {
             $image['image_id'] = 0;
             $image['is_processing'] = 0;
             $image['failed_date'] = time();
             $image['fail_count'] = 1;
             return $image;
         }
     } else {
         $db->query("\n\t\t\t\tUPDATE xf_image_proxy\n\t\t\t\tSET is_processing = ?\n\t\t\t\tWHERE image_id = ?\n\t\t\t", array($image['is_processing'], $image['image_id']));
     }
     $results = $this->_fetchImageForProxy($url);
     $requestFailed = $results['failed'];
     $streamFile = $results['tempFile'];
     $fileName = $results['fileName'];
     $mimeType = $results['mimeType'];
     $fileSize = $results['fileSize'];
     if (!$requestFailed) {
         $filePath = $this->getImagePath($image);
         $dirName = dirname($filePath);
         @unlink($filePath);
         if (XenForo_Helper_File::createDirectory($dirName, true) && XenForo_Helper_File::safeRename($streamFile, $filePath)) {
             // ensure the filename fits -- if it's too long, take off from the beginning to keep extension
             if (!preg_match('/./u', $fileName)) {
                 $fileName = preg_replace('/[\\x80-\\xFF]/', '?', $fileName);
             }
             $fileName = XenForo_Input::cleanString($fileName);
             $length = utf8_strlen($fileName);
             if ($length > 250) {
                 $fileName = utf8_substr($fileName, $length - 250);
             }
             $data = array('fetch_date' => time(), 'file_size' => $fileSize, 'file_name' => $fileName, 'mime_type' => $mimeType, 'pruned' => 0, 'is_processing' => 0, 'failed_date' => 0, 'fail_count' => 0);
             $image = array_merge($image, $data);
             $db->update('xf_image_proxy', $data, 'image_id = ' . $db->quote($image['image_id']));
         }
     }
     @unlink($streamFile);
     if ($requestFailed) {
         $data = array('is_processing' => 0, 'failed_date' => time(), 'fail_count' => $image['fail_count'] + 1);
         $image = array_merge($image, $data);
         $db->update('xf_image_proxy', $data, 'image_id = ' . $db->quote($image['image_id']));
     }
     return $image;
 }
예제 #27
0
 private static function _verifyAddOnFiles($packageDir, $xfDir, $relativePath = null)
 {
     $files = array();
     $dir = sprintf('%s/%s', $packageDir, $relativePath);
     $entries = scandir($dir);
     $subDirs = array();
     foreach ($entries as $entry) {
         if (substr($entry, 0, 1) === '.') {
             // ignore hidden files
             continue;
         }
         if ($relativePath !== null) {
             $fileRelativePath = sprintf('%s/%s', $relativePath, $entry);
         } else {
             $fileRelativePath = $entry;
         }
         if (is_file(sprintf('%s/%s', $packageDir, $fileRelativePath))) {
             $files[] = $fileRelativePath;
             $fileSystemPath = sprintf('%s/%s', $xfDir, $fileRelativePath);
             if (is_file($fileSystemPath)) {
                 if (!is_writable($fileSystemPath)) {
                     throw new XenForo_Exception('File is not writable: ' . $fileSystemPath, true);
                 }
             } elseif (is_dir($fileSystemPath)) {
                 throw new XenForo_Exception('File/directory conflict: ' . $fileSystemPath, true);
             } else {
                 $parentOfFileSystemPath = dirname($fileSystemPath);
                 if (is_dir($parentOfFileSystemPath)) {
                     if (!is_writable($parentOfFileSystemPath)) {
                         throw new XenForo_Exception('Directory is not writable: ' . $parentOfFileSystemPath, true);
                     }
                 } else {
                     if (!XenForo_Helper_File::createDirectory($parentOfFileSystemPath)) {
                         throw new XenForo_Exception('Directory cannot be created: ' . $parentOfFileSystemPath, true);
                     }
                 }
             }
         } else {
             $subDirs[] = $fileRelativePath;
         }
     }
     foreach ($subDirs as $subDir) {
         $files = array_merge($files, self::_verifyAddOnFiles($packageDir, $xfDir, $subDir));
     }
     return $files;
 }
예제 #28
0
 /**
  * Writes out an image.
  *
  * @param integer $contentId
  * @param string $size Size code
  * @param string $tempFile Temporary image file. Will be moved.
  *
  * @return boolean
  */
 protected function _writeImage($contentId, $size, $tempFile)
 {
     if (!in_array($size, array_keys(self::$_sizes))) {
         throw new XenForo_Exception('Invalid image size.');
     }
     $filePath = $this->getImageFilePath($contentId, $size);
     $directory = dirname($filePath);
     if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory)) {
         if (file_exists($filePath)) {
             unlink($filePath);
         }
         $success = rename($tempFile, $filePath);
         if ($success) {
             XenForo_Helper_File::makeWritableByFtpUser($filePath);
         }
         return $success;
     } else {
         return false;
     }
 }
예제 #29
0
 public function export($overwrite = false)
 {
     if (!$this->_addOnId) {
         throw new XenForo_Exception('Please specify an add-on id.');
     }
     $filename = str_replace('_', '/', $this->_className) . '.php';
     $existingContents = '';
     $fullFilename = XenForo_Autoloader::getInstance()->getRootDir() . '/' . $filename;
     if (file_exists($fullFilename)) {
         $existingContents = file_get_contents($fullFilename);
         $existingContentsArray = preg_split('/(\\r\\n|\\n|\\r)/', $existingContents);
         foreach ($existingContentsArray as $key => $value) {
             if (rtrim($value) != $value) {
                 $existingContentsArray[$key] = rtrim($value);
             }
         }
         $existingContents = implode("\n", $existingContentsArray);
         $existingContents = str_replace("\t", '	', $existingContents);
         file_put_contents($fullFilename, $existingContents);
         $existingPhpFile = self::createFromContents($this->_className, $existingContents);
     } else {
         if (!file_exists(dirname($fullFilename))) {
             XenForo_Helper_File::createDirectory(dirname($fullFilename));
         }
         $existingPhpFile = self::createFromContents($this->_className);
     }
     $contents = $this->getHeader();
     $this->mergeConstants($existingPhpFile->getConstants());
     if (isset($this->_constants) && !empty($this->_constants)) {
         foreach ($this->_constants as $constantName => $constant) {
             $contents .= $constant->getPhpDocAsString();
             $contents .= "\n\t";
             $contents .= 'const ' . $constant->getConstantName() . ' = ' . $constant->getValue() . ';' . "\n";
         }
     }
     $this->mergeVariables($existingPhpFile->getVariables());
     if (isset($this->_variables) && !empty($this->_variables)) {
         /* @var $variable ThemeHouse_PhpFile_Variable */
         foreach ($this->_variables as $variableName => $variable) {
             $contents .= $variable->getPhpDocAsString();
             $contents .= "\n\t";
             $contents .= $variable->getFullSignatureAsString() . ' = ' . $variable->getValue() . ';' . "\n";
         }
     }
     $this->mergeFunctions($existingPhpFile->getFunctions());
     if (isset($this->_functions) && !empty($this->_functions)) {
         /* @var $function ThemeHouse_PhpFile_Function */
         foreach ($this->_functions as $functionName => $function) {
             $contents .= $function->getPhpDocAsString();
             $contents .= "\n\t";
             $contents .= $function->getFullSignatureAsString();
             $contents .= "\n\t{";
             $contents .= $function->getBodyAsString();
             $contents .= "\n\t}\n";
         }
     }
     $contents .= "}";
     $export = XenForo_CodeEvent::fire('phpfile_export_th', array(&$filename, &$contents, $existingContents, $overwrite, $this->_addOnId));
     if ($export) {
         if (!file_exists(dirname(XenForo_AutoLoader::getInstance()->getRootDir() . '/' . $filename))) {
             mkdir(dirname(XenForo_AutoLoader::getInstance()->getRootDir() . '/' . $filename), 0, true);
         }
         file_put_contents(XenForo_AutoLoader::getInstance()->getRootDir() . '/' . $filename, $contents);
     }
 }
예제 #30
0
 public function createDirectories()
 {
     $internalDataDir = XenForo_Helper_File::getInternalDataPath();
     $dirs = array($internalDataDir . '/temp', $internalDataDir . '/page_cache');
     foreach ($dirs as $dir) {
         XenForo_Helper_File::createDirectory($dir, true);
     }
 }