/** * Saves file in storage * * @param string $sFile * @param string $sDestination * * @return bool|ModuleUploader_EntityItem */ public function Store($sFile, $sDestination = null) { if (!$sDestination) { $oUser = E::ModuleUser()->GetUserCurrent(); if (!$oUser) { return false; } $sDestination = E::ModuleUploader()->GetUserFileDir($oUser->getId()); } if ($sDestination) { $sMimeType = ModuleImg::MimeType($sFile); $bIsImage = strpos($sMimeType, 'image/') === 0; $iUserId = E::UserId(); $sExtension = F::File_GetExtension($sFile, true); if (substr($sDestination, -1) == '/') { $sDestinationDir = $sDestination; } else { $sDestinationDir = dirname($sDestination) . '/'; } $sUuid = ModuleMresource::CreateUuid('file', $sFile, md5_file($sFile), $iUserId); $sDestination = $sDestinationDir . $sUuid . '.' . $sExtension; if ($sStoredFile = E::ModuleUploader()->Move($sFile, $sDestination, true)) { $oStoredItem = E::GetEntity('Uploader_Item', array('storage' => 'file', 'uuid' => $sUuid, 'original_filename' => basename($sFile), 'url' => $this->Dir2Url($sStoredFile), 'file' => $sStoredFile, 'user_id' => $iUserId, 'mime_type' => $sMimeType, 'is_image' => $bIsImage)); return $oStoredItem; } } return false; }
/** * Plugin for Smarty * Returns URL for skin asset file * * @param array $aParams * @param Smarty_Internal_Template $oSmartyTemplate * * @return string */ function smarty_function_asset($aParams, $oSmartyTemplate) { if (empty($aParams['skin']) && empty($aParams['file'])) { trigger_error('Asset: missing "file" parameter', E_USER_WARNING); return ''; } if (isset($aParams['file'])) { if (stripos($aParams['file'], 'http://') === 0 || stripos($aParams['file'], 'https://') === 0 || stripos($aParams['file'], 'http://') === 0) { $sUrl = $aParams['file']; } else { $sSkin = !empty($aParams['skin']) ? $aParams['skin'] : E::ModuleViewer()->GetConfigSkin(); // File name has full local path if (F::File_LocalDir($aParams['file'])) { $sFile = $aParams['file']; } else { // Need URL to asset file if (isset($aParams['theme'])) { if (is_bool($aParams['theme'])) { $sTheme = E::ModuleViewer()->GetConfigTheme(); } else { $sTheme = $aParams['theme']; } } else { $sTheme = ''; } if ($sTheme) { $sTheme = 'themes/' . $sTheme . '/'; } if (isset($aParams['plugin'])) { $sFile = Plugin::GetTemplateFile($aParams['plugin'], $aParams['file']); } else { $sFile = Config::Get('path.skins.dir') . '/' . $sSkin . '/' . $sTheme . $aParams['file']; } } if (isset($aParams['prepare'])) { $sAssetName = empty($aParams['asset']) ? $sFile : $aParams['asset']; // Грязноватый хак, но иначе нам не получить ссылку $aFileData = array($sFile => array('name' => md5($sFile), 'prepare' => true)); /** @var ModuleViewerAsset $oLocalViewerAsset */ $oLocalViewerAsset = new ModuleViewerAsset(); $oLocalViewerAsset->AddFiles(F::File_GetExtension($sFile, true), $aFileData, $sAssetName); $oLocalViewerAsset->Prepare(); //$sUrl = $oLocalViewerAsset->AssetFileUrl(F::File_NormPath($sFile)); $aLinks = $oLocalViewerAsset->GetPreparedAssetLinks(); $sUrl = reset($aLinks); } else { $sUrl = E::ModuleViewerAsset()->File2Link($sFile, 'skin/' . $sSkin . '/'); } } } else { // Need URL to asset dir $sUrl = E::ModuleViewer()->GetAssetUrl() . 'skin/' . $aParams['skin'] . '/'; } return $sUrl; }
/** * Plugin for Smarty * Returns URL for skin asset file * * @param array $aParams * @param Smarty_Internal_Template $oSmartyTemplate * * @return string */ function smarty_function_asset($aParams, $oSmartyTemplate) { if (empty($aParams['skin']) && empty($aParams['file'])) { trigger_error('Asset: missing "file" parametr', E_USER_WARNING); return ''; } if (isset($aParams['file'])) { if (stripos($aParams['file'], 'http://') === 0 || stripos($aParams['file'], 'https://') === 0 || stripos($aParams['file'], 'http://') === 0) { $sUrl = $aParams['file']; } else { if (F::File_LocalDir($aParams['file'])) { $sFile = $aParams['file']; } else { // Need URL to asset file if (empty($aParams['skin'])) { $sSkin = E::ModuleViewer()->GetConfigSkin(); } else { $sSkin = $aParams['skin']; } if (isset($aParams['theme'])) { if (is_bool($aParams['theme'])) { $sTheme = E::ModuleViewer()->GetConfigTheme(); } else { $sTheme = $aParams['theme']; } } else { $sTheme = ''; } if ($sTheme) { $sTheme = 'themes/' . $sTheme . '/'; } if (isset($aParams['plugin'])) { $sFile = Plugin::GetTemplateFile($aParams['plugin'], $aParams['file']); } else { $sFile = Config::Get('path.skins.dir') . '/' . $sSkin . '/' . $sTheme . $aParams['file']; } } if (isset($aParams['prepare'])) { /** @var ModuleViewerAsset $oLocalViewerAsset */ $oLocalViewerAsset = new ModuleViewerAsset(); $oLocalViewerAsset->AddFiles(F::File_GetExtension($sFile, true), array($sFile)); $oLocalViewerAsset->Prepare(); $sUrl = $oLocalViewerAsset->AssetFileUrl(F::File_NormPath($sFile)); } else { $sUrl = E::ModuleViewerAsset()->File2Link($sFile, 'skin/' . $sSkin . '/'); } } } else { // Need URL to asset dir $sUrl = E::ModuleViewer()->GetAssetUrl() . 'skin/' . $aParams['skin'] . '/'; } return $sUrl; }
/** * Save uploaded image into store * * @param string $sImageFile * @param ModuleUser_EntityUser $oUser * @param string $sType * @param array $aOptions * * @return bool */ protected function _saveTopicImage($sImageFile, $oUser, $sType, $aOptions = array()) { $sExtension = F::File_GetExtension($sImageFile, true); $aConfig = E::ModuleUploader()->GetConfig($sImageFile, 'images.' . $sType); if ($aOptions) { $aConfig['transform'] = F::Array_Merge($aConfig['transform'], $aOptions); } // Check whether to save the original if (isset($aConfig['original']['save']) && $aConfig['original']['save']) { $sSuffix = isset($aConfig['original']['suffix']) ? $aConfig['original']['suffix'] : '-original'; $sOriginalFile = F::File_Copy($sImageFile, $sImageFile . $sSuffix . '.' . $sExtension); } else { $sSuffix = ''; $sOriginalFile = null; } // Transform image before saving $sFileTmp = E::ModuleImg()->TransformFile($sImageFile, $aConfig['transform']); if ($sFileTmp) { $sDirUpload = E::ModuleUploader()->GetUserImageDir($oUser->getId(), true, $sType); $sFileImage = E::ModuleUploader()->Uniqname($sDirUpload, $sExtension); if ($oStoredFile = E::ModuleUploader()->Store($sFileTmp, $sFileImage)) { if ($sOriginalFile) { E::ModuleUploader()->Move($sOriginalFile, $oStoredFile->GetFile() . $sSuffix . '.' . $sExtension); } return $oStoredFile->GetUrl(); } } return false; }
public function Process() { $bResult = true; foreach ($this->aLinks as $nIdx => $aLinkData) { if (empty($aLinkData['throw']) && !empty($aLinkData['compress'])) { $sAssetFile = $aLinkData['asset_file']; $sExtension = 'min.' . F::File_GetExtension($sAssetFile); $sCompressedFile = F::File_SetExtension($sAssetFile, $sExtension); if (!$this->CheckDestination($sCompressedFile)) { if ($sContents = F::File_GetContents($sAssetFile)) { $sContents = $this->Compress($sContents); if (F::File_PutContents($sCompressedFile, $sContents)) { F::File_Delete($sAssetFile); $this->aLinks[$nIdx]['link'] = F::File_SetExtension($this->aLinks[$nIdx]['link'], $sExtension); if (C::Get('compress.css.gzip') && C::Get('compress.css.merge') && C::Get('compress.css.use')) { // Сохраним gzip $sCompressedContent = gzencode($sContents, 9); F::File_PutContents($sCompressedFile . '.gz.css', $sCompressedContent); } } } } else { $this->aLinks[$nIdx]['link'] = F::File_SetExtension($this->aLinks[$nIdx]['link'], $sExtension); } } } return $bResult; }
/** * @param string $sType * @param array $aFiles * @param array $aOptions */ public function AddFilesToAssets($sType, $aFiles, $aOptions = array()) { if (!is_array($aFiles)) { $aFiles = array(array('file' => (string) $aFiles)); } $aAssetFiles = array(); $aFileList = array(); // seek wildcards - if name hase '*' then add files by pattern foreach ($aFiles as $sFileName => $aFileParams) { if (strpos($sFileName, '*')) { unset($aFiles[$sFileName]); $aFoundFiles = F::File_ReadFileList($sFileName, 0, true); if ($aFoundFiles) { foreach ($aFoundFiles as $sAddFile) { $sAddType = F::File_GetExtension($sAddFile, true); $aFileParams['name'] = $sAddFile; $aFileParams['file'] = $sAddFile; if ($sAddType == $sType) { $aFileList[$sAddFile] = $aFileParams; } else { $this->AddFilesToAssets($sAddType, array($sAddFile => $aFileParams), $aOptions); } } } } else { $aFileList[$sFileName] = $aFileParams; } } foreach ($aFileList as $sFileName => $aFileParams) { // extract & normalize full file path if (isset($aFileParams['file'])) { $sFile = F::File_NormPath($aFileParams['file']); } else { $sFile = F::File_NormPath((string) $sFileName); } $sName = isset($aFileParams['name']) ? $aFileParams['name'] : $sFile; if (!is_array($aFileParams)) { $aFileParams = array(); } $aFileParams['file'] = F::File_NormPath($sFile); $aFileParams['name'] = F::File_NormPath($sName); $aAssetFiles[$sName] = $aFileParams; } return $this->_add($sType, $aAssetFiles, $aOptions); }
/** * Загружаем картинку */ public function EventUploadImage() { // Устанавливаем формат Ajax ответа E::ModuleViewer()->SetResponseAjax('json', FALSE); E::ModuleSecurity()->ValidateSendForm(); // Проверяем, загружен ли файл if (!($aUploadedFile = $this->GetUploadedFile('uploader-upload-image'))) { E::ModuleMessage()->AddError(E::ModuleLang()->Get('error_upload_image'), E::ModuleLang()->Get('error')); return; } $sTarget = F::GetRequest('target', FALSE); $sTargetId = F::GetRequest('target_id', FALSE); // Проверяем, целевой объект и права на его редактирование if (!($oTarget = E::ModuleUploader()->CheckAccessAndGetTarget($sTarget, $sTargetId))) { // Здесь два варианта, либо редактировать нельзя, либо можно, но топика еще нет if ($oTarget === TRUE) { // Будем делать временную картинку } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error')); return; } } // Ошибок пока нет $sError = ''; // Загружаем временный файл $sTmpFile = E::ModuleUploader()->UploadLocal($aUploadedFile, $sTarget); // Вызовем хук перед началом загрузки картинки E::ModuleHook()->Run('uploader_upload_before', array('oTarget' => $oTarget, 'sTmpFile' => $sTmpFile, 'sTarget' => $sTarget, 'sTargetId' => $sTargetId)); // Если все ок, и по миме проходит, то if ($sTmpFile) { if (E::ModuleImg()->MimeType($sTmpFile)) { // Ресайзим и сохраняем уменьшенную копию // Храним две копии - мелкую для показа пользователю и крупную в качестве исходной для ресайза $sPreviewFile = E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false) . '_preview.' . F::File_GetExtension($sTmpFile); if ($sPreviewFile = E::ModuleImg()->Copy($sTmpFile, $sPreviewFile, self::PREVIEW_RESIZE, self::PREVIEW_RESIZE)) { // * Сохраняем в сессии временный файл с изображением E::ModuleSession()->Set('sTarget', $sTarget); E::ModuleSession()->Set('sTargetId', $sTargetId); E::ModuleSession()->Set("sTmp-{$sTarget}-{$sTargetId}", $sTmpFile); E::ModuleSession()->Set("sPreview-{$sTarget}-{$sTargetId}", $sPreviewFile); E::ModuleViewer()->AssignAjax('sPreview', E::ModuleUploader()->Dir2Url($sPreviewFile)); if (getRequest('direct', FALSE)) { $this->EventDirectImage(); } return; } } else { $sError = E::ModuleLang()->Get('error_upload_wrong_image_type'); } } else { // Ошибки загрузки картинки $sError = E::ModuleUploader()->GetErrorMsg(); if (!$sError) { $sError = E::ModuleLang()->Get('error_upload_image'); } } // Выведем ошибки пользователю E::ModuleMessage()->AddError($sError, E::ModuleLang()->Get('error')); // Удалим ранее загруженый файл F::File_Delete($sTmpFile); }
/** * Upload remote file by URL * * @param string $sUrl * @param string $sTarget * @param string $sDir * @param array $aParams [max_size => «размер в килобайтах»] * * @return bool */ public function UploadRemote($sUrl, $sTarget = 'default', $sDir = null, $aParams = array()) { $this->nLastError = 0; if (!isset($aParams['max_size'])) { $aParams['max_size'] = 0; } else { $aParams['max_size'] = intval($aParams['max_size']); } $sContent = ''; if ($aParams['max_size']) { $hFile = @fopen($sUrl, 'r'); if (!$hFile) { $this->nLastError = self::ERR_REMOTE_FILE_OPEN; return false; } $nSizeKb = 0; while (!feof($hFile) && $nSizeKb <= $aParams['max_size']) { $sPiece = fread($hFile, 1024); if ($sPiece) { $nSizeKb += strlen($sPiece); $sContent .= $sPiece; } else { break; } } fclose($hFile); // * Если конец файла не достигнут, значит файл имеет недопустимый размер if ($nSizeKb > $aParams['max_size']) { $this->nLastError = self::ERR_REMOTE_FILE_MAXSIZE; return false; } } else { $sContent = @file_get_contents($sUrl); if ($sContent === false) { $this->nLastError = self::ERR_REMOTE_FILE_READ; return false; } } if ($sContent) { $sTmpFile = F::File_UploadUniqname(F::File_GetExtension($sUrl)); if (!F::File_PutContents($sTmpFile, $sContent)) { $this->nLastError = self::ERR_REMOTE_FILE_WRITE; return false; } } if (!empty($sTmpFile) && $this->_checkUploadedFile($sTmpFile, $sTarget)) { if ($sDir) { return $this->MoveTmpFile($sTmpFile, $sDir); } else { return $sTmpFile; } } return false; }
/** * Загрузка временной картинки фото для последущего ресайза */ protected function EventUploadPhoto() { if (isset($_FILES['foto']) && !isset($_FILES['photo'])) { $_FILES['photo'] = $_FILES['foto']; } // * Устанавливаем формат Ajax ответа $this->Viewer_SetResponseAjax(F::AjaxRequest(true) ? 'json' : 'jsonIframe', false); if (!($aUploadedFile = $this->GetUploadedFile('photo')) && !($aUploadedFile = $this->GetUploadedFile('foto'))) { $this->Message_AddError($this->Lang_Get('settings_profile_photo_error'), $this->Lang_Get('error')); return; } $sError = ''; $sTmpFile = $this->Uploader_UploadLocal($aUploadedFile); if ($sTmpFile && $this->Img_MimeType($sTmpFile)) { /** * Ресайзим и сохраняем уменьшенную копию * Храним две копии - мелкую для показа пользователю и крупную в качестве исходной для ресайза */ $sPreviewFile = $this->Uploader_GetUserAvatarDir($this->oUserCurrent->getId()) . 'photo-preview.' . F::File_GetExtension($sTmpFile, true); if ($sPreviewFile = $this->Img_Copy($sTmpFile, $sPreviewFile, self::PREVIEW_RESIZE, self::PREVIEW_RESIZE)) { // * Сохраняем в сессии временный файл с изображением $this->Session_Set('sPhotoTmp', $sTmpFile); $this->Session_Set('sPhotoPreview', $sPreviewFile); $this->Viewer_AssignAjax('sTmpFile', $this->Uploader_Dir2Url($sPreviewFile)); return; } } else { $sError = $this->Uploader_GetErrorMsg(); if (!$sError) { $sError = $this->Lang_Get('settings_profile_photo_error'); } } $this->Message_AddError($sError, $this->Lang_Get('error')); F::File_Delete($sTmpFile); }