コード例 #1
1
ファイル: file.php プロジェクト: DarneoStudio/bitrix
 function CheckRights($method, $strong, &$path)
 {
     $result = true;
     if (!parent::CheckRights($method)) {
         $result = false;
         $GLOBALS["APPLICATION"]->ThrowException(GetMessage('WD_ACCESS_DENIED'), 'ACCESS_DENIED');
     } elseif ($path != '') {
         $io = CBXVirtualIo::GetInstance();
         $path = $io->CombinePath($this->_udecode($path));
         $strFileName = GetFileName($path);
         $extention = "." . strtolower(GetFileExtension($strFileName));
         if (in_array($method, array("COPY", "MOVE", "PUT"))) {
             if (!$GLOBALS["USER"]->IsAdmin() && HasScriptExtension($strFileName)) {
                 $result = false;
                 $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR13"), "FORBIDDEN_EXTENTION");
             } elseif (IsFileUnsafe($strFileName) || $strFileName == "index.php") {
                 $result = false;
                 $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR14"), "FORBIDDEN_NAME");
             } elseif (!$io->ValidatePathString($io->CombinePath("/", $path)) || !$io->ValidateFilenameString($strFileName)) {
                 $result = false;
                 $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR14"), "FORBIDDEN_NAME");
             } elseif (in_array($extention, $this->arFileForbiddenExtentions["WRITE"])) {
                 $result = false;
                 $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR13"), "FORBIDDEN_EXTENTION");
             }
         } elseif (in_array($extention, $this->arFileForbiddenExtentions["READ"])) {
             $result = false;
             $GLOBALS["APPLICATION"]->ThrowException(GetMessage('WD_ACCESS_DENIED'), 'ACCESS_DENIED');
         }
     }
     return $result;
 }
コード例 #2
0
/**
 * Парсер смайликов.
 * @param  $text
 * @return void
 */
function SmiliesReplace(&$text)
{
    static $codes = null;
    if (!isset($codes)) {
        $codes = array();
        $smilies_dir = System::config('general/smilies_dir');
        $smilies = System::database()->Select('smilies');
        // Пусть отключенные смайлики тоже парсятся
        foreach ($smilies as $smile) {
            $sub_codes = explode(',', $smile['code']);
            $smile_file = SafeDB($smile['file'], 255, str);
            if ($smile['desc'] != '') {
                $title = SafeDB($smile['desc'], 255, str);
            } else {
                $title = SafeDB(GetFileName($smile_file, true), 255, str);
            }
            foreach ($sub_codes as $code) {
                $code = trim($code);
                if ($code != '') {
                    $codes[$code] = '<img src="' . RealPath2($smilies_dir . $smile_file) . '" title="' . $title . '">';
                }
            }
        }
    }
    $text = strtr($text, $codes);
}
コード例 #3
0
function FormsCheckType($var, $typearr, &$error = null, &$filename = null)
{
    if ($typearr[1] == 'file') {
        $file_save_dir = 'uploads/forms';
        if (!is_dir($file_save_dir)) {
            mkdir($file_save_dir);
        }
        $UploadErrors = array(0 => '', 1 => 'Размер файла превышен', 2 => 'Размер файла превышен', 3 => 'Файл загружен только частично', 4 => 'Файл не был загружен.', 6 => 'Не найдена папка для временных файлов на сервере', 7 => 'Ошибка во время записи на диск', 8 => 'Загрузка файла была прервана расширением PHP', 9 => 'Ошибка во время записи на диск');
        if ($var['error'] == UPLOAD_ERR_OK) {
            $filename = Translit($var['name'], true);
            $ext = GetFileExt($filename);
            $name = GetFileName($filename, true);
            $file_path = $file_save_dir . '/' . $name . '_' . GenRandomString(8) . $ext;
            copy($var['tmp_name'], $file_path);
            return $file_path;
        } else {
            if ($var['error'] != 4) {
                $error = $UploadErrors[$var['error']];
            }
            return '';
        }
    }
    if ($typearr[2] == 'false') {
        $strip_tags = false;
    } else {
        $strip_tags = true;
    }
    $r = SafeEnv($var, (int) $typearr[0], (string) $typearr[1], $strip_tags);
    if ($r === false) {
        $r = '0';
    } elseif ($r === true) {
        $r = '1';
    }
    return $r;
}
コード例 #4
0
 public function __construct($Url = '', $Utf8 = false)
 {
     if ($Url == '') {
         return;
     }
     $info = parse_url($Url);
     if ($info === false) {
         return;
     }
     if (isset($info['scheme'])) {
         $this->Protocol = $info['scheme'];
     }
     if (isset($info['host'])) {
         $this->Host = $info['host'];
     }
     if (isset($info['port'])) {
         $this->Port = $info['port'];
     }
     if (isset($info['user'])) {
         $this->User = $info['user'];
     }
     if (isset($info['pass'])) {
         $this->Password = $info['pass'];
     }
     if (isset($info['path'])) {
         $this->Path = GetPathName($info['path']);
         $this->Document = GetFileName($info['path']);
     }
     if (isset($info['fragment'])) {
         $this->Anchor = $info['fragment'];
     }
     if (isset($info['query'])) {
         parse_str($info['query'], $params);
         parent::__construct($params);
         if ($Utf8) {
             foreach ($this as $key => $value) {
                 $value = Utf8ToCp1251($value);
                 $this[$key] = $value;
             }
         }
     } else {
         parent::__construct();
     }
 }
