コード例 #1
0
ファイル: fileinputreceiver.php プロジェクト: nycmic/bittest
	protected static function handleFileByPath($hash, &$file)
	{
		$key = "default";

		$path = $file["files"][$key]["tmp_name"];

		$io = \CBXVirtualIo::GetInstance();

		$newPath = substr($path, 0, (strlen($path) - strlen($key))).$file["name"];

		$f = $io->GetFile($path);
		$newF = $io->GetFile($newPath);

		if ((!$newF->IsExists() || $newF->unlink()) && $io->Rename($path, $newPath))
		{
			$f = $io->GetFile($newPath);
			$file["files"][$key]["tmp_name"] = $newPath;
		}

		if (self::resizePicture($file["files"][$key], array("method" => "resample")))
		{
			clearstatcache();
			$file["files"][$key]["wasChangedOnServer"] = true;
			$file["files"][$key]["size"] = filesize($file["files"][$key]["tmp_name"]);
			$file["files"][$key]["sizeFormatted"] = \CFile::FormatSize($file["files"][$key]["size"]);
		}

		$file["path"] = \Bitrix\Main\IO\Path::convertPhysicalToLogical($f->GetPathWithName());
		if (strpos($file["path"], $_SERVER["DOCUMENT_ROOT"]) === 0)
			$file["path"] = str_replace("//", "/", "/".substr($file["path"], strlen($_SERVER["DOCUMENT_ROOT"])));
		$file["uploadId"] = $file["path"];
		$file["files"][$key]["url"] =
		$file["files"][$key]["tmp_url"] = \Bitrix\Main\IO\Path::convertPhysicalToUri($file["path"]);

		$file["type"] = $file["files"][$key]["type"];
		return true;
	}
コード例 #2
0
ファイル: file.php プロジェクト: andy-profi/bxApiDocs
 /**
  * <p>Метод сохраняет файл и регистрирует его в таблице файлов (b_file). Статичный метод.</p>
  *
  *
  * @param array $file  Массив с данными файла формата:<br><br><pre>Array( "name" =&gt; "название файла",
  * "size" =&gt; "размер", "tmp_name" =&gt; "временный путь на сервере", "type" =&gt; "тип
  * загружаемого файла", "old_file" =&gt; "ID старого файла", "del" =&gt; "флажок -
  * удалить ли существующий файл (Y|N)", "MODULE_ID" =&gt; "название модуля",
  * "description" =&gt; "описание файла", "content" =&gt; "содержимое файла. Можно
  * сохранять файл, указывая его содержимое, а не только массив,
  * полученный при загрузке браузером."</pre> Массив такого вида может
  * быть получен, например, объединением массивов $_FILES[имя поля] и
  * Array("del" =&gt; ${"имя поля"."_del"}, "MODULE_ID" = "название модуля");
  *
  * @param string $save_path  Путь к папке в которой хранятся файлы (относительно папки /upload).
  *
  * @param bool $ForceMD5 = false Необязательный. По умолчанию <i>false</i>.
  *
  * @param bool $SkipExt = false) Необязательный. По умолчанию <i>false</i>.
  *
  * @return mixed <p>Метод возвращает числовой идентификатор сохранённого и
  * зарегистрированного в системе файла.</p>
  *
  * <h4>Example</h4> 
  * <pre>
  * &lt;?
  * if (strlen($save)&gt;0 &amp;&amp; $REQUEST_METHOD=="POST")
  * {
  *     $arIMAGE = $_FILES["IMAGE_ID"];
  *     $z = $DB-&gt;Query("SELECT IMAGE_ID FROM b_vote WHERE ID='$ID'", false, $err_mess.__LINE__);
  *     $zr = $z-&gt;Fetch();
  *     $arIMAGE["old_file"] = $zr["IMAGE_ID"];
  *     $arIMAGE["del"] = ${"IMAGE_ID_del"};
  *     $arIMAGE["MODULE_ID"] = "vote";
  *     if (strlen($arIMAGE["name"])&gt;0 || strlen($arIMAGE["del"])&gt;0) 
  *     {
  *         $fid = <b>CFile::SaveFile</b>($arIMAGE, "vote");
  *         if (intval($fid)&gt;0) $arFields["IMAGE_ID"] = intval($fid); 
  *         else $arFields["IMAGE_ID"] = "null";
  *         $DB-&gt;Update("b_vote",$arFields,"WHERE ID='".$ID."'",$err_mess.__LINE__);
  *     }
  * }
  * ?&gt;
  * </pre>
  *
  *
  * <h4>See Also</h4> 
  * <ul> <li> <a href="http://dev.1c-bitrix.ru/api_help/main/functions/file/rewritefile.php">RewriteFile</a> </li> <li> <a
  * href="http://dev.1c-bitrix.ru/api_help/main/reference/cfile/inputfile.php">CFile::InputFile</a> </li> </ul><a
  * name="examples"></a>
  *
  *
  * @static
  * @link http://dev.1c-bitrix.ru/api_help/main/reference/cfile/savefile.php
  * @author Bitrix
  */
 public static 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(IO\Path::convertPhysicalToLogical($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;
 }
コード例 #3
0
 protected function createFileInternal(FileData $fileData)
 {
     if (!$this->checkRequiredInputParams($fileData->toArray(), array('name', 'src'))) {
         return null;
     }
     $accessToken = $this->getAccessToken();
     $fileName = $fileData->getName();
     $fileName = $this->convertToUtf8($fileName);
     $http = new HttpClient(array('redirect' => false, 'socketTimeout' => 10, 'streamTimeout' => 30, 'version' => HttpClient::HTTP_1_1));
     $fileName = urlencode($fileName);
     $accessToken = urlencode($accessToken);
     if ($http->query('PUT', "https://apis.live.net/v5.0/me/skydrive/files/{$fileName}?access_token={$accessToken}", IO\File::getFileContents(IO\Path::convertPhysicalToLogical($fileData->getSrc()))) === false) {
         $errorString = implode('; ', array_keys($http->getError()));
         $this->errorCollection->add(array(new Error($errorString, self::ERROR_HTTP_FILE_INTERNAL)));
         return null;
     }
     if (!$this->checkHttpResponse($http)) {
         return null;
     }
     $finalOutput = Json::decode($http->getResult());
     if ($finalOutput === null) {
         $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON)));
         return null;
     }
     $fileData->setId($finalOutput['id']);
     $props = $this->getFileData($fileData);
     if ($props === null) {
         return null;
     }
     $fileData->setLinkInService($props['link']);
     return $fileData;
 }