コード例 #5
0
function GetFileNewName($aid, $typeid, $timetag, $title, $ismake = 0, $rank = 0, $namerule = '', $typedir = '', $money = 0, $filename = '')
{
    global $cfg_arc_dirname;
    $articlename = GetFileName($aid, $typeid, $timetag, $title, $ismake, $rank, $namerule, $typedir, $money, $filename);
    if (ereg("\\?", $articlename)) {
        return $articlename;
    }
    if ($cfg_arc_dirname == 'Y' && ereg("/\$", $articlename)) {
        $articlename = $articlename . "index.html";
    }
    $slen = strlen($articlename) - 1;
    for ($i = $slen; $i >= 0; $i--) {
        if ($articlename[$i] == '/') {
            $subpos = $i;
            break;
        }
    }
    $okdir = substr($articlename, 0, $subpos);
    CreateDir($okdir);
    return $articlename;
}
コード例 #6
0
ファイル: smile.php プロジェクト: andy-profi/bxApiDocs
 public static function import($arParams)
 {
     global $APPLICATION;
     // check fields
     $aMsg = array();
     $arParams['SET_ID'] = intval($arParams['SET_ID']);
     $arParams['IMPORT_IF_FILE_EXISTS'] = isset($arParams['IMPORT_IF_FILE_EXISTS']) && $arParams['IMPORT_IF_FILE_EXISTS'] == 'Y' ? true : false;
     if (isset($arParams['FILE']) && GetFileExtension($arParams['FILE']) != 'zip') {
         $aMsg["FILE_EXT"] = array("id" => "FILE_EXT", "text" => GetMessage("MAIN_SMILE_IMPORT_FILE_EXT_ERROR"));
     } else {
         if (!isset($arParams['FILE']) || !file_exists($arParams['FILE'])) {
             $aMsg["FILE"] = array("id" => "FILE", "text" => GetMessage("MAIN_SMILE_IMPORT_FILE_ERROR"));
         } else {
             if ($arParams['SET_ID'] <= 0) {
                 $aMsg["SET_ID"] = array("id" => "SET_ID", "text" => GetMessage("MAIN_SMILE_IMPORT_SET_ID_ERROR"));
             }
         }
     }
     if (!empty($aMsg)) {
         $e = new CAdminException($aMsg);
         $APPLICATION->ThrowException($e);
         return false;
     }
     $sUnpackDir = CTempFile::GetDirectoryName(1);
     CheckDirPath($sUnpackDir);
     /** @var IBXArchive $oArchiver */
     $oArchiver = CBXArchive::GetArchive($arParams['FILE'], "ZIP");
     $oArchiver->SetOptions(array("STEP_TIME" => 300));
     if (!$oArchiver->Unpack($sUnpackDir)) {
         $aMsg["UNPACK"] = array("id" => "UNPACK", "text" => GetMessage("MAIN_SMILE_IMPORT_UNPACK_ERROR"));
         $e = new CAdminException($aMsg);
         $APPLICATION->ThrowException($e);
         return false;
     }
     $arSmiles = array();
     if (file_exists($sUnpackDir . 'install.csv')) {
         $arLang = array();
         $db_res = CLanguage::GetList($b = "sort", $o = "asc");
         while ($res = $db_res->Fetch()) {
             if (file_exists($sUnpackDir . 'install_lang_' . $res["LID"] . '.csv')) {
                 $arSmiles = array();
                 $csvFile = new CCSVData();
                 $csvFile->LoadFile($sUnpackDir . 'install_lang_' . $res["LID"] . '.csv');
                 $csvFile->SetFieldsType("R");
                 $csvFile->SetFirstHeader(false);
                 while ($smile = $csvFile->Fetch()) {
                     if (defined('BX_UTF') && BX_UTF && $res["LID"] == 'ru') {
                         $smile[1] = $APPLICATION->ConvertCharset($smile[1], 'windows-1251', 'utf-8');
                     }
                     $arLang[$smile[0]][$res["LID"]] = $smile[1];
                 }
             }
         }
         $csvFile = new CCSVData();
         $csvFile->LoadFile($sUnpackDir . 'install.csv');
         $csvFile->SetFieldsType("R");
         $csvFile->SetFirstHeader(false);
         while ($smileRes = $csvFile->Fetch()) {
             $smile = array('TYPE' => $smileRes[0], 'CLICKABLE' => $smileRes[1] == 'Y' ? 'Y' : 'N', 'SORT' => intval($smileRes[2]), 'IMAGE' => $smileRes[3], 'IMAGE_WIDTH' => intval($smileRes[4]), 'IMAGE_HEIGHT' => intval($smileRes[5]), 'IMAGE_DEFINITION' => in_array($smileRes[6], array(self::IMAGE_SD, self::IMAGE_HD, self::IMAGE_UHD)) ? $smileRes[6] : ($smileRes[6] == 'Y' ? self::IMAGE_HD : self::IMAGE_SD), 'HIDDEN' => in_array($smileRes[7], array('Y', 'N')) ? $smileRes[7] : 'N', 'IMAGE_LANG' => in_array($smileRes[7], array('Y', 'N')) ? $smileRes[8] : $smileRes[7], 'TYPING' => in_array($smileRes[7], array('Y', 'N')) ? $smileRes[9] : $smileRes[8]);
             if (!in_array($smile['TYPE'], array(CSmile::TYPE_SMILE, CSmile::TYPE_ICON))) {
                 continue;
             }
             $smile['IMAGE'] = GetFileName($smile['IMAGE']);
             $imgArray = CFile::GetImageSize($sUnpackDir . $smile['IMAGE']);
             if (!is_array($imgArray)) {
                 continue;
             }
             $arInsert = array('TYPE' => $smile['TYPE'], 'SET_ID' => $arParams['SET_ID'], 'CLICKABLE' => $smile['CLICKABLE'], 'SORT' => $smile['SORT'], 'IMAGE' => $smile['IMAGE'], 'IMAGE_WIDTH' => $smile['IMAGE_WIDTH'], 'IMAGE_HEIGHT' => $smile['IMAGE_HEIGHT'], 'IMAGE_DEFINITION' => $smile['IMAGE_DEFINITION'], 'HIDDEN' => $smile['HIDDEN'], 'TYPING' => $smile['TYPING']);
             if (isset($arLang[$smile['IMAGE_LANG']])) {
                 $arInsert['LANG'] = $arLang[$smile['IMAGE_LANG']];
             }
             $arSmiles[] = $arInsert;
         }
     } else {
         $smileSet = CSmileSet::getById($arParams['SET_ID']);
         if ($handle = @opendir($sUnpackDir)) {
             $sort = 300;
             while (($file = readdir($handle)) !== false) {
                 if ($file == "." || $file == "..") {
                     continue;
                 }
                 if (is_file($sUnpackDir . $file)) {
                     $imgArray = CFile::GetImageSize($sUnpackDir . $file);
                     if (is_array($imgArray)) {
                         $smileHR = self::IMAGE_SD;
                         $smileType = CSmile::TYPE_SMILE;
                         $smileCode = GetFileNameWithoutExtension($file);
                         if (strpos($file, 'smile_') !== false && strpos($file, 'smile_') == 0) {
                             $smileCode = substr($smileCode, 6);
                         } elseif (strpos($file, 'smile') !== false && strpos($file, 'smile') == 0) {
                             $smileCode = substr($smileCode, 5);
                         } elseif (strpos($file, 'icon_') !== false && strpos($file, 'icon_') == 0) {
                             $smileType = CSmile::TYPE_ICON;
                             $smileCode = substr($smileCode, 5);
                         } else {
                             if (strpos($file, 'icon') !== false && strpos($file, 'icon') == 0) {
                                 $smileType = CSmile::TYPE_ICON;
                                 $smileCode = substr($smileCode, 4);
                             }
                         }
                         if (strrpos($smileCode, '_hr') !== false && strrpos($smileCode, '_hr') == strlen($smileCode) - 3) {
                             $smileHR = self::IMAGE_HD;
                             $smileCode = substr($smileCode, 0, strrpos($smileCode, '_hr'));
                         }
                         if ($pos = strpos($smileCode, '_hr_')) {
                             $smileHR = self::IMAGE_HD;
                             $smileCode = substr($smileCode, 0, $pos) . '_' . substr($smileCode, $pos + 4);
                         }
                         $arSmiles[] = array('TYPE' => $smileType, 'SET_ID' => $arParams['SET_ID'], 'CLICKABLE' => 'Y', 'SORT' => $sort, 'IMAGE' => $file, 'IMAGE_WIDTH' => intval($imgArray[0]), 'IMAGE_HEIGHT' => intval($imgArray[1]), 'IMAGE_DEFINITION' => $smileHR, 'TYPING' => ':' . (isset($smileSet['STRING_ID']) ? $smileSet['STRING_ID'] : $smileSet['ID']) . '/' . $smileCode . ':');
                         $sort = $sort + 5;
                     }
                 }
             }
             @closedir($handle);
         }
     }
     $importSmile = 0;
     foreach ($arSmiles as $smile) {
         $sUploadDir = ($smile['TYPE'] == CSmile::TYPE_ICON ? CSmile::PATH_TO_ICON : CSmile::PATH_TO_SMILE) . intval($smile["SET_ID"]) . '/';
         if (file_exists($sUnpackDir . $smile['IMAGE']) && ($arParams['IMPORT_IF_FILE_EXISTS'] || !file_exists($_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE']))) {
             if (CheckDirPath($_SERVER["DOCUMENT_ROOT"] . $sUploadDir)) {
                 $insertId = CSmile::add($smile);
                 if ($insertId) {
                     if ($arParams['IMPORT_IF_FILE_EXISTS'] && file_exists($_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE'])) {
                         $importSmile++;
                     } else {
                         if (copy($sUnpackDir . $smile['IMAGE'], $_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE'])) {
                             @chmod($_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE'], BX_FILE_PERMISSIONS);
                             $importSmile++;
                         } else {
                             CSmile::delete($insertId);
                         }
                     }
                 }
                 $APPLICATION->ResetException();
             }
         }
     }
     return $importSmile;
 }
コード例 #7
0
ファイル: fileman.php プロジェクト: Satariall/izurit
 function GetFileName($path)
 {
     return GetFileName($path);
 }
コード例 #8
0
ファイル: component.php プロジェクト: mrdeadmouse/u136006
} elseif (SITE_TEMPLATE_ID == "bitrix24") {
    $sType = "b24_template";
}
$arResult = array("SITE_TYPE" => $sType, "ICON" => "empty.jpg", "F_SIZE" => 0, "DESCRIPTION" => "", "FILE_NOT_FOUND" => false, "PASSWORD" => "NOT");
$hash = CWebDavExtLinks::GetHashFromURL();
if ($hash === false) {
    ShowError(GetMessage('WD_MODULE_IS_FILE_NOT_FOUND'));
    return 0;
}
//not set default value to in getList LINK_TYPE
$resF = CWebDavExtLinks::GetList(array("HASH" => $hash, "ACTUAL" => true, 'LINK_TYPE' => null), array("URL", "RESOURCE_TYPE", "FOLDER", "IBLOCK_TYPE", "IBLOCK_ID", "BASE_URL", "HASH", "CREATION_DATE", "USER_ID", "SALT", "PASSWORD", "LIFETIME", "F_SIZE", "DESCRIPTION", "ROOT_SECTION_ID", "URL_HASH", 'SINGLE_SESSION', 'LINK_TYPE', 'DOWNLOAD_COUNT', 'VERSION_ID', 'ELEMENT_ID', 'FILE_ID'));
$arGetListRes = null;
if ($arF = $resF->Fetch()) {
    $arGetListRes = $arF;
    $arResult["HASH"] = $hash;
    $arResult["NAME"] = GetFileName($arF["URL"]);
    $arResult["ICON"] = CWebDavExtLinks::GetExtensionIcon($arF["URL"]);
    $arResult["F_SIZE"] = $arF["F_SIZE"];
    $arResult["DESCRIPTION"] = $arF["DESCRIPTION"];
    $arResult["PASSWORD"] = CheckUserPassword($arF);
    $arResult["DOWNLOAD_COUNT"] = $arF['DOWNLOAD_COUNT'];
}
if (!$arF || !empty($_GET['notfoud'])) {
    $arResult["NAME"] = GetMessage("WD_MODULE_IS_FILE_NOT_FOUND");
    $arResult["ICON"] = "nf.png";
    $arResult["F_SIZE"] = 0;
    $arResult["DESCRIPTION"] = GetMessage("WD_MODULE_IS_FILE_NOT_FOUND_DESCRIPTION");
    $arResult["FILE_NOT_FOUND"] = true;
}
if (!empty($_POST['checkViewByGoogle'])) {
    CWebDavTools::sendJsonResponse(array('viewByGoogle' => $arResult["DOWNLOAD_COUNT"] > 0));
コード例 #9
0
ファイル: fileman.php プロジェクト: ASDAFF/bxApiDocs
	public static function GetFileName($path)
	{
		return GetFileName($path);
	}
コード例 #10
0
ファイル: tools.php プロジェクト: nProfessor/Mytb
function IsFileUnsafe($name)
{
	static $arFiles = false;
	if($arFiles === false)
	{
		$fileList = COption::GetOptionString("main", "~unsafe_files", ".htaccess,.htpasswd,web.config,global.asax");
		$arFiles = explode(",", strtolower($fileList));
	}
	$name = GetFileName($name);
	return in_array(strtolower(TrimUnsafe($name)), $arFiles);
}
コード例 #11
0
 /**
  * Восстанавливает базу данных из резервной копии.
  * @param type $BackupFile Имя файла бекапа
  * @param type $Table      Имя таблицы, если нужно восстановить одну таблицу
  */
 public function RestoreBackupFile($BackupFile, $Table = '')
 {
     $zip = new ZipArchive();
     $iferrors = false;
     if (GetSecondFileExt($BackupFile, true) == $this->Name && $zip->open($BackupFile) === true) {
         for ($i = 0; $i < $zip->numFiles; $i++) {
             $filename = $zip->getNameIndex($i);
             if ($Table == '' || $Table == GetFileName($filename, true)) {
                 $sql = $zip->getFromIndex($i);
                 $sql = explode(";", $sql);
                 foreach ($sql as $query) {
                     if (trim($query) == '') {
                         continue;
                     }
                     if (System::database()->MySQLQuery($query) === false) {
                         if (defined('ADMIN_SCRIPT')) {
                             System::admin()->HighlightError(System::database()->MySQLGetErrMsg() . ' (' . $filename . ')');
                         }
                         $iferrors = true;
                     }
                 }
             }
         }
         $zip->close();
         // Обрабытываем ошибки
         if ($iferrors) {
             return 2;
             // Ошибки при восстановлении таблиц
         }
         return 1;
         // Успешно восстановлено
     } else {
         return 3;
         // Неверный формат файла
     }
 }
コード例 #12
0
ファイル: file.php プロジェクト: nProfessor/Mytb
	function CheckFile($arFile, $intMaxSize=0, $strMimeType=false, $strExt=false)
	{
		/****************************** QUOTA ******************************/
		if (COption::GetOptionInt("main", "disk_space") > 0)
		{
			$quota = new CDiskQuota;
			if (!$quota->checkDiskQuota($arFile))
				return $quota->LAST_ERROR;
		}
		/****************************** QUOTA ******************************/
		if(strlen($arFile["name"])<=0)
			return "";

		if(strlen(GetFileName($arFile["name"])) > 255)
			return GetMessage("MAIN_BAD_FILENAME_LEN");

		if(COption::GetOptionString("main", "save_original_file_name", "N")=="Y" && COption::GetOptionString("main", "convert_original_file_name", "Y")!="Y")
		{
			$io = CBXVirtualIo::GetInstance();
			if(!$io->ValidateFilenameString(bx_basename($arFile["name"])))
				return GetMessage("MAIN_BAD_FILENAME1");
		}

		if($intMaxSize>0 && intval($arFile["size"])>$intMaxSize)
		{
			return GetMessage("FILE_BAD_SIZE")." (".CFile::FormatSize($intMaxSize).").";
		}

		$strFileExt = '';
		if($strExt)
		{
			$strFileExt = GetFileExtension($arFile["name"]);
			if($strFileExt == '')
				return GetMessage("FILE_BAD_TYPE");
		}

		//Check mime_type and ext
		if($strMimeType!==false && substr($arFile["type"], 0, strlen($strMimeType)) != $strMimeType)
			return GetMessage("FILE_BAD_TYPE")."!";

		if($strExt===false)
			return "";

		$IsExtCorrect = true;
		if($strExt)
		{
			$IsExtCorrect = false;
			$tok = strtok($strExt,",");
			while($tok)
			{
				if(strtolower(trim($tok)) == strtolower($strFileExt))
				{
					$IsExtCorrect=true;
					break;
				}
				$tok = strtok(",");
			}
		}

		if($IsExtCorrect)
			return "";

		return GetMessage("FILE_BAD_TYPE")." (".strip_tags($strFileExt).")!";
	}
コード例 #13
0
    $aTabs[] = array("DIV" => "edit1", "TAB" => GetMessage("FLOW_EDIT_RECORD"), "ICON" => "workflow_edit", "TITLE" => GetMessage("FLOW_NEW_RECORD"));
}
$aTabs[] = array("DIV" => "edit2", "TAB" => GetMessage("FLOW_UPLOADED_FILES"), "ICON" => "workflow_edit", "TITLE" => GetMessage("FLOW_UPLOADED_FILES_TITLE"));
$aTabs[] = array("DIV" => "edit3", "TAB" => GetMessage("FLOW_COMMENTS"), "ICON" => "workflow_edit", "TITLE" => GetMessage("FLOW_COMMENTS_TITLE"));
$tabControl = new CAdminTabControl("tabControl", $aTabs);
// Save or Apply was clicked
if ((strlen($save) > 0 || strlen($apply) > 0) && $WORKFLOW_RIGHT > "R" && $REQUEST_METHOD == "POST" && check_bitrix_sessid()) {
    if (CheckFields()) {
        $nums = intval($nums);
        if ($nums > 0) {
            for ($i = 1; $i <= $nums; $i++) {
                $arFile = $HTTP_POST_FILES["file_" . $i];
                if (strlen($arFile["name"]) <= 0 || $arFile["tmp_name"] == "none") {
                    continue;
                }
                $arFile["name"] = GetFileName($arFile["name"]);
                $fname = ${"fname_" . $i};
                if (strlen($fname) <= 0) {
                    $fname = $arFile["name"];
                }
                $path = GetDirPath($FILENAME);
                $pathto = Rel2Abs($path, $fname);
                $ext = GetFileExtension($pathto);
                if (!$USER->IsAdmin() && in_array($ext, $arExt)) {
                    $message = new CAdminMessage(array("MESSAGE" => GetMessage("FLOW_ERROR"), "DETAILS" => GetMessage("FLOW_FILEUPLOAD_PHPERROR") . " \"" . $pathto . "\"", "TYPE" => "ERROR"));
                } elseif (!$USER->CanDoFileOperation('fm_edit_in_workflow', array($SITE_ID, $pathto))) {
                    $message = new CAdminMessage(array("MESSAGE" => GetMessage("FLOW_ERROR"), "DETAILS" => GetMessage("FLOW_FILEUPLOAD_ACCESS_DENIED") . " \"" . $pathto . "\": " . GetMessage("FLOW_MIN_RIGHTS"), "TYPE" => "ERROR"));
                } elseif (!CBXVirtualIoFileSystem::ValidatePathString($pathto)) {
                    $message = new CAdminMessage(array("MESSAGE" => GetMessage("FLOW_ERROR"), "DETAILS" => GetMessage("FLOW_FILE_NAME_NOT_VALID"), "TYPE" => "ERROR"));
                } else {
                    $z = CWorkflow::GetFileByID($ID, $pathto);
コード例 #14
0
ファイル: file.php プロジェクト: nycmic/bittest
 function SaveFile($arFile, $strSavePath, $bForceMD5 = false, $bSkipExt = false)
 {
     $strFileName = GetFileName($arFile["name"]);
     /* filename.gif */
     if (isset($arFile["del"]) && $arFile["del"] != '') {
         CFile::DoDelete($arFile["old_file"]);
         if ($strFileName == '') {
             return "NULL";
         }
     }
     if ($arFile["name"] == '') {
         if (isset($arFile["description"]) && intval($arFile["old_file"]) > 0) {
             CFile::UpdateDesc($arFile["old_file"], $arFile["description"]);
         }
         return false;
     }
     if (isset($arFile["content"])) {
         if (!isset($arFile["size"])) {
             $arFile["size"] = CUtil::BinStrlen($arFile["content"]);
         }
     } else {
         try {
             $file = new IO\File($arFile["tmp_name"]);
             $arFile["size"] = $file->getSize();
         } catch (IO\IoException $e) {
             $arFile["size"] = 0;
         }
     }
     $arFile["ORIGINAL_NAME"] = $strFileName;
     //translit, replace unsafe chars, etc.
     $strFileName = self::transformName($strFileName, $bForceMD5, $bSkipExt);
     //transformed name must be valid, check disk quota, etc.
     if (self::validateFile($strFileName, $arFile) !== "") {
         return false;
     }
     if ($arFile["type"] == "image/pjpeg" || $arFile["type"] == "image/jpg") {
         $arFile["type"] = "image/jpeg";
     }
     $bExternalStorage = false;
     foreach (GetModuleEvents("main", "OnFileSave", true) as $arEvent) {
         if (ExecuteModuleEventEx($arEvent, array(&$arFile, $strFileName, $strSavePath, $bForceMD5, $bSkipExt))) {
             $bExternalStorage = true;
             break;
         }
     }
     if (!$bExternalStorage) {
         $upload_dir = COption::GetOptionString("main", "upload_dir", "upload");
         $io = CBXVirtualIo::GetInstance();
         if ($bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N") == "Y") {
             $dir_add = '';
             $i = 0;
             while (true) {
                 $dir_add = substr(md5(uniqid("", true)), 0, 3);
                 if (!$io->FileExists($_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/" . $dir_add . "/" . $strFileName)) {
                     break;
                 }
                 if ($i >= 25) {
                     $j = 0;
                     while (true) {
                         $dir_add = substr(md5(mt_rand()), 0, 3) . "/" . substr(md5(mt_rand()), 0, 3);
                         if (!$io->FileExists($_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/" . $dir_add . "/" . $strFileName)) {
                             break;
                         }
                         if ($j >= 25) {
                             $dir_add = substr(md5(mt_rand()), 0, 3) . "/" . md5(mt_rand());
                             break;
                         }
                         $j++;
                     }
                     break;
                 }
                 $i++;
             }
             if (substr($strSavePath, -1, 1) != "/") {
                 $strSavePath .= "/" . $dir_add;
             } else {
                 $strSavePath .= $dir_add . "/";
             }
         } else {
             $strFileExt = $bSkipExt == true || ($ext = GetFileExtension($strFileName)) == '' ? '' : "." . $ext;
             while (true) {
                 if (substr($strSavePath, -1, 1) != "/") {
                     $strSavePath .= "/" . substr($strFileName, 0, 3);
                 } else {
                     $strSavePath .= substr($strFileName, 0, 3) . "/";
                 }
                 if (!$io->FileExists($_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/" . $strFileName)) {
                     break;
                 }
                 //try the new name
                 $strFileName = md5(uniqid("", true)) . $strFileExt;
             }
         }
         $arFile["SUBDIR"] = $strSavePath;
         $arFile["FILE_NAME"] = $strFileName;
         $strDirName = $_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/";
         $strDbFileNameX = $strDirName . $strFileName;
         $strPhysicalFileNameX = $io->GetPhysicalName($strDbFileNameX);
         CheckDirPath($strDirName);
         if (is_set($arFile, "content")) {
             $f = fopen($strPhysicalFileNameX, "ab");
             if (!$f) {
                 return false;
             }
             if (fwrite($f, $arFile["content"]) === false) {
                 return false;
             }
             fclose($f);
         } elseif (!copy($arFile["tmp_name"], $strPhysicalFileNameX) && !move_uploaded_file($arFile["tmp_name"], $strPhysicalFileNameX)) {
             CFile::DoDelete($arFile["old_file"]);
             return false;
         }
         if (isset($arFile["old_file"])) {
             CFile::DoDelete($arFile["old_file"]);
         }
         @chmod($strPhysicalFileNameX, BX_FILE_PERMISSIONS);
         //flash is not an image
         $flashEnabled = !CFile::IsImage($arFile["ORIGINAL_NAME"], $arFile["type"]);
         $imgArray = CFile::GetImageSize($strDbFileNameX, false, $flashEnabled);
         if (is_array($imgArray)) {
             $arFile["WIDTH"] = $imgArray[0];
             $arFile["HEIGHT"] = $imgArray[1];
             if ($imgArray[2] == IMAGETYPE_JPEG) {
                 $exifData = CFile::ExtractImageExif($io->GetPhysicalName($strDbFileNameX));
                 if ($exifData && isset($exifData['Orientation'])) {
                     //swap width and height
                     if ($exifData['Orientation'] >= 5 && $exifData['Orientation'] <= 8) {
                         $arFile["WIDTH"] = $imgArray[1];
                         $arFile["HEIGHT"] = $imgArray[0];
                     }
                     $properlyOriented = CFile::ImageHandleOrientation($exifData['Orientation'], $io->GetPhysicalName($strDbFileNameX));
                     if ($properlyOriented) {
                         $jpgQuality = intval(COption::GetOptionString('main', 'image_resize_quality', '95'));
                         if ($jpgQuality <= 0 || $jpgQuality > 100) {
                             $jpgQuality = 95;
                         }
                         imagejpeg($properlyOriented, $io->GetPhysicalName($strDbFileNameX), $jpgQuality);
                     }
                 }
             }
         } else {
             $arFile["WIDTH"] = 0;
             $arFile["HEIGHT"] = 0;
         }
     }
     if ($arFile["WIDTH"] == 0 || $arFile["HEIGHT"] == 0) {
         //mock image because we got false from CFile::GetImageSize()
         if (strpos($arFile["type"], "image/") === 0) {
             $arFile["type"] = "application/octet-stream";
         }
     }
     if ($arFile["type"] == '' || !is_string($arFile["type"])) {
         $arFile["type"] = "application/octet-stream";
     }
     /****************************** QUOTA ******************************/
     if (COption::GetOptionInt("main", "disk_space") > 0) {
         CDiskQuota::updateDiskQuota("file", $arFile["size"], "insert");
     }
     /****************************** QUOTA ******************************/
     $NEW_IMAGE_ID = CFile::DoInsert(array("HEIGHT" => $arFile["HEIGHT"], "WIDTH" => $arFile["WIDTH"], "FILE_SIZE" => $arFile["size"], "CONTENT_TYPE" => $arFile["type"], "SUBDIR" => $arFile["SUBDIR"], "FILE_NAME" => $arFile["FILE_NAME"], "MODULE_ID" => $arFile["MODULE_ID"], "ORIGINAL_NAME" => $arFile["ORIGINAL_NAME"], "DESCRIPTION" => isset($arFile["description"]) ? $arFile["description"] : '', "HANDLER_ID" => isset($arFile["HANDLER_ID"]) ? $arFile["HANDLER_ID"] : '', "EXTERNAL_ID" => isset($arFile["external_id"]) ? $arFile["external_id"] : md5(mt_rand())));
     CFile::CleanCache($NEW_IMAGE_ID);
     return $NEW_IMAGE_ID;
 }
コード例 #15
0
ファイル: resize.php プロジェクト: royalswe/yas26
function resize($thumb, $size = null, $source = "game")
{
    $imageMethod = "GD";
    global $setting;
    switch ($source) {
        case 'download':
            $sourcePath = $setting['sitepath'] . '/ourgames/img/';
            break;
        case 'avatar':
            if (strstr($thumb, 'useruploads')) {
                $sourcePath = $setting['sitepath'] . '/avatars/useruploads/';
            } else {
                $sourcePath = $setting['sitepath'] . '/avatars/';
            }
            break;
        default:
            $sourcePath = $setting['sitepath'] . '/img/';
            break;
    }
    $cachePath = $setting['sitepath'] . '/cache/img/';
    $ext = GetFileExtension($thumb);
    $filename = GetFileName($thumb) . '.' . $ext;
    $thumbPath = $sourcePath . $filename;
    $imagickPath = '/convert/convert';
    if (!file_exists($thumbPath)) {
        return $setting['siteurl'] . 'templates/' . $setting['theme'] . '/skins/' . $setting['skin'] . '/images/nopic150.jpg';
    }
    $newthumbname = md5_file($thumbPath);
    $ext = GetFileExtension($thumbPath);
    if (isset($size['w'])) {
        $w = $size['w'];
    }
    if (isset($size['h'])) {
        $h = $size['h'];
    }
    if (!empty($w) and !empty($h)) {
        $newthumbpath = $cachePath . $newthumbname . '_w' . $w . '_h' . $h . '.' . $ext;
    } elseif (!empty($w)) {
        $newthumbpath = $cachePath . $newthumbname . '_w' . $w . '.' . $ext;
    } elseif (!empty($h)) {
        $newthumbpath = $cachePath . $newthumbname . '_h' . $h . '.' . $ext;
    } else {
        return false;
    }
    if (file_exists($newthumbpath)) {
        return str_replace($setting['sitepath'] . '/', $setting['siteurl'], $newthumbpath);
    }
    switch ($imageMethod) {
        case 'IM':
            list($width, $height) = getimagesize($thumbPath);
            $rw = $width / $w;
            $rh = $height / $h;
            if ($rw > $rh) {
                $nw = round($width / $rh);
                $resize = $nw;
            }
            if ($rh > $rw) {
                $nh = round($height / $rw);
                $resize = "x" . $nh;
            } else {
                $resize = $w . "x" . $h;
            }
            $cmd = $setting['sitepath'] . $imagickPath . " " . $thumbPath . " -resize " . $resize . " -size " . $w . "x" . $h . " xc:transparent +swap -gravity center -composite -quality 90 " . $newthumbpath;
            $c = exec($cmd, $data, $ret);
            if ($ret != 0) {
                return $thumb;
            } else {
                return str_replace($setting['sitepath'] . '/', $setting['siteurl'], $newthumbpath);
            }
            break;
        case 'GD':
            include_once "resizer.php";
            $image = new SimpleImage();
            if (!$image) {
                return $thumbPath;
            }
            $image->load($thumbPath);
            $image->resize($w, $h);
            $image->save($newthumbpath);
            return str_replace($setting['sitepath'] . '/', $setting['siteurl'], $newthumbpath);
            break;
        default:
            return $thumbPath;
            break;
    }
}
コード例 #16
0
        $UploadError = false;
        $pathto = '';
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $file = $_FILES['watermark_img'];
            $checkImgMsg = CFile::CheckImageFile($file);
            if ($file['error'] != 0) {
                $UploadError = "[IU_WM01] " . GetMessage("P_WM_IMG_ERROR01");
            } elseif (strlen($checkImgMsg) > 0 || $checkImgMsg === "") {
                $UploadError = "[IU_WM02] " . ($checkImg === "" ? GetMessage("P_WM_IMG_ERROR02") : $checkImg);
            } else {
                $imgArray = CFile::GetImageSize($file["tmp_name"]);
                if (is_array($imgArray)) {
                    $width = $imgArray[0];
                    $height = $imgArray[1];
                }
                $pathto = CTempFile::GetDirectoryName(1) . '/' . "watermark_" . GetFileName($file["name"]);
                CheckDirPath($pathto);
                $pathtoRel = substr($pathto, strlen($_SERVER["DOCUMENT_ROOT"]));
                if (!move_uploaded_file($file["tmp_name"], $pathto)) {
                    $UploadError = "[IU_WM03] " . GetMessage("P_WM_IMG_ERROR03");
                }
            }
        }
        $APPLICATION->RestartBuffer();
        ?>
			<script>
			<?php 
        if ($UploadError === false && $pathto != '') {
            ?>
				top.bxiu_wm_img_res = {path: '<?php 
            echo CUtil::JSEscape($pathtoRel);
コード例 #17
0
ファイル: iblock.php プロジェクト: mrdeadmouse/u136006
 function COPY($options, $drop = false)
 {
     $statusSymlinkDelete = false;
     $arCacheCleanID = array();
     if (!$this->CheckWebRights("", array("action" => "create"), true)) {
         return $this->ThrowAccessDenied(__LINE__);
     } elseif ($_SERVER['REQUEST_METHOD'] == "MOVE" && !empty($_SERVER["CONTENT_LENGTH"])) {
         return "415 Unsupported media type";
     } elseif ($options["path"] == $options["dest_url"]) {
         return "204 No Content";
     } elseif (empty($options["dest_url"])) {
         return $this->ThrowError("502 bad gateway", "EMPTY_DESTINATION_URL", GetMessage("WD_FILE_ERROR2"), __LINE__);
     }
     $destUrl = $options["dest_url"];
     if (substr($destUrl, -1) === "/") {
         $destUrl = substr($destUrl, 0, -1);
     }
     $destName = GetFileName($destUrl);
     if ($destUrl !== "" && $destName !== "") {
         $destParentDir = GetDirPath($destUrl);
         $destParentDir = count($destParentDir) > 0 ? $destParentDir : "/";
         $o = array("path" => $destParentDir, "depth" => 1);
         $result = $this->PROPFIND($o, $files, array("COLUMNS" => array("ID", "NAME"), "return" => "array"));
         if (!empty($result["RESULT"])) {
             foreach ($result["RESULT"] as $key => $res) {
                 if ($res["NAME"] === $destName) {
                     if (strlen(GetFileExtension($destName)) > 0) {
                         return $this->ThrowError("400 Bad Request", "FOLDER_IS_EXISTS", str_replace("#FILE#", '"' . $res["NAME"] . '"', GetMessage("WD_FILE_ERROR8")), __LINE__);
                     } elseif (isset($options['section_id']) && $res['ID'] == $options['section_id']) {
                         return $this->ThrowError("400 Bad Request", "SAME_FOLDER_IS_EXISTS", str_replace("#FOLDER#", '"' . $res["NAME"] . '"', GetMessage("WD_FILE_ERROR5")), __LINE__);
                     } else {
                         return $this->ThrowError("400 Bad Request", "FOLDER_IS_EXISTS", str_replace("#FOLDER#", '"' . $res["NAME"] . '"', GetMessage("WD_FILE_ERROR5")), __LINE__);
                     }
                 }
             }
         }
     }
     //$this->CheckUniqueName($basename, $section_id, &$res)
     //GetFileName()
     $arFrom = array();
     $arTo = array();
     $is_dir = false;
     ////////////// CHECK FROM
     $this->IsDir($options);
     $arFrom = $this->arParams;
     if ($this->arParams["not_found"]) {
         return $this->ThrowError("404 Not Found", "DESTINATION_FILE_OR_FOLDER_IS_NOT_FOUND", GetMessage("WD_FILE_ERROR3"), __LINE__);
     } elseif ($this->arParams["is_dir"] === true) {
         $is_dir = true;
         if ($_SERVER['REQUEST_METHOD'] == "MOVE" && $options["depth"] != "infinity") {
             return "400 Bad request";
         } elseif ($this->check_creator) {
             return $this->ThrowAccessDenied("USER_IS_NOT_CREATOR", __LINE__);
         } elseif (empty($options["path"])) {
             $options["path"] = $this->_get_path($arFrom["item_id"], false);
         }
         $res = $this->_udecode($options["dest_url"]);
         $res2 = str_replace("//", "/", $res . "/");
         $res1 = str_replace("//", "/", $options["path"] . "/");
         if ($res1 === $res2) {
             return "204 No Content";
         } elseif (strtolower(substr($res2, 0, strlen($res1))) == strtolower($res1) && strlen($res1) != strlen($res2)) {
             return $this->ThrowError("400 Bad Request", "SECTION_IS_NOT_UPDATED", GetMessage("WD_FILE_ERROR100"), __LINE__);
         }
     } else {
         // found and is_file
     }
     if (!empty($arFrom['parent_id'])) {
         list($contextType, $contextEntityId) = $this->getContextData();
         $sectionData = $this->getSectionDataForLinkAnalyze($arFrom['parent_id']);
         if (CWebDavSymlinkHelper::isLink($contextType, $contextEntityId, $sectionData)) {
             $arFrom['is_symlink'] = true;
             $arFrom['symlink_section_data'] = $sectionData;
             $arFrom['symlink_section_data_link'] = CWebDavSymlinkHelper::getLinkData($contextType, $contextEntityId, $sectionData);
         }
     }
     ////////////// CHECK TO
     $arToParams = array("path" => $options['dest_url']);
     if (strpos($options['dest_url'], '.Trash') !== false) {
         $arToParams['check_permissions'] = false;
     }
     $this->IsDir($arToParams);
     $arTo = $this->arParams;
     if (!empty($arTo['parent_id'])) {
         list($contextType, $contextEntityId) = $this->getContextData();
         $sectionData = $this->getSectionDataForLinkAnalyze($arTo['parent_id']);
         if (CWebDavSymlinkHelper::isLink($contextType, $contextEntityId, $sectionData)) {
             $arTo['is_symlink'] = true;
             $arTo['symlink_section_data'] = $sectionData;
             $arTo['symlink_section_data_link'] = CWebDavSymlinkHelper::getLinkData($contextType, $contextEntityId, $sectionData);
         }
     }
     if ($this->arParams["not_found"] == true) {
         if ($this->e_rights && strpos($options['dest_url'], '.Trash') === false && !$this->CheckWebRights("COPY", array('action' => $drop ? 'move' : 'copy', 'from' => array($arFrom), 'to' => array($arTo)), false)) {
             return $this->ThrowAccessDenied(__LINE__);
         }
         //$arTo = false;
     } elseif ($arFrom["is_dir"] === true && $arTo["is_file"] === true || $arFrom["is_file"] === true && $arTo["is_dir"] === true) {
         return $this->ThrowError("400 Bad Request", "FOLDER_IS_EXISTS", str_replace("#FOLDER#", $this->arParams["item_id"], GetMessage("WD_FILE_ERROR5")), __LINE__);
     } elseif (!$this->CheckWebRights("COPY", array('action' => $drop ? 'move' : 'copy', 'from' => array($arFrom), 'to' => array($arTo)), false)) {
         return $this->ThrowAccessDenied(__LINE__);
     } elseif ($arFrom["item_id"] == $arTo["item_id"] && $arFrom['basename'] == $arTo['basename']) {
         // else - trying to change case in name
         return "204 No Content";
     } elseif ($arFrom["element_array"]["WF_PARENT_ELEMENT_ID"] > 0) {
         unset($arTo["item_id"]);
     } elseif (isset($options['rename']) && $options['rename'] === true) {
         // fix fast delete to trash from different folders with the same file name
         $nameSuffix = 1;
         do {
             $tmpName = $options["dest_url"] . " (" . $nameSuffix++ . ")";
             $this->IsDir(array("path" => $tmpName));
             $arTo = $this->arParams;
         } while ($arTo["not_found"] !== true);
         $options['dest_url'] = $tmpName;
     } elseif (!$options["overwrite"]) {
         return $this->ThrowError('412 Precondition failed', "FILE_OR_FOLDER_ALREADY_EXISTS", GetMessage("WD_FILE_ERROR4"), __LINE__);
     } elseif (!$this->CheckName($arTo["basename"])) {
         return $this->ThrowError("400 bad request", "BAD_NAME", GetMessage("WD_FILE_ERROR101"), __LINE__);
     } elseif ($arTo["is_file"] && $this->check_creator && $arTo["element_array"]["CREATED_BY"] != $GLOBALS["USER"]->GetID()) {
         return $this->ThrowAccessDenied("USER_IS_NOT_CREATOR", __LINE__);
     }
     if ($this->workflow == 'workflow' && $arFrom["is_file"] && !CWorkflow::IsAdmin() && !$GLOBALS['USER']->CanDoOperation('webdav_change_settings')) {
         $bNeedCheckWfRights = false;
         if ($this->e_rights) {
             $arToParent = $this->GetObject(array('section_id' => $arTo['parent_id']));
             if ($arToParent['is_dir']) {
                 $bNeedCheckWfRights = !$this->GetPermission('SECTION', $arToParent['item_id'], 'element_edit_any_wf_status');
             }
         } else {
             $bNeedCheckWfRights = $this->permission < 'W';
         }
         if ($bNeedCheckWfRights && CIBlockElement::WF_GetStatusPermission($arFrom["element_array"]["WF_STATUS_ID"]) != 2) {
             return $this->ThrowError("400 bad request", "BAD_WF_RIGHTS", GetMessage("WD_FILE_ERROR110"), __LINE__);
         }
     }
     if ($arTo['parent_id'] == $this->GetMetaID('TRASH')) {
         $arCheckTrashElement = $arFrom[$arFrom['is_dir'] ? 'dir_array' : 'element_array'];
         if ($this->_parse_webdav_info($arCheckTrashElement) && !isset($arCheckTrashElement['PROPS']['BX:']['UNDELETE'])) {
             return $this->ThrowAccessDenied("BAD_NAME", __LINE__);
         }
     }
     if ($arFrom["is_file"]) {
         $el = new CIBlockElement();
         if ($arTo["item_id"] && $arTo['item_id'] !== $arFrom['item_id']) {
             $this->_ib_elm_delete($arTo['item_id']);
             // TODO: need to check permissions ?
         }
         //drop == true if this action is @move@
         //is file
         if ($drop) {
             $actionRename = $arFrom['parent_id'] == $arTo['parent_id'];
             $arFields = array("NAME" => $arTo["basename"], "MODIFIED_BY" => $GLOBALS['USER']->GetID(), "IBLOCK_SECTION_ID" => $arTo["parent_id"]);
             $this->_onEvent($arFrom['parent_id'] != $arTo['parent_id'] ? 'Move' : 'Rename', $arFrom['element_id'], 'FILE', array('TO' => $arFrom['parent_id'] != $arTo['parent_id'] ? $arTo["parent_id"] : $arTo["basename"]));
             //from symlink move. Not rename!!!!
             if (!$actionRename && (!empty($arFrom['is_symlink']) || !empty($arTo['is_symlink']))) {
                 $targetIblockId = $this->IBLOCK_ID;
                 if (!empty($arTo['is_symlink'])) {
                     $targetIblockId = $arTo['symlink_section_data']['IBLOCK_ID'];
                 }
                 //move and don't delete item
                 if (self::_move_from_iblock_to_iblock($arFrom['item_id'], $targetIblockId, $arTo['parent_id'], false, true)) {
                     $statusSymlinkDelete = $this->DELETE(array("element_id" => $arFrom['item_id']));
                 }
             } else {
                 if ($this->workflow == 'workflow') {
                     if ($arTo["parent_id"] != $arFrom["parent_id"]) {
                         $arFields["WF_COMMENTS"] = GetMessage("WD_FILE_IS_MOVED");
                         $el->SetElementSection($arFrom["item_id"], $arTo["parent_id"]);
                         // TODO: need to check permissions ???
                     } else {
                         $arFields["WF_COMMENTS"] = GetMessage("WD_FILE_IS_RENAMED");
                     }
                     if ($arTo["parent_id"] != $arFrom["parent_id"] && $arTo["basename"] != $arFrom["element_name"]) {
                         $arFields["WF_COMMENTS"] = GetMessage("WD_FILE_IS_MOVED_AND_RENAMED");
                     }
                 }
                 if ($this->workflow == 'bizproc' || $this->workflow == 'bizproc_limited') {
                     $this->AddDocumentToHistory($arFrom['item_id'], $arFrom['element_name']);
                 }
                 $el->Update($arFrom["item_id"], $arFields, $this->workflow == 'workflow', true, false, false);
                 // TODO: need to check permissions ???
                 $arCacheCleanID[] = 'element' . $arFrom["item_id"];
                 if ($this->workflow == 'bizproc' || $this->workflow == 'bizproc_limited') {
                     $db_res2 = CIBlockElement::GetList(array(), array("WF_PARENT_ELEMENT_ID" => $arFrom["item_id"], "SHOW_HISTORY" => "Y"), false, false, array("ID"));
                     if ($db_res2 && ($res2 = $db_res2->Fetch())) {
                         do {
                             $res = $el->Update($res2["ID"], array("IBLOCK_SECTION_ID" => $arFields["IBLOCK_SECTION_ID"]), false, true, false, false);
                             $arCacheCleanID[] = 'element' . $res2["ID"];
                         } while ($res2 = $db_res2->Fetch());
                     }
                 }
             }
         } else {
             //from symlink copy
             if (!empty($arFrom['is_symlink']) || !empty($arTo['is_symlink'])) {
                 $targetIblockId = $this->IBLOCK_ID;
                 if (!empty($arTo['is_symlink'])) {
                     $targetIblockId = $arTo['symlink_section_data']['IBLOCK_ID'];
                 }
                 //move and don't delete item
                 if (!self::_move_from_iblock_to_iblock($arFrom['item_id'], $targetIblockId, $arTo['parent_id'], false, true)) {
                     return '403 Forbidden';
                 }
             } else {
                 $options = array('path' => $options["dest_url"], 'content_length' => $arFrom["file_array"]['FILE_SIZE'], 'content_type' => $arFrom["file_array"]['CONTENT_TYPE']);
                 $stat = $this->PUT($options);
                 if ($stat === false) {
                     return '403 Forbidden';
                 } elseif (is_resource($stat) && get_resource_type($stat) == 'stream') {
                     fclose($stat);
                     $arTmpFile = CFile::MakeFileArray($arFrom['element_array']['PROPERTY_FILE_VALUE']);
                     // since CopyDirFiles doesn't support clouds
                     if (!(is_array($arTmpFile) && is_set($arTmpFile, 'tmp_name'))) {
                         return false;
                     }
                     CopyDirFiles($arTmpFile['tmp_name'], $options["TMP_FILE"]);
                     clearstatcache();
                     $options['USER_FIELDS'] = $this->GetUfFieldsSimpleArray($arFrom['item_id']);
                     if (!$this->put_commit($options)) {
                         return $this->ThrowError('409 Conflict', "BAD_BP_PERMISSIONS", GetMessage("WD_FILE_ERROR110"), __LINE__);
                     }
                 }
             }
         }
         $this->_onEvent(($arFrom['parent_id'] != $arTo['parent_id'] ? 'Move' : 'Rename') . 'Finished', $arFrom['element_id'], 'FILE');
     } else {
         $se = new CIBlockSection();
         $actionRename = $arFrom['parent_id'] == $arTo['parent_id'];
         $actionWithSymlink = !empty($arFrom['is_symlink']) || !empty($arTo['is_symlink']);
         $actionMoveInSymlink = false;
         if ($actionWithSymlink) {
             $actionMoveInSymlink = $arFrom['symlink_section_data_link'] == $arTo['symlink_section_data_link'];
         }
         //drop == true if this action is @move@
         //not symlink and move! but if action rename in symlink - run this code block
         if (!$actionWithSymlink && $drop || $actionWithSymlink && $actionRename || $actionMoveInSymlink) {
             $this->_onEvent($arFrom['parent_id'] != $arTo['parent_id'] ? 'Move' : 'Rename', $arFrom['item_id'], 'FOLDER', array('TO' => $arFrom['parent_id'] != $arTo['parent_id'] ? $arTo["parent_id"] : $arTo["basename"]));
             $GLOBALS['DB']->StartTransaction();
             if (isset($options['overwrite']) && $arTo['is_dir'] === true && $arTo['item_id'] !== $arFrom['item_id']) {
                 $se->Delete($arTo['item_id']);
             }
             $result = $se->Update($arFrom["item_id"], array("NAME" => $arTo["basename"], "IBLOCK_SECTION_ID" => $arTo["parent_id"]));
             // TODO: need to check permissions ???
             if ($result == false) {
                 $GLOBALS['DB']->Rollback();
                 return $this->ThrowError("409 Conflict", "SECTION_IS_NOT_UPDATED", $se->LAST_ERROR ? $se->LAST_ERROR : GetMessage("WD_FILE_ERROR102"), __LINE__);
             } else {
                 $arCacheCleanID[] = 'section' . $arFrom["item_id"];
                 $this->ClearCache("section");
                 $GLOBALS['DB']->Commit();
             }
         } else {
             if (isset($options['overwrite']) && $arTo['is_dir'] === true) {
                 $se->Delete($arTo['item_id']);
             }
             if ($arTo["item_id"] === false) {
                 $arPath = explode("/", $options["dest_url"]);
                 $this->IsDir(array('path' => "/" . implode("/", array_slice($arPath, 0, -1))));
                 if ($this->arParams["not_found"] === false) {
                     if ($this->arParams["item_id"] == 0) {
                         // root
                         $arTo["dir_array"] = array("LEFT_MARGIN" => 0, "RIGHT_MARGIN" => $this->INT_MAX);
                     }
                     if ($arTo["dir_array"]["LEFT_MARGIN"] - 1 < $arFrom["dir_array"]["LEFT_MARGIN"] && $arFrom["dir_array"]["RIGHT_MARGIN"] < $arTo["dir_array"]["RIGHT_MARGIN"] + 1) {
                         // If folder moved to upper folder
                     } elseif ($arTo["dir_array"]["RIGHT_MARGIN"] < $arFrom["dir_array"]["LEFT_MARGIN"] || $arFrom["dir_array"]["RIGHT_MARGIN"] < $arTo["dir_array"]["LEFT_MARGIN"]) {
                         // if folder moved to neighbourhood folder
                     } elseif ($arFrom["dir_array"]["LEFT_MARGIN"] - 1 <= $arTo["dir_array"]["LEFT_MARGIN"] && $arTo["dir_array"]["RIGHT_MARGIN"] <= $arFrom["dir_array"]["RIGHT_MARGIN"] + 1 || $arTo["dir_array"]["ID"] == $arFrom["dir_array"]["ID"]) {
                         return $this->ThrowError("400 Bad Request", "SECTION_IS_NOT_UPDATED", GetMessage("WD_FILE_ERROR100"), __LINE__);
                     }
                     if (!empty($arTo['is_symlink'])) {
                         $parentSectionId = $this->arParams["item_id"];
                         if ($this->arParams["item_id"] == $arTo['symlink_section_data_link']['ID']) {
                             $parentSectionId = $arTo['symlink_section_data_link'][self::UF_LINK_SECTION_ID];
                         }
                         $arTo["dir_array"]["ID"] = $se->Add(array("IBLOCK_ID" => $arTo['symlink_section_data']['IBLOCK_ID'], "IBLOCK_SECTION_ID" => $parentSectionId, "NAME" => end(array_slice($arPath, -1, 1))));
                         $arTo["dir_array"]['IBLOCK_ID'] = $arTo['symlink_section_data']['IBLOCK_ID'];
                     } else {
                         $arTo["dir_array"]["ID"] = $se->Add(array("IBLOCK_ID" => $this->IBLOCK_ID, "IBLOCK_SECTION_ID" => $this->arParams["item_id"], "NAME" => end(array_slice($arPath, -1, 1))));
                     }
                     if ($arTo["dir_array"]["ID"] === false) {
                         return $this->ThrowError("409 Conflict", "FOLDER_IS_NOT_MOVED", str_replace(array("#FOLDER#", "#TEXT_ERROR#"), array("/" . implode("/", $arPath), $se->LAST_ERROR), GetMessage("WD_FILE_ERROR103")), __LINE__);
                     } else {
                         $returnSection = $arTo["dir_array"]["ID"];
                         $this->_onEvent('Add', $returnSection, 'FOLDER');
                     }
                 }
             } else {
                 return $this->ThrowError("409 Conflict", "FOLDER_IS_NOT_MOVED", str_replace(array("#FOLDER#", "#TEXT_ERROR#"), array($options["dest_url"], $se->LAST_ERROR), GetMessage("WD_FILE_ERROR103")), __LINE__);
             }
             $arFrom["dir_array"]['is_symlink'] = !empty($arFrom['is_symlink']);
             $arFrom["dir_array"]['symlink_section_data'] = empty($arFrom['symlink_section_data']) ? array() : $arFrom['symlink_section_data'];
             $arTo["dir_array"]['is_symlink'] = !empty($arTo['is_symlink']);
             $arTo["dir_array"]['symlink_section_data'] = empty($arTo['symlink_section_data']) ? array() : $arTo['symlink_section_data'];
             $result = $this->copy_commit($arFrom["dir_array"], $arTo["dir_array"], $options, $drop);
             if ($result === true && $drop === true) {
                 if ($actionWithSymlink) {
                     $this::$lastActionMoveWithSymlink = true;
                     $this->DELETE(array("section_id" => $arFrom["item_id"]));
                 } else {
                     CIBlockSection::Delete($arFrom["item_id"]);
                 }
                 $this->ClearCache("section");
             } elseif (is_string($result) && strpos($result, "403") !== false) {
                 return $this->ThrowAccessDenied(__LINE__);
             }
         }
         if ($result !== true) {
             return $result;
         }
     }
     if ($arFrom['element_id']) {
         CWebDavDiskDispatcher::sendEventToOwners($arFrom['element_array'], null, 'copy');
     } elseif ($arFrom['is_dir']) {
         CWebDavDiskDispatcher::sendEventToOwners(null, $arFrom['dir_array'], 'copy');
     }
     $this->ClearCache($arCacheCleanID, 'local');
     if (isset($returnSection)) {
         $this->arParams["changed_section_id"] = $returnSection;
     }
     if ($statusSymlinkDelete !== false) {
         return $statusSymlinkDelete;
     }
     return $arTo["not_found"] ? "201 Created" : "204 No Content";
 }
コード例 #18
0
ファイル: ComunicoErrorBK.php プロジェクト: linuxman/uycodeka
                                $Archivo = extract_unit($vero, "No se pudo copiar el fichero", ": Acceso denegado");
                                $Archivo = str_replace('"', "", GetFileName($Archivo));
                                $Archivo = str_replace(':', "", $Archivo);
                                $messageAux .= "Se denegó el acceso al archivo " . $Archivo . " <b>esta siendo utilizado</b><br>";
                            } elseif (strpos($conta['message'], "No se ha encontrado la ruta de acceso de la red") !== false) {
                                $stopI = strpos($conta['message'], ": No se ha encontrado la ruta de acceso de la red");
                                $vero = substr($conta['message'], $startI, $stopI - 2);
                                $Archivo = extract_unit($vero, "No se pudo copiar el fichero", " No se ha encontrado la ruta de acceso de la red");
                                $Archivo = str_replace('"', "", GetFileName($Archivo));
                                $Archivo = str_replace(':', "", $Archivo);
                                $messageAux .= " Hay un problema de red o el equipo de respaldo está apagado. Archivo: " . $Archivo . "<br>";
                            } elseif (strpos($conta['message'], "Se anuló la solicitud") !== false) {
                                $stopI = strpos($conta['message'], ": Se anuló la solicitud");
                                $vero = substr($conta['message'], $startI, $stopI - 2);
                                $Archivo = extract_unit($vero, "No se pudo copiar el fichero", ": Se anuló la solicitud");
                                $Archivo = str_replace('"', "", GetFileName($Archivo));
                                $Archivo = str_replace(':', "", $Archivo);
                                $messageAux .= " <b>El nombre del archivo</b> " . $Archivo . " no es válido o la profundida de directorio\n\t\t\t\t\t\t\texcede el máximo permitido.<br>";
                            }
                        } elseif (strpos($conta['message'], "no existe o no pudo ser accedida") !== false) {
                            $messageAux .= " Cobian backup se está ejecutando desde un usuario sin prermisos administrativos.<br>";
                        }
                        $BGCOLOR = "#FFFFFF";
                        $COLOR = "#000000";
                        $message .= '<TR>
		<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" BGCOLOR="' . $BGCOLOR . '" HEIGHT="17" ALIGN="CENTER" SDVAL="41629" SDNUM="3082;0;DD/MM/AA">
		<FONT COLOR="' . $COLOR . '">' . implota($conta['fecha']) . '</FONT></TD>
		<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" BGCOLOR="' . $BGCOLOR . '" ALIGN="CENTER" VALIGN=MIDDLE SDNUM="3082;0;@">
		<FONT COLOR="' . $COLOR . '">' . $alias . '</FONT></TD>
		<TD STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" BGCOLOR="' . $BGCOLOR . '" ALIGN="LEFT" SDNUM="3082;0;@">
		<FONT COLOR="' . $COLOR . '">&nbsp;' . $conta["tarea"] . '</FONT></TD>
コード例 #19
0
    public static function Request($action, $site)
    {
        global $USER;
        if (!$USER->CanDoOperation('fileman_view_file_structure')) {
            return;
        }
        $io = CBXVirtualIo::GetInstance();
        CUtil::JSPostUnescape();
        switch ($action) {
            case "count":
            case "search":
            case "replace":
                $oSearch = new CFilemanSearch();
                $oSearch->Init(array('lastPath' => isset($_POST['last_path']) ? $_POST['last_path'] : false, 'bCount' => $action == "count", 'bReplace' => $action == "replace", "fileName" => trim($_POST['file']), "phrase" => trim($_POST['phrase']), "replacePhrase" => trim($_POST['replace_phrase']), "dir" => CFilemanUtils::NormalizePath($_POST['dir']), "bSubdir" => $_POST['subdir'], "dateFrom" => $_POST['date_from'], "dateTo" => $_POST['date_to'], "sizeFrom" => intVal($_POST['size_from']), "sizeTo" => intVal($_POST['size_to']), "entire" => $_POST['entire'], "bCaseSens" => $_POST['case_sens'], "bDirsToo" => $_POST['dirs_too'], "ssess" => $_POST['ssess'], "bInResult" => $_POST['in_result'], "site" => CFileMan::__CheckSite($_GET['fu_site'])));
                CFileMan::SaveLastPath(CFilemanUtils::NormalizePath($_POST['dir']));
                break;
            case "clean_old":
                CFilemanSearch::CleanOldSearchResult();
                break;
            case "search_save_config":
                CFilemanSearch::SaveConfig(array("advMode" => (bool) $_POST['adv_mode'], "bSubdir" => (bool) $_POST['subdir'], "entire" => (bool) $_POST['entire'], "bCaseSens" => (bool) $_POST['case_sens'], "bDirsToo" => (bool) $_POST['dirs_too']));
                break;
            case "copy_save_config":
                CFilemanCopy::SaveConfig(array("advMode" => (bool) $_POST['adv_mode'], "caseOption" => $_POST['case_option']));
                break;
            case "copy":
            case "move":
                $oCopy = new CFilemanCopy();
                $oCopy->Init(array("bCopy" => $action == "copy", "caseOption" => $_POST['case_option'], "arFiles" => $_POST['files'], "copyTo" => $_POST['copy_to'], "createCopyTo" => $_POST['create_copy_to'] == "Y", "userCaseAnswer" => isset($_POST['uc_answer']) ? $_POST['uc_answer'] : false, "userCaseToAll" => isset($_POST['uc_to_all']) ? $_POST['uc_to_all'] : false, "userCaseLastPath" => isset($_POST['uc_last_path']) ? $_POST['uc_last_path'] : false, "bSearch" => $_POST['search'] == "Y", "ssess" => $_POST['ssess'], "siteTo" => CFileMan::__CheckSite($_GET['fu_site'])));
                CFileMan::SaveLastPath($_POST['copy_to']);
                break;
            case "get_last_pathes":
                ?>
				<script>window.bx_last_pathes = <?php 
                echo CUtil::PhpToJSObject(CFilemanUtils::GetLastPathes());
                ?>
;</script>
				<?php 
                break;
            case "pack":
                if (isset($_POST["startFile"])) {
                    $startFile = trim($_POST["startFile"]);
                }
                if (isset($_POST["quickPath"])) {
                    $quickPath = trim($_POST["quickPath"]);
                }
                if (isset($_POST["packTo"])) {
                    if (substr($_POST["packTo"], 0, 1) == "/") {
                        $pack_to = $_POST["packTo"];
                    } else {
                        $pack_to = "/" . $_POST["packTo"];
                    }
                }
                $siteTo = CFileMan::__CheckSite($_POST['siteTo']);
                $docRootTo = CSite::GetSiteDocRoot($siteTo) ? CSite::GetSiteDocRoot($siteTo) : '';
                $siteFrom = CFileMan::__CheckSite($site);
                $docRootFrom = CSite::GetSiteDocRoot($siteFrom);
                if (!$USER->IsAdmin()) {
                    $pack_to = RemoveScriptExtension($pack_to);
                }
                //check writing permissions
                if (!$USER->CanDoFileOperation('fm_create_new_file', array($siteTo, $pack_to))) {
                    ?>
					<script>
						window.BXFM_archivePermsError = true;
					</script>
					<?php 
                    return;
                }
                if (IsFileUnsafe($docRootTo . $pack_to) || CFileMan::CheckFileName(GetFileName($pack_to)) !== true) {
                    ?>
					<script>
						window.BXFM_archiveFNameError = true;
					</script>
					<?php 
                    return;
                }
                //ask if the file already exists
                if (file_exists($io->GetPhysicalName($docRootTo . $pack_to))) {
                    if (empty($startFile)) {
                        if ($_POST["bPackReplace"] != "replace") {
                            ?>
							<script>
								window.BXFM_archiveExists = {
									fileOld:
									{
										name: "<?php 
                            echo CUtil::JSEscape(basename($pack_to));
                            ?>
",
										path: "<?php 
                            echo CUtil::JSEscape($pack_to);
                            ?>
",
										site: "<?php 
                            echo CUtil::JSEscape($siteTo);
                            ?>
",
										size: "<?php 
                            echo CFile::FormatSize(filesize($io->GetPhysicalName($docRootTo . $pack_to)));
                            ?>
",
										date: "<?php 
                            echo date(CDatabase::DateFormatToPHP(CLang::GetDateFormat('FULL')), filemtime($io->GetPhysicalName($docRootTo . $pack_to)) + CTimeZone::GetOffset());
                            ?>
"
									}
								};
							</script>
							<?php 
                            return;
                        }
                    }
                }
                $packarc = CBXArchive::GetArchive($docRootTo . $pack_to, trim($_POST['arcType']));
                if ($packarc instanceof IBXArchive) {
                    //this set of options is common for every archive type
                    $packarc->SetOptions(array("COMPRESS" => true, "STEP_TIME" => COption::GetOptionString("fileman", "archive_step_time", 30), "ADD_PATH" => false, "REMOVE_PATH" => $docRootFrom . $quickPath, "CHECK_PERMISSIONS" => $USER->IsAdmin() ? false : true));
                    $arPackFiles = array();
                    foreach ($_POST["files"] as $path2file) {
                        $arPackFiles[] = $docRootFrom . $path2file['path'];
                    }
                    @set_time_limit(0);
                    $pRes = $packarc->Pack($arPackFiles, $startFile);
                    switch ($pRes) {
                        case IBXArchive::StatusContinue:
                            ?>
							<script>
							window.fmPackTimeout = true;
							window.fmPackLastFile = '<?php 
                            echo CUtil::JSEscape($packarc->GetStartFile());
                            ?>
';
							</script>
						<?php 
                            break;
                        case IBXArchive::StatusSuccess:
                            ?>
							<script>
							window.fmPackTimeout = false;
							window.fmPackLastFile = '';
							window.fmPackSuccess = true;
							</script>
						<?php 
                            break;
                        case IBXArchive::StatusError:
                            $arErrors = $packarc->GetErrors();
                            ?>
							<script>
							window.fmPackTimeout = false;
							window.fmPackSuccess = false;
							window.fmPackErrors = <?php 
                            echo CUtil::PhpToJSObject($arErrors);
                            ?>
;
							</script>
						<?php 
                            break;
                    }
                } else {
                    ?>
					<script>
					window.fmPackSuccess = false;
					window.fmPackErrors = <?php 
                    echo CUtil::PhpToJsObject(GetMessage("FM_UTIL_ARC_ERROR"));
                    ?>
;
					</script>
					<?php 
                }
                break;
            case "unpack":
                global $USER;
                if (isset($_POST["packTo"])) {
                    if (substr($_POST["packTo"], 0, 1) == "/") {
                        $pack_to = $_POST["packTo"];
                    } else {
                        $pack_to = "/" . $_POST["packTo"];
                    }
                }
                $siteFrom = CFileMan::__CheckSite($_GET['site']);
                $siteTo = CFileMan::__CheckSite($_POST['siteTo']);
                $docRootFrom = CSite::GetSiteDocRoot($siteFrom);
                $docRootTo = CSite::GetSiteDocRoot($siteTo);
                if (!($USER->CanDoFileOperation('fm_create_new_file', array($siteTo, $_POST["packTo"])) || $USER->CanDoFileOperation('fm_create_new_folder', array($siteTo, $_POST["packTo"])))) {
                    ?>
					<script>
						window.BXFM_archivePermsError = true;
					</script>
					<?php 
                    return;
                }
                $bReplaceFiles = $_POST["case_option"] == "replace" ? true : false;
                $arc = CBXArchive::GetArchive($docRootFrom . $_POST["files"][0]);
                if ($arc instanceof IBXArchive) {
                    global $USER;
                    $arc->SetOptions(array("REMOVE_PATH" => $docRootFrom, "UNPACK_REPLACE" => $bReplaceFiles, "CHECK_PERMISSIONS" => $USER->IsAdmin() ? false : true));
                    $uRes = $arc->Unpack($docRootTo . $pack_to);
                    if (!$uRes) {
                        $uErrors = $arc->GetErrors();
                        ?>
						<script>
						window.fmUnpackSuccess = false;
						window.fmUnpackErrors = <?php 
                        echo CUtil::PhpToJSObject($uErrors);
                        ?>
						</script>
					<?php 
                    } else {
                        ?>
						<script>
						window.fmUnpackSuccess = true;
						</script>
					<?php 
                    }
                } else {
                    ?>
					<script>
					window.fmUnpackSuccess = false;
					window.fmUnpackErrors = <?php 
                    echo CUtil::PhpToJsObject(GetMessage("FM_UTIL_ARC_ERROR"));
                    ?>
;
					</script>
					<?php 
                }
                break;
        }
    }
コード例 #20
0
ファイル: file.php プロジェクト: k-kalashnikov/geekcon_new
 function SaveFile($arFile, $strSavePath, $bForceMD5 = false, $bSkipExt = false)
 {
     $strFileName = GetFileName($arFile["name"]);
     /* filename.gif */
     if (isset($arFile["del"]) && $arFile["del"] != '') {
         CFile::DoDelete($arFile["old_file"]);
         if ($strFileName == '') {
             return "NULL";
         }
     }
     if ($arFile["name"] == '') {
         if (isset($arFile["description"]) && intval($arFile["old_file"]) > 0) {
             CFile::UpdateDesc($arFile["old_file"], $arFile["description"]);
         }
         return false;
     }
     if (array_key_exists("content", $arFile)) {
         if (!array_key_exists("size", $arFile)) {
             $arFile["size"] = CUtil::BinStrlen($arFile["content"]);
         }
     } else {
         $arFile["size"] = filesize($arFile["tmp_name"]);
     }
     $arFile["ORIGINAL_NAME"] = $strFileName;
     $io = CBXVirtualIo::GetInstance();
     if (self::validateFile($strFileName, $arFile, $bForceMD5) !== "") {
         return false;
     }
     $upload_dir = COption::GetOptionString("main", "upload_dir", "upload");
     if ($arFile["type"] == "image/pjpeg" || $arFile["type"] == "image/jpg") {
         $arFile["type"] = "image/jpeg";
     }
     //.jpe is not image type on many systems
     if (strtolower(GetFileExtension($strFileName)) == "jpe") {
         $strFileName = substr($strFileName, 0, -4) . ".jpg";
     }
     $bExternalStorage = false;
     foreach (GetModuleEvents("main", "OnFileSave", true) as $arEvent) {
         if (ExecuteModuleEventEx($arEvent, array(&$arFile, $strFileName, $strSavePath, $bForceMD5, $bSkipExt))) {
             $bExternalStorage = true;
             break;
         }
     }
     if (!$bExternalStorage) {
         $newName = '';
         if ($bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N") == "Y") {
             $dir_add = '';
             $i = 0;
             while (true) {
                 $dir_add = substr(md5(uniqid(mt_rand(), true)), 0, 3);
                 if (!$io->FileExists($_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/" . $dir_add . "/" . $strFileName)) {
                     break;
                 }
                 if ($i >= 25) {
                     $j = 0;
                     while (true) {
                         $dir_add = substr(md5(mt_rand()), 0, 3) . "/" . substr(md5(mt_rand()), 0, 3);
                         if (!$io->FileExists($_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/" . $dir_add . "/" . $strFileName)) {
                             break;
                         }
                         if ($j >= 25) {
                             $dir_add = substr(md5(mt_rand()), 0, 3) . "/" . md5(mt_rand());
                             break;
                         }
                         $j++;
                     }
                     break;
                 }
                 $i++;
             }
             if (substr($strSavePath, -1, 1) != "/") {
                 $strSavePath .= "/" . $dir_add;
             } else {
                 $strSavePath .= $dir_add . "/";
             }
             $newName = $strFileName;
         } else {
             $strFileExt = $bSkipExt == true ? '' : strrchr($strFileName, ".");
             while (true) {
                 $newName = md5(uniqid(mt_rand(), true)) . $strFileExt;
                 if (substr($strSavePath, -1, 1) != "/") {
                     $strSavePath .= "/" . substr($newName, 0, 3);
                 } else {
                     $strSavePath .= substr($newName, 0, 3) . "/";
                 }
                 if (!$io->FileExists($_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/" . $newName)) {
                     break;
                 }
             }
         }
         $arFile["SUBDIR"] = $strSavePath;
         $arFile["FILE_NAME"] = $newName;
         $strDirName = $_SERVER["DOCUMENT_ROOT"] . "/" . $upload_dir . "/" . $strSavePath . "/";
         $strDbFileNameX = $strDirName . $newName;
         $strPhysicalFileNameX = $io->GetPhysicalName($strDbFileNameX);
         CheckDirPath($strDirName);
         if (is_set($arFile, "content")) {
             $f = fopen($strPhysicalFileNameX, "ab");
             if (!$f) {
                 return false;
             }
             if (!fwrite($f, $arFile["content"])) {
                 return false;
             }
             fclose($f);
         } elseif (!copy($arFile["tmp_name"], $strPhysicalFileNameX) && !move_uploaded_file($arFile["tmp_name"], $strPhysicalFileNameX)) {
             CFile::DoDelete($arFile["old_file"]);
             return false;
         }
         if (isset($arFile["old_file"])) {
             CFile::DoDelete($arFile["old_file"]);
         }
         @chmod($strPhysicalFileNameX, BX_FILE_PERMISSIONS);
         $imgArray = CFile::GetImageSize($strDbFileNameX);
         if (is_array($imgArray)) {
             $arFile["WIDTH"] = $imgArray[0];
             $arFile["HEIGHT"] = $imgArray[1];
         } else {
             $arFile["WIDTH"] = 0;
             $arFile["HEIGHT"] = 0;
         }
     }
     /****************************** QUOTA ******************************/
     if (COption::GetOptionInt("main", "disk_space") > 0) {
         CDiskQuota::updateDiskQuota("file", $arFile["size"], "insert");
     }
     /****************************** QUOTA ******************************/
     $NEW_IMAGE_ID = CFile::DoInsert(array("HEIGHT" => $arFile["HEIGHT"], "WIDTH" => $arFile["WIDTH"], "FILE_SIZE" => $arFile["size"], "CONTENT_TYPE" => $arFile["type"], "SUBDIR" => $arFile["SUBDIR"], "FILE_NAME" => $arFile["FILE_NAME"], "MODULE_ID" => $arFile["MODULE_ID"], "ORIGINAL_NAME" => $arFile["ORIGINAL_NAME"], "DESCRIPTION" => isset($arFile["description"]) ? $arFile["description"] : '', "HANDLER_ID" => isset($arFile["HANDLER_ID"]) ? $arFile["HANDLER_ID"] : ''));
     CFile::CleanCache($NEW_IMAGE_ID);
     return $NEW_IMAGE_ID;
 }
コード例 #21
0
function AdminUserAvatarsGallery()
{
    global $galeryedit;
    TAddSubTitle('Галерея аватар');
    if (isset($_GET['user']) && $_GET['user'] == '1') {
        $personal = true;
        $dir = System::config('general/personal_avatars_dir');
        $dirlink = System::admin()->Link('Показать аватары из галереи', ADMIN_FILE . '?exe=user&a=avatars');
        $users = System::database()->Select('users', "`type`='2'");
        $c = sizeof($users);
        for ($i = 0; $i < $c; $i++) {
            $users[$users[$i]['avatar']] = $i;
        }
    } else {
        $personal = false;
        $dir = System::config('general/avatars_dir');
        $dirlink = System::admin()->Link('Показать аватары пользователей', ADMIN_FILE . '?exe=user&a=avatars&user=1');
    }
    $avatars2 = GetFiles($dir, false, true, '.gif.jpg.jpeg.png');
    $avatars = array();
    foreach ($avatars2 as $av) {
        $name = GetFileName($av, true);
        $sub = substr($name, -3);
        if ($sub != 'x24' && $sub != 'x64') {
            $avatars[] = $av;
        }
    }
    $c = count($avatars);
    $allsize = 0;
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    if ($c > 0) {
        $col = 0;
        for ($i = 0; $i < $c; $i++) {
            if ($col == 0) {
                $text .= '<tr>';
            }
            $col++;
            $imagfn = $dir . $avatars[$i];
            $size = getimagesize($imagfn);
            $fsize = filesize($imagfn);
            $allsize = $allsize + $fsize;
            if ($galeryedit) {
                $funcs = System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=user&a=delavatar&filename=' . $avatars[$i] . ($personal ? '&personal' : ''), 'images/admin/delete.png', 'Удалить аватар?');
            } else {
                $funcs = '&nbsp;';
            }
            $text .= '<td align="center">
				<table cellspacing="0" cellpadding="0" align="center" style="border:none; background: none;">
				<tr style="border:none; background: none;">
					<td style="border:none; background: none;"><a href="' . $imagfn . '" target="_blank"><img src="' . $imagfn . '" border="0" width="64" title="(' . $size[0] . ' x ' . $size[1] . ', ' . FormatFileSize($fsize) . ') ' . $avatars[$i] . '" /></a></td>
					<td valign="top" style="border:none; background: none;">' . $funcs . '</td>
				</tr>
				';
            if ($personal && isset($users[$avatars[$i]])) {
                $text .= '<tr><td colspan="2" align="left" style="border:none; background: none;"><a href="' . ADMIN_FILE . '?exe=user&a=edituser&id=' . SafeDB($users[$users[$avatars[$i]]]['id'], 11, int) . '">' . SafeDB($users[$users[$avatars[$i]]]['name'], 255, str) . '</a></td></tr>';
            }
            $text .= '</table></td>';
            if ($col == 5) {
                $text .= '</tr>';
                $col = 0;
            }
        }
        if ($col < 5) {
            $text .= '<td colspan="' . (5 - $col) . '"></td>';
            $text .= '</tr>';
        }
    } else {
        $text .= '<tr><td>В галерее нет ни одного аватара.</td></tr>';
    }
    $text .= '</table>';
    $info = '<table cellspacing="0" cellpadding="0" border="0" class="cfgtable">
		<tr>
		<td width="34%">Аватар в галерее: ' . $c . '</td>
		<td width="33%">Общий размер: ' . FormatFileSize($allsize) . '</td>
		<td>' . $dirlink . '</td>
		</tr>
	</table>';
    $text = $info . $text;
    AddCenterBox('Галерея аватар', $text);
    AddText($text);
    if (!$personal && $galeryedit) {
        System::admin()->FormTitleRow('Загрузить аватар');
        FormRow('Выберите файл', System::site()->FFile('avatar'));
        AddForm(System::site()->FormOpen(ADMIN_FILE . '?exe=user&a=saveavatar', 'post', true), System::site()->Submit('Загрузить'));
    }
    AddText('<br />');
}
コード例 #22
0
 /**
  * Возвращае список всех доступных ключей в группе.
  * @param string $Group
  * @return array
  */
 public function GetKeys($Group)
 {
     $files = GetFiles($this->Path . $Group . '/');
     foreach ($files as $key => $file) {
         $files[$key] = GetFileName($file, true);
     }
     return $files;
 }
コード例 #23
0
 }
 if ($ismenu) {
     $aDDMenuEdit[] = array("TEXT" => GetMessage("FILEMAN_FILEEDIT_AS_MENU"), "ACTION" => "window.location='fileman_menu_edit.php?" . $addUrl . "&amp;site=" . Urlencode($site) . "&amp;path=" . UrlEncode($arParsedPath["PREV"]) . "&amp;name=" . UrlEncode($regs[1]) . ($new == 'y' ? "&amp;new=Y" : "") . (strlen($back_url) > 0 ? "&amp;back_url=" . urlencode($back_url) : "") . "';");
 }
 $aDDMenuEdit[] = array("TEXT" => GetMessage("FILEMAN_FILEEDIT_AS_HTML"), "ACTION" => "return;", "ICON" => "checked");
 $aMenu[] = array("TEXT" => GetMessage("FILEMAN_FILE_EDIT"), "TITLE" => GetMessage("FILEMAN_FILE_EDIT"), "MENU" => $aDDMenuEdit);
 if ($bEdit) {
     if ($USER->CanDoFileOperation('fm_rename_file', $arPath)) {
         $aMenu[] = array("TEXT" => GetMessage("FILEMAN_FILEEDIT_RENAME"), "LINK" => "fileman_rename.php?" . $addUrl . "&amp;site=" . Urlencode($site) . "&amp;path=" . UrlEncode($arParsedPath["PREV"]) . "&amp;files[]=" . UrlEncode($arParsedPath["LAST"]));
     }
     if ($USER->CanDoFileOperation('fm_download_file', $arPath) && !(HasScriptExtension($path) || substr(CFileman::GetFileName($path), 0, 1) == ".") || $USER->CanDoOperation('edit_php')) {
         $aMenu[] = array("TEXT" => GetMessage("FILEMAN_FILEEDIT_DOWNLOAD"), "LINK" => "fileman_file_download.php?" . $addUrl . "&amp;site=" . Urlencode($site) . "&amp;path=" . UrlEncode($path));
     }
     if ($USER->CanDoFileOperation('fm_delete_file', $arPath)) {
         $folder_path = substr($path, 0, strrpos($path, "/"));
         $id = GetFileName($path);
         $aMenu[] = array("TEXT" => GetMessage("FILEMAN_FILE_DELETE"), "LINK" => "javascript:if(confirm('" . GetMessage("FILEMAN_FILE_DELETE_CONFIRM") . "')) window.location='/bitrix/admin/fileman_admin.php?ID=" . urlencode($id) . "&action=delete&" . $addUrl . "&site=" . urlencode($site) . "&path=" . urlencode($folder_path) . "&" . bitrix_sessid_get() . "';", "TITLE" => GetMessage("FILEMAN_FILE_DELETE"));
     }
 }
 $context = new CAdminContextMenu($aMenu);
 $context->Show();
 global $__fd_path;
 $__fd_path = $bEdit ? $arParsedPath["PREV"] : $path;
 $arContextTemplates = array();
 $arTemplates = CFileman::GetFileTemplates(LANGUAGE_ID, array($site_template));
 $cntTempl = count($arTemplates);
 for ($i = 0; $i < $cntTempl; $i++) {
     $arContextTemplates[] = array("TEXT" => htmlspecialcharsbx($arTemplates[$i]["name"]), "ONCLICK" => "__NewDocTempl('" . AddSlashes(htmlspecialcharsbx($arTemplates[$i]["file"])) . "')");
 }
 $u = new CAdminPopup("new_doc_list", "new_doc_list", $arContextTemplates);
 CAdminFileDialog::ShowScript(array("event" => "__bx_fd_save_as", "arResultDest" => array("FUNCTION_NAME" => "OnSaveAs"), "arPath" => array('SITE' => $site, 'PATH' => $_REQUEST['path']), "select" => 'F', "operation" => 'S', "showUploadTab" => false, "showAddToMenuTab" => true, "fileFilter" => 'php,html,htm,phtml', "allowAllFiles" => true, "saveConfig" => false));
コード例 #24
0
ファイル: archive.php プロジェクト: Satariall/izurit
 /**
  * Checks if current user has access to the file or folder according to Bitrix permissions
  * @static
  * @param string $strFilename full path to the file
  * @param boolean $isFile true if we check file permissions, false if folder permissions should be checked
  * @return boolean
  */
 public static function HasAccess($strFilename, $isFile)
 {
     $result = false;
     $path = removeDocRoot($strFilename);
     global $USER;
     if (!$isFile) {
         if ($USER->CanDoFileOperation("fm_view_listing", array(SITE_ID, $path))) {
             $result = true;
         }
     } else {
         if ($USER->CanDoFileOperation('fm_view_file', array(SITE_ID, $path)) && ($USER->CanDoOperation('edit_php') || $USER->CanDoFileOperation('fm_lpa', array(SITE_ID, $path)) || !(HasScriptExtension($path) || substr(GetFileName($path), 0, 1) == "."))) {
             $result = true;
         }
     }
     return $result;
 }
コード例 #25
0
function GetFieldValue($s_fld, $a_main_vars, $s_array_sep = ";")
{
    if (!isset($a_main_vars[$s_fld])) {
        if (($s_name = GetFileName($s_fld)) === false) {
            $s_name = "";
        }
        return $s_name;
    }
    if (is_array($a_main_vars[$s_fld])) {
        return implode($s_array_sep, $a_main_vars[$s_fld]);
    } else {
        return (string) $a_main_vars[$s_fld];
    }
}
コード例 #26
0
if ($avatar == '' || !is_file($avatar)) {
    $avatar = GetGalleryAvatar('noavatar.gif');
}
// Создаём уменьшенную копию аватара, если нужно и отправляем пользователю
if (isset($_GET['size'])) {
    switch ($_GET['size']) {
        case 'small':
            $avatar_64 = System::config('general/personal_avatars_dir') . GetFileName($avatar, true) . '_64x64' . GetFileExt($avatar);
            if (is_file($avatar_64)) {
                CreateThumb($avatar_64)->SendToHTTPClient();
            } else {
                CreateThumb($avatar, $avatar_64, 64, 64)->SendToHTTPClient();
            }
            break;
        case 'smallest':
            $avatar_24 = System::config('general/personal_avatars_dir') . GetFileName($avatar, true) . '_24x24' . GetFileExt($avatar);
            if (is_file($avatar_24)) {
                CreateThumb($avatar_24)->SendToHTTPClient();
            } else {
                CreateThumb($avatar, $avatar_24, 24, 24)->SendToHTTPClient();
            }
            break;
        default:
            CreateThumb($avatar)->SendToHTTPClient();
    }
} else {
    CreateThumb($avatar)->SendToHTTPClient();
}
if (isset($user_id) && !System::config('user/secure_avatar_upload')) {
    System::user()->UpdateAvatarData($user_id);
}
コード例 #27
0
 function GetSafeFieldValue($s_fld, $b_text_subs = false, $s_array_sep = ";")
 {
     //
     // for array values, insert the array separator after making
     // the individual values HTML-safe
     // The equivalent logic up to and including version 8.24 used
     // htmlspecialchars not htmlentities.
     // The use of htmlentities broke UTF-8 template processing,
     // and this was reported in version 8.28.
     // By specifying the character set, we trigger the use of htmlspecialchars
     // so the logic is equivalent to the old logic.
     //
     if (isset($this->_aFields[$s_fld]) && is_array($this->_aFields[$s_fld])) {
         $s_value = implode($this->_GetArraySep($s_array_sep), HTMLEntitiesArray($this->_aFields[$s_fld], false, GetMailOption("CharSet")));
     } else {
         if (!isset($this->_aFields[$s_fld])) {
             if (($s_name = GetFileName($s_fld)) === false) {
                 $s_name = "";
             }
             $s_value = $s_name;
         } else {
             $s_value = (string) $this->_aFields[$s_fld];
         }
         if ($b_text_subs) {
             list($s_value, $a_subs_data) = $this->_PrepareTextSubstitute($s_value);
         }
         $s_value = FixedHTMLEntities($s_value, GetMailOption("CharSet"));
         if ($b_text_subs) {
             $s_value = $this->_CompleteTextSubstitute($s_value, $a_subs_data);
         }
     }
     return $s_value;
 }
コード例 #28
0
/**
 * Удаляет все размеры аватара по его имени
 * @param $AvatarFileName
 * @return void
 */
function UnlinkUserAvatarFiles($AvatarFileName)
{
    $pavatar_dir = System::config('general/personal_avatars_dir');
    $AvatarFileName = RealPath2($pavatar_dir . $AvatarFileName);
    if (is_file($AvatarFileName)) {
        unlink($AvatarFileName);
        $_name = GetFileName($AvatarFileName, true);
        $_ext = GetFileExt($AvatarFileName);
        if (is_file($pavatar_dir . $_name . '_24x24' . $_ext)) {
            unlink($pavatar_dir . $_name . '_24x24' . $_ext);
        }
        if (is_file($pavatar_dir . $_name . '_64x64' . $_ext)) {
            unlink($pavatar_dir . $_name . '_64x64' . $_ext);
        }
    }
}
コード例 #29
0
ファイル: zip.php プロジェクト: ASDAFF/entask.ru
 private function _extractFile(&$arEntry, $path, $removePath, $removeAllPath, &$arParams)
 {
     if (($res = $this->_readFileHeader($header)) != 1) {
         return $res;
     }
     //to be checked: file header should be coherent with $arEntry info
     $arEntry["filename"] = CharsetConverter::ConvertCharset($arEntry["filename"], "cp866", $this->fileSystemEncoding);
     $arEntry["stored_filename"] = CharsetConverter::ConvertCharset($arEntry["stored_filename"], "cp866", $this->fileSystemEncoding);
     //protecting against ../ etc in file path
     //only absolute path should be in the $arEntry
     $arEntry['filename'] = _normalizePath($arEntry['filename']);
     $arEntry['stored_filename'] = _normalizePath($arEntry['stored_filename']);
     if ($removeAllPath == true) {
         $arEntry['filename'] = basename($arEntry['filename']);
     } else {
         if ($removePath != "") {
             if ($this->_containsPath($removePath, $arEntry['filename']) == 2) {
                 //change file status
                 $arEntry['status'] = "filtered";
                 return $res;
             }
             $removePath_size = strlen($removePath);
             if (substr($arEntry['filename'], 0, $removePath_size) == $removePath) {
                 //remove path
                 $arEntry['filename'] = substr($arEntry['filename'], $removePath_size);
             }
         }
     }
     //making absolute path to the extracted file out of filename stored in the zip header and passed extracting path
     if ($path != '') {
         $arEntry['filename'] = $path . "/" . $arEntry['filename'];
     }
     //pre-extract callback
     if (isset($arParams['callback_pre_extract']) && $arParams['callback_pre_extract'] != '') {
         //generate local info
         $arLocalHeader = array();
         $this->_convertHeader2FileInfo($arEntry, $arLocalHeader);
         //callback call
         eval('$res = ' . $arParams['callback_pre_extract'] . '(\'callback_pre_extract\', $arLocalHeader);');
         //change file status
         if ($res == 0) {
             $arEntry['status'] = "skipped";
             $res = 1;
         }
         //update the info, only some fields can be modified
         $arEntry['filename'] = $arLocalHeader['filename'];
     }
     //check if extraction should be done
     if ($arEntry['status'] == 'ok') {
         $logicalFilename = $this->io->GetLogicalName($arEntry['filename']);
         if ((HasScriptExtension($arEntry['filename']) || IsFileUnsafe($arEntry['filename']) || !$this->io->ValidatePathString($logicalFilename) || !$this->io->ValidateFilenameString(GetFileName($logicalFilename))) && $this->checkBXPermissions == true) {
             $arEntry['status'] = "no_permissions";
         } else {
             //if the file exists, change status
             if (file_exists($arEntry['filename'])) {
                 if (is_dir($arEntry['filename'])) {
                     $arEntry['status'] = "already_a_directory";
                 } else {
                     if (!is_writeable($arEntry['filename'])) {
                         $arEntry['status'] = "write_protected";
                     } else {
                         if (filemtime($arEntry['filename']) > $arEntry['mtime'] && !$this->replaceExistentFiles) {
                             $arEntry['status'] = "newer_exist";
                         }
                     }
                 }
             } else {
                 //check the directory availability and create it if necessary
                 if (($arEntry['external'] & 0x10) == 0x10 || substr($arEntry['filename'], -1) == '/') {
                     $checkDir = $arEntry['filename'];
                 } else {
                     if (!strstr($arEntry['filename'], "/")) {
                         $checkDir = "";
                     } else {
                         $checkDir = dirname($arEntry['filename']);
                     }
                 }
                 if (($res = $this->_checkDir($checkDir, ($arEntry['external'] & 0x10) == 0x10)) != 1) {
                     //change file status
                     $arEntry['status'] = "path_creation_fail";
                     //return $res;
                     $res = 1;
                 }
             }
         }
     }
     //check if extraction should be done
     if ($arEntry['status'] == 'ok') {
         //if not a folder - extract
         if (!(($arEntry['external'] & 0x10) == 0x10)) {
             //if zip file with 0 compression
             if ($arEntry['compression'] == 0 && $arEntry['compressed_size'] == $arEntry['size']) {
                 if (($destFile = @fopen($arEntry['filename'], 'wb')) == 0) {
                     $arEntry['status'] = "write_error";
                     return $res;
                 }
                 //reading the fileby by self::ReadBlockSize octets blocks
                 $size = $arEntry['compressed_size'];
                 while ($size != 0) {
                     $length = $size < self::ReadBlockSize ? $size : self::ReadBlockSize;
                     $buffer = fread($this->zipfile, $length);
                     $binary_data = pack('a' . $length, $buffer);
                     @fwrite($destFile, $binary_data, $length);
                     $size -= $length;
                 }
                 //close the destination file
                 fclose($destFile);
                 //changing file modification time
                 touch($arEntry['filename'], $arEntry['mtime']);
             } else {
                 if (($destFile = @fopen($arEntry['filename'], 'wb')) == 0) {
                     //change file status
                     $arEntry['status'] = "write_error";
                     return $res;
                 }
                 //read the compressed file in a buffer (one shot)
                 $buffer = @fread($this->zipfile, $arEntry['compressed_size']);
                 //decompress the file
                 $fileContent = gzinflate($buffer);
                 unset($buffer);
                 //write uncompressed data
                 @fwrite($destFile, $fileContent, $arEntry['size']);
                 unset($fileContent);
                 @fclose($destFile);
                 touch($arEntry['filename'], $arEntry['mtime']);
             }
             if (isset($arParams['set_chmod']) && $arParams['set_chmod'] != 0) {
                 chmod($arEntry['filename'], $arParams['set_chmod']);
             }
         }
     }
     //post-extract callback
     if (isset($arParams['callback_post_extract']) && $arParams['callback_post_extract'] != '') {
         //make local info
         $arLocalHeader = array();
         $this->_convertHeader2FileInfo($arEntry, $arLocalHeader);
         //callback call
         eval('$res = ' . $arParams['callback_post_extract'] . '(\'callback_post_extract\', $arLocalHeader);');
     }
     return $res;
 }
コード例 #30
0
ファイル: tar_gz.php プロジェクト: ASDAFF/open_bx
 private function _extractList($p_path, &$p_list_detail, $p_mode, $p_file_list, $p_remove_path)
 {
     $v_result = true;
     $v_nb = 0;
     $v_extract_all = true;
     $v_listing = false;
     $p_path = str_replace("\\", "/", $p_path);
     $p_path = $this->io->GetPhysicalName($p_path);
     if ($p_path == '' || substr($p_path, 0, 1) != '/' && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':')) {
         $p_path = "./" . $p_path;
     }
     $p_remove_path = str_replace("\\", "/", $p_remove_path);
     if ($p_remove_path != '' && substr($p_remove_path, -1) != '/') {
         $p_remove_path .= '/';
     }
     $p_remove_path_size = strlen($p_remove_path);
     switch ($p_mode) {
         case "complete":
             $v_extract_all = TRUE;
             $v_listing = FALSE;
             break;
         case "partial":
             $v_extract_all = FALSE;
             $v_listing = FALSE;
             break;
         case "list":
             $v_extract_all = FALSE;
             $v_listing = TRUE;
             break;
         default:
             $this->_arErrors[] = array("ERR_PARAM", str_replace("#EXTRACT_MODE#", $p_mode, GetMessage("MAIN_ARCHIVE_ERR_PARAM")));
             return false;
     }
     clearstatcache();
     while (self::$bMbstring ? mb_strlen($v_binary_data = $this->_readBlock(), "latin1") : strlen($v_binary_data = $this->_readBlock()) != 0) {
         $v_extract_file = FALSE;
         $v_extraction_stopped = 0;
         if (!$this->_readHeader($v_binary_data, $v_header)) {
             return false;
         }
         if ($v_header['filename'] == '') {
             continue;
         }
         // ----- Look for long filename
         if ($v_header['typeflag'] == 'L') {
             if (!$this->_readLongHeader($v_header)) {
                 return false;
             }
         }
         if (!$v_extract_all && is_array($p_file_list)) {
             // ----- By default no unzip if the file is not found
             $v_extract_file = false;
             $l = count($p_file_list);
             for ($i = 0; $i < $l; $i++) {
                 // ----- Look if it is a directory
                 if (substr($p_file_list[$i], -1) == '/') {
                     // ----- Look if the directory is in the filename path
                     if (strlen($v_header['filename']) > strlen($p_file_list[$i]) && substr($v_header['filename'], 0, strlen($p_file_list[$i])) == $p_file_list[$i]) {
                         $v_extract_file = TRUE;
                         break;
                     }
                 } elseif ($p_file_list[$i] == $v_header['filename']) {
                     // ----- It is a file, so compare the file names
                     $v_extract_file = TRUE;
                     break;
                 }
             }
         } else {
             $v_extract_file = TRUE;
         }
         // ----- Look if this file need to be extracted
         if ($v_extract_file && !$v_listing) {
             if ($p_remove_path != '' && substr($v_header['filename'], 0, $p_remove_path_size) == $p_remove_path) {
                 $v_header['filename'] = substr($v_header['filename'], $p_remove_path_size);
             }
             if ($p_path != './' && $p_path != '/') {
                 while (substr($p_path, -1) == '/') {
                     $p_path = substr($p_path, 0, strlen($p_path) - 1);
                 }
                 if (substr($v_header['filename'], 0, 1) == '/') {
                     $v_header['filename'] = $p_path . $v_header['filename'];
                 } else {
                     $v_header['filename'] = $p_path . '/' . $v_header['filename'];
                 }
             }
             if (file_exists($v_header['filename'])) {
                 if (@is_dir($v_header['filename']) && $v_header['typeflag'] == '') {
                     $this->_arErrors[] = array("DIR_EXISTS", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_DIR_EXISTS")));
                     return false;
                 }
                 if (is_file($v_header['filename']) && $v_header['typeflag'] == "5") {
                     $this->_arErrors[] = array("FILE_EXISTS", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_FILE_EXISTS")));
                     return false;
                 }
                 if (!is_writeable($v_header['filename'])) {
                     $this->_arErrors[] = array("FILE_PERMS", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_FILE_PERMS")));
                     return false;
                 }
             } elseif (($v_result = $this->_dirCheck($v_header['typeflag'] == "5" ? $v_header['filename'] : dirname($v_header['filename']))) != 1) {
                 $this->_arErrors[] = array("NO_DIR", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_NO_DIR")));
                 return false;
             }
             if ($v_extract_file) {
                 $logicalFilename = $this->io->GetLogicalName($v_header['filename']);
                 if ((HasScriptExtension($v_header['filename']) || IsFileUnsafe($v_header['filename']) || !$this->io->ValidatePathString($logicalFilename) || !$this->io->ValidateFilenameString(GetFileName($logicalFilename))) && $this->CheckBXPermissions == true) {
                     $this->_jumpBlock(ceil($v_header['size'] / 512));
                 } elseif (file_exists($v_header['filename']) && $this->ReplaceExistentFiles || !file_exists($v_header['filename'])) {
                     if ($v_header['typeflag'] == "5") {
                         if (!@file_exists($v_header['filename'])) {
                             if (!@mkdir($v_header['filename'], FX_DIR_PERMISSIONS)) {
                                 $this->_arErrors[] = array("ERR_CREATE_DIR", str_replace("#DIR_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_ERR_CREATE_DIR")));
                                 return false;
                             }
                         }
                     } else {
                         if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) {
                             $this->_arErrors[] = array("ERR_CREATE_FILE", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_ERR_CREATE_FILE")));
                             return false;
                         } else {
                             $n = floor($v_header['size'] / 512);
                             for ($i = 0; $i < $n; $i++) {
                                 $v_content = $this->_readBlock();
                                 fwrite($v_dest_file, $v_content, 512);
                             }
                             if ($v_header['size'] % 512 != 0) {
                                 $v_content = $this->_readBlock();
                                 fwrite($v_dest_file, $v_content, $v_header['size'] % 512);
                             }
                             @fclose($v_dest_file);
                             @chmod($v_header['filename'], FX_FILE_PERMISSIONS);
                             @touch($v_header['filename'], $v_header['mtime']);
                         }
                         clearstatcache();
                         if (filesize($v_header['filename']) != $v_header['size']) {
                             $this->_arErrors[] = array("ERR_SIZE_CHECK", str_replace(array("#FILE_NAME#", "#SIZE#", "#EXP_SIZE#"), array(removeDocRoot($v_header['size']), filesize($v_header['filename']), $v_header['size']), GetMessage("MAIN_ARCHIVE_ERR_SIZE_CHECK")));
                             return false;
                         }
                     }
                 } else {
                     $this->_jumpBlock(ceil($v_header['size'] / 512));
                 }
             } else {
                 $this->_jumpBlock(ceil($v_header['size'] / 512));
             }
         } else {
             $this->_jumpBlock(ceil($v_header['size'] / 512));
         }
         if ($v_listing || $v_extract_file || $v_extraction_stopped) {
             if (($v_file_dir = dirname($v_header['filename'])) == $v_header['filename']) {
                 $v_file_dir = '';
             }
             if (substr($v_header['filename'], 0, 1) == '/' && $v_file_dir == '') {
                 $v_file_dir = '/';
             }
             $p_list_detail[$v_nb++] = $v_header;
         }
     }
     return true;
 }