Exemple #1
0
 protected function receiveFiles()
 {
     $result = array();
     $timeToKeepFiles = 24;
     $tmpDir = \CTempFile::GetDirectoryName($timeToKeepFiles);
     CheckDirPath($tmpDir);
     $sftp = \Bitrix\Sale\TradingPlatform\Ebay\Helper::getSftp($this->siteId);
     $sftp->connect();
     /*
     $orderFiles = $sftp->getFilesList($this->remotePath);
     
     foreach($orderFiles as $file)
     {
     	if($sftp->downloadFile($this->remotePath."/".$file, $tmpDir.$file))
     	{
     		$result[] = $tmpDir.$file;
     		Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_SOURCE_ORDERFILE_RECEIVED", $file, "File received successfully.", $this->siteId);
     	}
     }
     */
     $file = "orderLatest";
     if ($sftp->downloadFile($this->orderLatest, $tmpDir . $file)) {
         $result[] = $tmpDir . $file;
         Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_SOURCE_ORDERFILE_RECEIVED", $file, "File received successfully.", $this->siteId);
     }
     return $result;
 }
Exemple #2
0
 /**
  * @return string
  */
 public function getFileInfo()
 {
     $fileInfo = null;
     if ($this->encoding === 'B' || $this->encoding === 'BASE64') {
         $type = $this->type !== '' ? strtolower($this->type) : 'jpg';
         if ($type === '' || !in_array($type, explode(',', \CFile::GetImageExtensions()), true)) {
             $type = 'jpg';
         }
         $filePath = \CTempFile::GetFileName(uniqid('vcard_img') . '.' . $type);
         CheckDirPath($filePath);
         //Removing of line folding
         $encodedData = preg_replace("/\\\\n/i", "\n", $this->value);
         if (file_put_contents($filePath, base64_decode($encodedData)) !== false) {
             $fileInfo = \CFile::MakeFileArray($filePath, "image/{$type}");
         }
     } elseif ($this->valueType === 'URI' && \CCrmUrlUtil::HasScheme($this->value) && \CCrmUrlUtil::IsSecureUrl($this->value)) {
         $fileInfo = \CFile::MakeFileArray($this->value);
     }
     return is_array($fileInfo) && strlen(\CFile::CheckImageFile($fileInfo)) === 0 ? $fileInfo : null;
 }
Exemple #3
0
 protected function processActionCommit()
 {
     if (!$this->checkPermission()) {
         $this->sendJsonResponse(array('status' => self::STATUS_DENIED));
     }
     if (!isset($_FILES['file'])) {
         $this->sendJsonResponse(array('status' => self::STATUS_DENIED, 'message' => 'Upload file'));
     }
     $downloadedFile = $_FILES['file'];
     $webdav = $this->getWebdav();
     if (empty($webdav->arParams['element_array']['ID'])) {
         $this->sendJsonResponse(array('status' => self::STATUS_NOT_FOUND));
     }
     $filename = CTempFile::GetFileName(uniqid('_wd'));
     $nameToSavedFile = $webdav->arParams['element_name'];
     CheckDirPath($filename);
     if (($downloadedFile['error'] = intval($downloadedFile['error'])) > 0) {
         if ($downloadedFile['error'] < 3) {
             $this->sendJsonResponse(array('status' => self::STATUS_ERROR, 'message' => "Upload error: {$downloadedFile['error']}"));
         } else {
             $this->sendJsonResponse(array('status' => self::STATUS_ERROR, 'message' => "Upload error: {$downloadedFile['error']}"));
         }
     }
     if (!is_uploaded_file($downloadedFile['tmp_name'])) {
         $this->sendJsonResponse(array('status' => self::STATUS_ERROR, 'message' => "Upload error"));
     }
     if (!move_uploaded_file($downloadedFile['tmp_name'], $filename)) {
         $this->sendJsonResponse(array('status' => self::STATUS_ERROR, 'message' => "Bad move after upload"));
     }
     $options = array('new' => false, 'FILE_NAME' => $nameToSavedFile, 'ELEMENT_ID' => $webdav->arParams['element_array']['ID'], 'arUserGroups' => $webdav->USER['GROUPS'], 'TMP_FILE' => $filename);
     $this->getDb()->startTransaction();
     if (!$this->getWebDav()->put_commit($options)) {
         $this->getDb()->rollback();
         $this->sendJsonResponse(array('status' => self::STATUS_ERROR, 'message' => 'Error in commit.', 'description' => $webdav->LAST_ERROR));
     }
     $this->getDb()->commit();
     $this->sendJsonResponse(array('status' => self::STATUS_SUCCESS));
 }
Exemple #4
0
 protected function getFileContent($feedData)
 {
     $result = "";
     $timeToKeepFiles = 24;
     $tmpDir = \CTempFile::GetDirectoryName($timeToKeepFiles);
     CheckDirPath($tmpDir);
     $sftp = \Bitrix\Sale\TradingPlatform\Ebay\Helper::getSftp($this->siteId);
     $sftp->connect();
     $remotePath = $this->createRemotePath($feedData);
     $files = $sftp->getFilesList($remotePath);
     foreach ($files as $file) {
         if (!strstr($file, $feedData["FILENAME"])) {
             continue;
         }
         if ($sftp->downloadFile($remotePath . "/" . $file, $tmpDir . $file)) {
             $result = file_get_contents($tmpDir . $file);
             Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_SOURCE_RESULTS_RECEIVED", $file, "File received successfully.", $this->siteId);
         } else {
             Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_SOURCE_RESULTS_ERROR", $tmpDir . $file, "Can't receive file content.", $this->siteId);
         }
     }
     return $result;
 }
Exemple #5
0
 private static function _absolute_path_recursive_delete($path)
 {
     if (strlen($path) == 0 || $path == '/') {
         return false;
     }
     $f = true;
     if (is_file($path) || is_link($path)) {
         if (@unlink($path)) {
             return true;
         }
         return false;
     } elseif (is_dir($path)) {
         if ($handle = opendir($path)) {
             while (($file = readdir($handle)) !== false) {
                 if ($file == "." || $file == "..") {
                     continue;
                 }
                 if (!CTempFile::_absolute_path_recursive_delete($path . "/" . $file)) {
                     $f = false;
                 }
             }
             closedir($handle);
         }
         if (!@rmdir($path)) {
             return false;
         }
         return $f;
     }
     return false;
 }
Exemple #6
0
 function ResizeImageFile($sourceFile, &$destinationFile, $arSize, $resizeType = BX_RESIZE_IMAGE_PROPORTIONAL, $arWaterMark = array(), $jpgQuality = false, $arFilters = false)
 {
     $io = CBXVirtualIo::GetInstance();
     if (!$io->FileExists($sourceFile)) {
         return false;
     }
     $bNeedCreatePicture = false;
     if ($resizeType != BX_RESIZE_IMAGE_EXACT && $resizeType != BX_RESIZE_IMAGE_PROPORTIONAL_ALT) {
         $resizeType = BX_RESIZE_IMAGE_PROPORTIONAL;
     }
     if (!is_array($arSize)) {
         $arSize = array();
     }
     if (!array_key_exists("width", $arSize) || intval($arSize["width"]) <= 0) {
         $arSize["width"] = 0;
     }
     if (!array_key_exists("height", $arSize) || intval($arSize["height"]) <= 0) {
         $arSize["height"] = 0;
     }
     $arSize["width"] = intval($arSize["width"]);
     $arSize["height"] = intval($arSize["height"]);
     $arSourceSize = array("x" => 0, "y" => 0, "width" => 0, "height" => 0);
     $arDestinationSize = array("x" => 0, "y" => 0, "width" => 0, "height" => 0);
     $arSourceFileSizeTmp = CFile::GetImageSize($sourceFile);
     if (!in_array($arSourceFileSizeTmp[2], array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_BMP))) {
         return false;
     }
     if (class_exists("imagick") && function_exists('memory_get_usage')) {
         //When memory limit reached we'll try to use ImageMagic
         $memoryNeeded = round(($arSourceFileSizeTmp[0] * $arSourceFileSizeTmp[1] * $arSourceFileSizeTmp['bits'] * ($arSourceFileSizeTmp['channels'] > 0 ? $arSourceFileSizeTmp['channels'] : 1) / 8 + pow(2, 16)) * 1.65);
         $memoryLimit = CUtil::Unformat(ini_get('memory_limit'));
         if (memory_get_usage() + $memoryNeeded > $memoryLimit) {
             if ($arSize["width"] <= 0 || $arSize["height"] <= 0) {
                 $arSize["width"] = $arSourceFileSizeTmp[0];
                 $arSize["height"] = $arSourceFileSizeTmp[1];
             }
             CFile::ScaleImage($arSourceFileSizeTmp[0], $arSourceFileSizeTmp[1], $arSize, $resizeType, $bNeedCreatePicture, $arSourceSize, $arDestinationSize);
             if ($bNeedCreatePicture) {
                 $new_image = CTempFile::GetFileName(bx_basename($sourceFile));
                 CheckDirPath($new_image);
                 $im = new Imagick();
                 try {
                     $im->setSize($arDestinationSize["width"], $arDestinationSize["height"]);
                     $im->readImage($io->GetPhysicalName($sourceFile));
                     $im->setImageFileName($new_image);
                     $im->thumbnailImage($arDestinationSize["width"], $arDestinationSize["height"], true);
                     $im->writeImage();
                     $im->destroy();
                 } catch (ImagickException $e) {
                     $new_image = "";
                 }
                 if ($new_image != "") {
                     $sourceFile = $new_image;
                     $arSourceFileSizeTmp = CFile::GetImageSize($io->GetPhysicalName($sourceFile));
                 }
             }
         }
     }
     if ($io->Copy($sourceFile, $destinationFile)) {
         switch ($arSourceFileSizeTmp[2]) {
             case IMAGETYPE_GIF:
                 $sourceImage = imagecreatefromgif($io->GetPhysicalName($sourceFile));
                 $bHasAlpha = true;
                 break;
             case IMAGETYPE_PNG:
                 $sourceImage = imagecreatefrompng($io->GetPhysicalName($sourceFile));
                 $bHasAlpha = true;
                 break;
             case IMAGETYPE_BMP:
                 $sourceImage = CFile::ImageCreateFromBMP($io->GetPhysicalName($sourceFile));
                 $bHasAlpha = false;
                 break;
             default:
                 $sourceImage = imagecreatefromjpeg($io->GetPhysicalName($sourceFile));
                 $bHasAlpha = false;
                 break;
         }
         $sourceImageWidth = intval(imagesx($sourceImage));
         $sourceImageHeight = intval(imagesy($sourceImage));
         if ($sourceImageWidth > 0 && $sourceImageHeight > 0) {
             if ($arSize["width"] <= 0 || $arSize["height"] <= 0) {
                 $arSize["width"] = $sourceImageWidth;
                 $arSize["height"] = $sourceImageHeight;
             }
             CFile::ScaleImage($sourceImageWidth, $sourceImageHeight, $arSize, $resizeType, $bNeedCreatePicture, $arSourceSize, $arDestinationSize);
             if ($bNeedCreatePicture) {
                 if (CFile::IsGD2()) {
                     $picture = ImageCreateTrueColor($arDestinationSize["width"], $arDestinationSize["height"]);
                     if ($arSourceFileSizeTmp[2] == IMAGETYPE_PNG) {
                         $transparentcolor = imagecolorallocatealpha($picture, 0, 0, 0, 127);
                         imagefilledrectangle($picture, 0, 0, $arDestinationSize["width"], $arDestinationSize["height"], $transparentcolor);
                         imagealphablending($picture, false);
                         imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]);
                         imagealphablending($picture, true);
                     } elseif ($arSourceFileSizeTmp[2] == IMAGETYPE_GIF) {
                         imagepalettecopy($picture, $sourceImage);
                         //Save transparency for GIFs
                         $transparentcolor = imagecolortransparent($sourceImage);
                         if ($transparentcolor >= 0 && $transparentcolor < imagecolorstotal($sourceImage)) {
                             $RGB = imagecolorsforindex($sourceImage, $transparentcolor);
                             $transparentcolor = imagecolorallocate($picture, $RGB["red"], $RGB["green"], $RGB["blue"]);
                             imagecolortransparent($picture, $transparentcolor);
                             imagefilledrectangle($picture, 0, 0, $arDestinationSize["width"], $arDestinationSize["height"], $transparentcolor);
                         }
                         imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]);
                     } else {
                         imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]);
                     }
                 } else {
                     $picture = ImageCreate($arDestinationSize["width"], $arDestinationSize["height"]);
                     imagecopyresized($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]);
                 }
             } else {
                 $picture = $sourceImage;
             }
             if (is_array($arFilters)) {
                 foreach ($arFilters as $arFilter) {
                     $bNeedCreatePicture |= CFile::ApplyImageFilter($picture, $arFilter, $bHasAlpha);
                 }
             }
             if (is_array($arWaterMark)) {
                 $arWaterMark["name"] = "watermark";
                 $bNeedCreatePicture |= CFile::ApplyImageFilter($picture, $arWaterMark, $bHasAlpha);
             }
             if ($bNeedCreatePicture) {
                 if ($io->FileExists($destinationFile)) {
                     $io->Delete($destinationFile);
                 }
                 switch ($arSourceFileSizeTmp[2]) {
                     case IMAGETYPE_GIF:
                         imagegif($picture, $io->GetPhysicalName($destinationFile));
                         break;
                     case IMAGETYPE_PNG:
                         imagealphablending($picture, false);
                         imagesavealpha($picture, true);
                         imagepng($picture, $io->GetPhysicalName($destinationFile));
                         break;
                     default:
                         if ($arSourceFileSizeTmp[2] == IMAGETYPE_BMP) {
                             $destinationFile .= ".jpg";
                         }
                         if ($jpgQuality === false) {
                             $jpgQuality = intval(COption::GetOptionString('main', 'image_resize_quality', '95'));
                         }
                         if ($jpgQuality <= 0 || $jpgQuality > 100) {
                             $jpgQuality = 95;
                         }
                         imagejpeg($picture, $io->GetPhysicalName($destinationFile), $jpgQuality);
                         break;
                 }
                 imagedestroy($picture);
             }
         }
         return true;
     }
     return false;
 }
Exemple #7
0
 function EMailMessageAdd($arMessageFields, $ACTION_VARS)
 {
     $arActionVars = explode("&", $ACTION_VARS);
     $countAr = count($arActionVars);
     for ($i = 0; $i < $countAr; $i++) {
         $v = $arActionVars[$i];
         if ($pos = strpos($v, "=")) {
             ${substr($v, 0, $pos)} = urldecode(substr($v, $pos + 1));
         }
     }
     if (!CModule::IncludeModule("support")) {
         return false;
     }
     if (strlen($W_SUPPORT_SITE_ID) > 0) {
         $rs = CSite::GetByID($W_SUPPORT_SITE_ID);
         if ($ar = $rs->Fetch()) {
             $SITE_ID = $ar["LID"];
         }
     }
     if (strlen($SITE_ID) <= 0) {
         $SITE_ID = $arMessageFields["LID"];
     }
     $sourceMail = COption::GetOptionString("support", "SOURCE_MAIL");
     $dbr = CTicketDictionary::GetBySID($sourceMail, "SR", $SITE_ID);
     if (!($ar = $dbr->Fetch())) {
         return false;
     }
     $TICKET_SOURCE_ID = $ar["ID"];
     $ID = $arMessageFields["ID"];
     $message_email = strlen($arMessageFields["FIELD_REPLY_TO"]) > 0 ? $arMessageFields["FIELD_REPLY_TO"] : $arMessageFields["FIELD_FROM"];
     $message_email_addr = strtolower(CMailUtil::ExtractMailAddress($message_email));
     $TID = 0;
     $arSubjects = explode("\n", trim($W_SUPPORT_SUBJECT));
     $countAr = count($arSubjects);
     for ($i = 0; $i < $countAr; $i++) {
         $arSubjects[$i] = Trim($arSubjects[$i]);
         if (strlen($arSubjects[$i]) > 0) {
             if (preg_match("/" . $arSubjects[$i] . "/" . BX_UTF_PCRE_MODIFIER, $arMessageFields["SUBJECT"], $regs)) {
                 $TID = IntVal($regs[1]);
                 break;
             }
         }
     }
     if ($TID > 0) {
         $db_ticket = CTicket::GetByID($TID, $SITE_ID, "N", "N", "N");
         if ($ar_ticket = $db_ticket->Fetch()) {
             //check user email address limits
             if ($W_SUPPORT_SEC == "domain" || $W_SUPPORT_SEC == "email") {
                 $bEMailOK = false;
                 if ($TICKET_SOURCE_ID == $ar_ticket["SOURCE_ID"]) {
                     $ticket_email = strtolower(CMailUtil::ExtractMailAddress($ar_ticket["OWNER_SID"]));
                     if ($W_SUPPORT_SEC == "domain") {
                         $ticket_email = substr($ticket_email, strpos($ticket_email, "@"));
                     }
                     if (strpos($message_email_addr, $ticket_email) !== false) {
                         $bEMailOK = true;
                     }
                 }
                 if (!$bEMailOK && $ar_ticket["OWNER_USER_ID"] > 0) {
                     $db_user = CUser::GetByID($ar_ticket["OWNER_USER_ID"]);
                     if ($arUser = $db_user->Fetch()) {
                         $ticket_email = strtolower(CMailUtil::ExtractMailAddress($arUser["EMAIL"]));
                         if ($check_type == "domain") {
                             $ticket_email = substr($ticket_email, strpos($ticket_email, "@"));
                         }
                         if (strpos($message_email_addr, $ticket_email) !== false) {
                             $bEMailOK = true;
                         }
                     }
                 }
                 if (!$bEMailOK) {
                     $TID = 0;
                 }
             }
         } else {
             $TID = 0;
         }
     }
     //when message subject is empty - generate it from message body
     $title = trim($arMessageFields["SUBJECT"]);
     if (strlen($title) <= 0) {
         $title = trim($arMessageFields["BODY"]);
         $title = preg_replace("/[\n\r\t ]+/s" . BX_UTF_PCRE_MODIFIER, " ", $title);
         $title = substr($title, 0, 50);
     }
     $arFieldsTicket = array("CLOSE" => "N", "TITLE" => $title, "MESSAGE" => $arMessageFields["BODY"], "MESSAGE_AUTHOR_SID" => $message_email, "MESSAGE_SOURCE_SID" => "email", "MODIFIED_MODULE_NAME" => "mail", "EXTERNAL_ID" => $ID, "EXTERNAL_FIELD_1" => $arMessageFields["HEADER"]);
     if ($W_SUPPORT_USER_FIND == "Y") {
         $o = "LAST_LOGIN";
         $b = "DESC";
         $res = CUser::GetList($o, $b, array("ACTIVE" => "Y", "=EMAIL" => $message_email_addr));
         if (($arr = $res->Fetch()) && strtolower(CMailUtil::ExtractMailAddress($arr["EMAIL"])) == $message_email_addr) {
             $AUTHOR_USER_ID = $arr["ID"];
         }
     }
     // process attach files
     $arFILES = array();
     $rsAttach = CMailAttachment::GetList(array(), array("MESSAGE_ID" => $ID));
     while ($arAttach = $rsAttach->Fetch()) {
         // save from db to hdd
         $filename = CTempFile::GetFileName(md5(uniqid("")) . ".tmp");
         CheckDirPath($filename);
         if (file_put_contents($filename, $arAttach["FILE_DATA"]) !== false) {
             $arFILES[] = array("name" => $arAttach["FILE_NAME"], "type" => $arAttach["CONTENT_TYPE"], "size" => filesize($filename), "tmp_name" => $filename, "MODULE_ID" => "support");
         }
     }
     if (count($arFILES) > 0) {
         $arFieldsTicket["FILES"] = $arFILES;
     }
     $arFieldsTicket["CURRENT_USER_ID"] = null;
     if (intval($AUTHOR_USER_ID) > 0) {
         $resU = CUser::GetByID(intval($AUTHOR_USER_ID));
         if ($arU = $resU->Fetch()) {
             $arFieldsTicket["CURRENT_USER_ID"] = $arU["ID"];
         }
     }
     if ($TID > 0) {
         $arFieldsTicket["MESSAGE_AUTHOR_USER_ID"] = $AUTHOR_USER_ID;
         if ($W_SUPPORT_ADD_MESSAGE_AS_HIDDEN == "Y") {
             $arFieldsTicket["HIDDEN"] = "Y";
         }
         if ($arMessageFields["SPAM"] == "Y") {
             $arFieldsTicket["IS_SPAM"] = "Y";
         }
         $TID = CTicket::Set($arFieldsTicket, $MESSAGE_ID, $TID, "N");
     } else {
         $arFieldsTicket["SITE_ID"] = $SITE_ID;
         $arFieldsTicket["OWNER_USER_ID"] = $AUTHOR_USER_ID;
         $arFieldsTicket["OWNER_SID"] = $message_email;
         $arFieldsTicket["CREATED_MODULE_NAME"] = "mail";
         $arFieldsTicket["SOURCE_SID"] = "email";
         if ($arMessageFields["SPAM"] == "Y") {
             $arFieldsTicket["IS_SPAM"] = "Y";
         }
         if ($W_SUPPORT_CATEGORY > 0) {
             $arFieldsTicket["CATEGORY_ID"] = $W_SUPPORT_CATEGORY;
         }
         if ($W_SUPPORT_CRITICALITY > 0) {
             $arFieldsTicket["CRITICALITY_ID"] = $W_SUPPORT_CRITICALITY;
         }
         if (strlen(trim($arFieldsTicket["TITLE"])) <= 0) {
             $arFieldsTicket["TITLE"] = " ";
         }
         if (strlen(trim($arFieldsTicket["MESSAGE"])) <= 0) {
             $arFieldsTicket["MESSAGE"] = " ";
         }
         $TID = CTicket::Set($arFieldsTicket, $MESSAGE_ID, "", "N");
     }
 }
 function UnpackFileArchive($strfile, $path_to)
 {
     global $APPLICATION;
     $res = true;
     $arcname = CTempFile::GetFileName(md5(uniqid(rand(), true)) . '.tar.gz');
     CheckDirPath($arcname);
     if (file_put_contents($arcname, $strfile) !== false) {
         include_once dirname(__FILE__) . '/tar_gz.php';
         $ob = new CArchiver($arcname);
         CheckDirPath($_SERVER['DOCUMENT_ROOT'] . $path_to);
         $res = $ob->extractFiles($_SERVER['DOCUMENT_ROOT'] . $path_to);
         if (!$res && is_object($APPLICATION)) {
             $arErrors = $ob->GetErrors();
             if (count($arErrors)) {
                 $strError = "";
                 foreach ($arErrors as $error) {
                     $strError .= $error[1] . "<br>";
                 }
                 $e = new CApplicationException($strError);
                 $APPLICATION->ThrowException($e);
             }
         }
     }
     return $res;
 }
Exemple #9
0
$db_res = CLanguage::GetList($b = "sort", $o = "asc");
while ($res = $db_res->Fetch()) {
    $arLang[$res["LID"]] = $res;
    $arLangTitle["reference_id"][] = $res["LID"];
    $arLangTitle["reference"][] = htmlspecialcharsbx($res["NAME"]);
}
$bInitVars = false;
$bImportComplete = false;
$APPLICATION->SetTitle(GetMessage("SMILE_IMPORT_TITLE"));
$fileName = '';
if ($REQUEST_METHOD == "POST" && (strlen($save) > 0 || strlen($apply) > 0)) {
    $fileName = 'import' . $USER->GetID() . time() . '.zip';
    if (!check_bitrix_sessid()) {
        $arError[] = array("id" => "bad_sessid", "text" => GetMessage("ERROR_BAD_SESSID"));
    } elseif (!empty($_FILES["IMPORT"]["tmp_name"])) {
        $sUploadDir = CTempFile::GetDirectoryName(1);
        CheckDirPath($sUploadDir);
        $res = CFile::CheckFile($_FILES["IMPORT"], 500000, false, 'zip');
        if (strLen($res) > 0) {
            $arError[] = array("id" => "IMPORT", "text" => $res);
        } elseif (file_exists($sUploadDir . $fileName)) {
            $arError[] = array("id" => "IMPORT", "text" => GetMessage("ERROR_EXISTS_FILE"));
        } elseif (!@copy($_FILES["IMPORT"]["tmp_name"], $sUploadDir . $fileName)) {
            $arError[] = array("id" => "IMPORT", "text" => GetMessage("ERROR_COPY_FILE"));
        } else {
            @chmod($sUploadDir . $fileName, BX_FILE_PERMISSIONS);
        }
    } elseif (empty($_FILES["IMPORT"]["tmp_name"])) {
        $arError[] = array("id" => "IMPORT", "text" => GetMessage("ERROR_EXISTS_FILE"));
    }
    if (empty($arError)) {
Exemple #10
0
 function SocnetEMailMessageAdd($arMessageFields, $ACTION_VARS)
 {
     if (!is_array($arMessageFields["FORUM_EMAIL_FILTER"])) {
         return false;
     }
     if (!CModule::IncludeModule("socialnetwork")) {
         return false;
     }
     $arParams = $arMessageFields["FORUM_EMAIL_FILTER"];
     if (!CSocNetFeatures::IsActiveFeature(SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum")) {
         return false;
     }
     // Найдем кто отправитель
     $message_email = strlen($arMessageFields["FIELD_REPLY_TO"]) > 0 ? $arMessageFields["FIELD_REPLY_TO"] : $arMessageFields["FIELD_FROM"];
     $message_email_addr = strtolower(CMailUtil::ExtractMailAddress($message_email));
     $o = "LAST_LOGIN";
     $b = "DESC";
     $res = CUser::GetList($o, $b, array("ACTIVE" => "Y", "EMAIL" => $message_email_addr));
     if (($arUser = $res->Fetch()) && strtolower(CMailUtil::ExtractMailAddress($arUser["EMAIL"])) == $message_email_addr) {
         $AUTHOR_USER_ID = $arUser["ID"];
     } elseif ($arParams["NOT_MEMBER_POST"] == "Y") {
         $AUTHOR_USER_ID = false;
     } else {
         CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR1") . ": " . $message_email_addr));
         return false;
     }
     if ($arParams["NOT_MEMBER_POST"] != "Y") {
         // Проверим права доступа
         if (CSocNetFeaturesPerms::CanPerformOperation($AUTHOR_USER_ID, SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum", "full")) {
             $PERMISSION = "Y";
         } elseif (CSocNetFeaturesPerms::CanPerformOperation($AUTHOR_USER_ID, SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum", "newtopic")) {
             $PERMISSION = "M";
         } elseif (CSocNetFeaturesPerms::CanPerformOperation($AUTHOR_USER_ID, SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum", "answer")) {
             $PERMISSION = "I";
         } else {
             CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR2") . " " . $arUser["LOGIN"] . " [" . $AUTHOR_USER_ID . "] (" . $message_email_addr . ")"));
             return false;
         }
     }
     $body = $arMessageFields["BODY"];
     //$body = preg_replace("/(\r\n)+/", "\r\n", $body);
     $p = strpos($body, "\r\nFrom:");
     if ($p > 0) {
         $body = substr($body, 0, $p) . "\r\n[CUT]" . substr($body, $p) . "[/CUT]";
     }
     $subject = $arMessageFields["SUBJECT"];
     // обрежем все RE и FW
     $subject = trim(preg_replace('#^\\s*((RE[0-9\\[\\]]*:\\s*)|(FW:\\s*))+(.*)$#i', '\\4', $subject));
     if ($subject == '') {
         $subject = GetMessage("FORUM_MAIL_EMPTY_TOPIC_TITLE") . " " . rand();
     }
     // Найдем какая тема
     $arFields = array();
     $FORUM_ID = IntVal($arParams["FORUM_ID"]);
     $SOCNET_GROUP_ID = IntVal($arParams["SOCNET_GROUP_ID"]);
     $TOPIC_ID = 0;
     global $DB;
     if ($arMessageFields["IN_REPLY_TO"] != '') {
         $dbTopic = $DB->Query("SELECT FT.ID FROM b_forum_topic FT INNER JOIN b_forum_message FM ON FM.TOPIC_ID=FT.ID WHERE FM.XML_ID='" . $DB->ForSQL($arMessageFields["IN_REPLY_TO"], 255) . "' AND FT.FORUM_ID=" . $FORUM_ID . " AND FT.SOCNET_GROUP_ID=" . $SOCNET_GROUP_ID);
         if ($arTopic = $dbTopic->Fetch()) {
             $TOPIC_ID = $arTopic["ID"];
         }
     }
     if ($arParams["USE_SUBJECT"] == "Y" && $TOPIC_ID <= 0) {
         $dbTopic = $DB->Query("SELECT ID FROM b_forum_topic WHERE TITLE='" . $DB->ForSQL($subject, 255) . "' AND FORUM_ID=" . $FORUM_ID . " AND SOCNET_GROUP_ID=" . $SOCNET_GROUP_ID);
         // ограничить по старости?
         if ($arTopic = $dbTopic->Fetch()) {
             $TOPIC_ID = $arTopic["ID"];
         }
     }
     if ($AUTHOR_USER_ID > 0) {
         if ($TOPIC_ID < 0 && $PERMISSION <= "I") {
             CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR3") . " " . $arUser["LOGIN"] . " [" . $AUTHOR_USER_ID . "] (" . $message_email_addr . ")"));
             return false;
         }
         $bSHOW_NAME = true;
         $res = CForumUser::GetByUSER_ID($AUTHOR_USER_ID);
         if ($res) {
             $bSHOW_NAME = $res["SHOW_NAME"] == "Y";
         }
         if ($bSHOW_NAME) {
             $AUTHOR_NAME = $arUser["NAME"] . (strlen($arUser["NAME"]) <= 0 || strlen($arUser["LAST_NAME"]) <= 0 ? "" : " ") . $arUser["LAST_NAME"];
         }
         if (strlen(Trim($AUTHOR_NAME)) <= 0) {
             $AUTHOR_NAME = $arUser["LOGIN"];
         }
     } else {
         $AUTHOR_NAME = $arMessageFields["FIELD_FROM"];
         $arFields["AUTHOR_EMAIL"] = $arMessageFields["FIELD_FROM"];
     }
     $arFields["NEW_TOPIC"] = "N";
     if ($PERMISSION >= "Q") {
         $arFields["APPROVED"] = "Y";
     } else {
         $arFields["APPROVED"] = $arParams["MODERATION"] == "Y" ? "N" : "Y";
     }
     // Добавим новую тему
     if ($TOPIC_ID <= 0) {
         $arTopicFields = array("TITLE" => $subject, "FORUM_ID" => $FORUM_ID, "USER_START_ID" => $AUTHOR_USER_ID, "OWNER_ID" => $AUTHOR_USER_ID, "SOCNET_GROUP_ID" => $SOCNET_GROUP_ID);
         $arTopicFields["XML_ID"] = $arMessageFields["MSG_ID"];
         $arTopicFields["APPROVED"] = $arFields['APPROVED'];
         $arTopicFields["USER_START_NAME"] = $AUTHOR_NAME;
         $arTopicFields["LAST_POSTER_NAME"] = $AUTHOR_NAME;
         $TOPIC_ID = CForumTopic::Add($arTopicFields);
         if (IntVal($TOPIC_ID) <= 0) {
             CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR4")));
             return false;
         }
         $arFields["NEW_TOPIC"] = "Y";
     }
     // Добавим сообщение
     $arFields["POST_MESSAGE"] = $body;
     // Аттаченные файлы
     $arFILES = array();
     $rsAttach = CMailAttachment::GetList(array(), array("MESSAGE_ID" => $arMessageFields["ID"]));
     while ($arAttach = $rsAttach->Fetch()) {
         $filename = CTempFile::GetFileName(md5(uniqid("")) . ".tmp");
         CheckDirPath($filename);
         if (file_put_contents($filename, $arAttach["FILE_DATA"]) !== false) {
             $arFile = array("name" => $arAttach["FILE_NAME"], "type" => $arAttach["CONTENT_TYPE"], "size" => @filesize($filename), "tmp_name" => $filename, "MODULE_ID" => "forum");
             $arFilter = array("FORUM_ID" => $FORUM_ID);
             $arFiles = array($arFile);
             if (CForumFiles::CheckFields($arFiles, $arFilter)) {
                 $arFILES[] = $arFiles[0];
             } else {
                 $oError = $GLOBALS["APPLICATION"]->GetException();
                 CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR6") . " (" . $arAttach["FILE_NAME"] . "): " . ($oError && $oError->GetString() ? $oError->GetString() : "")));
             }
         }
     }
     if (count($arFILES) > 0) {
         $arFields["FILES"] = $arFILES;
     }
     $arFields["AUTHOR_NAME"] = $AUTHOR_NAME;
     $arFields["AUTHOR_ID"] = $AUTHOR_USER_ID;
     $arFields["FORUM_ID"] = $FORUM_ID;
     $arFields["TOPIC_ID"] = $TOPIC_ID;
     $arFields["XML_ID"] = $arMessageFields["MSG_ID"];
     $arFields["SOURCE_ID"] = "EMAIL";
     $arRes = array();
     if (!empty($arMessageFields["FIELD_FROM"])) {
         $arRes[] = "From: " . $arMessageFields["FIELD_FROM"];
     }
     if (!empty($arMessageFields["FIELD_TO"])) {
         $arRes[] = "To: " . $arMessageFields["FIELD_TO"];
     }
     if (!empty($arMessageFields["FIELD_CC"])) {
         $arRes[] = "Cc: " . $arMessageFields["FIELD_CC"];
     }
     if (!empty($arMessageFields["FIELD_BCC"])) {
         $arRes[] = "Bcc: " . $arMessageFields["FIELD_BCC"];
     }
     $arRes[] = "Subject: " . $arMessageFields["SUBJECT"];
     $arRes[] = "Date: " . $arMessageFields["FIELD_DATE"];
     $arFields["MAIL_HEADER"] = implode("\r\n", $arRes);
     preg_match_all('#Received:\\s+from\\s+(.*)by.*#i', $arMessageFields["HEADER"], $regs);
     if (is_array($regs) && is_array($regs[1])) {
         $arFields["AUTHOR_IP"] = $arFields["AUTHOR_REAL_IP"] = '<email: ' . $regs[1][count($regs[1]) - 1] . '>';
     } else {
         $arFields["AUTHOR_IP"] = $arFields["AUTHOR_REAL_IP"] = '<email: no address>';
     }
     /*
     
     $AUTHOR_IP = ForumGetRealIP();
     $AUTHOR_IP_tmp = $AUTHOR_IP;
     $AUTHOR_REAL_IP = $_SERVER['REMOTE_ADDR'];
     if (COption::GetOptionString("forum", "FORUM_GETHOSTBYADDR", "N") == "Y")
     {
     	$AUTHOR_IP = @gethostbyaddr($AUTHOR_IP);
     
     	if ($AUTHOR_IP_tmp==$AUTHOR_REAL_IP)
     		$AUTHOR_REAL_IP = $AUTHOR_IP;
     	else
     		$AUTHOR_REAL_IP = @gethostbyaddr($AUTHOR_REAL_IP);
     }
     
     $arFields["AUTHOR_IP"] = ($AUTHOR_IP!==False) ? $AUTHOR_IP : "<no address>";
     $arFields["AUTHOR_REAL_IP"] = ($AUTHOR_REAL_IP!==False) ? $AUTHOR_REAL_IP : "<no address>";
     */
     $strErrorMessage = '';
     $MESSAGE_ID = CForumMessage::Add($arFields, false);
     if (intVal($MESSAGE_ID) <= 0) {
         $str = $GLOBALS['APPLICATION']->GetException();
         if ($str && $str->GetString()) {
             $strErrorMessage .= "[" . $str->GetString() . "]";
         }
         if ($arFields["NEW_TOPIC"] == 'Y') {
             CForumTopic::Delete($TOPIC_ID);
         }
         CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR5") . " " . $strErrorMessage));
     }
     if ($MESSAGE_ID > 0) {
         CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_COMPLETE", "MESSAGE" => GetMessage("FORUM_MAIL_OK") . " " . $MESSAGE_ID . " (TID#" . $TOPIC_ID . ")"));
         CForumMessage::SendMailMessage($MESSAGE_ID, array(), false, "NEW_FORUM_MESSAGE");
         $dbSite = CSite::GetById($arMessageFields["LID"]);
         if ($arSite = $dbSite->Fetch()) {
             $lang = $arSite['LANGUAGE_ID'];
         } else {
             $lang = $LANGUAGE_ID;
         }
         $parser = new forumTextParser();
         $arForum = CForumNew::GetByID($FORUM_ID);
         $arAllow = array("HTML" => "N", "ANCHOR" => "N", "BIU" => "N", "IMG" => "N", "LIST" => "N", "QUOTE" => "N", "CODE" => "N", "FONT" => "N", "SMILES" => "N", "UPLOAD" => $arForum["ALLOW_UPLOAD"], "NL2BR" => "N", "TABLE" => "N", "ALIGN" => "N");
         if ($arFields["NEW_TOPIC"] == "Y") {
             $arFieldsForSocnet = array("ENTITY_TYPE" => SONET_ENTITY_GROUP, "ENTITY_ID" => $SOCNET_GROUP_ID, "EVENT_ID" => "forum", "=LOG_DATE" => $GLOBALS["DB"]->CurrentTimeFunction(), "TITLE_TEMPLATE" => str_replace("#AUTHOR_NAME#", $AUTHOR_NAME, CForumEmail::GetLangMessage("FORUM_MAIL_SOCNET_TITLE_TOPIC", $lang)), "TITLE" => $subject, "MESSAGE" => $parser->convert($body, $arAllow), "TEXT_MESSAGE" => $parser->convert4mail($body), "URL" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("UID" => $AUTHOR_USER_ID, "FID" => $FORUM_ID, "TID" => $TOPIC_ID, "MID" => $MESSAGE_ID)), "PARAMS" => serialize(array("PATH_TO_MESSAGE" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("TID" => $TOPIC_ID)))), "MODULE_ID" => false, "CALLBACK_FUNC" => false, "SOURCE_ID" => $MESSAGE_ID, "RATING_TYPE_ID" => "FORUM_TOPIC", "RATING_ENTITY_ID" => intval($TOPIC_ID));
             if (intVal($AUTHOR_USER_ID) > 0) {
                 $arFieldsForSocnet["USER_ID"] = $AUTHOR_USER_ID;
             }
             $logID = CSocNetLog::Add($arFieldsForSocnet, false);
             if (intval($logID) > 0) {
                 CSocNetLog::Update($logID, array("TMP_ID" => $logID));
                 CSocNetLogRights::SetForSonet($logID, $arFieldsForSocnet["ENTITY_TYPE"], $arFieldsForSocnet["ENTITY_ID"], "forum", "view", true);
                 CSocNetLog::SendEvent($logID, "SONET_NEW_EVENT", $logID);
             }
         } else {
             $dbForumMessage = CForumMessage::GetList(array("ID" => "ASC"), array("TOPIC_ID" => $TOPIC_ID));
             if ($arForumMessage = $dbForumMessage->Fetch()) {
                 $dbRes = CSocNetLog::GetList(array("ID" => "DESC"), array("EVENT_ID" => "forum", "SOURCE_ID" => $arForumMessage["ID"]), false, false, array("ID", "TMP_ID"));
                 if ($arRes = $dbRes->Fetch()) {
                     $log_id = $arRes["TMP_ID"];
                 } else {
                     $dbFirstMessage = CForumMessage::GetList(array("ID" => "ASC"), array("TOPIC_ID" => $arForumMessage["TOPIC_ID"]), false, 1);
                     if ($arFirstMessage = $dbFirstMessage->Fetch()) {
                         $arTopic = CForumTopic::GetByID($arFirstMessage["TOPIC_ID"]);
                         $sFirstMessageText = COption::GetOptionString("forum", "FILTER", "Y") == "Y" ? $arFirstMessage["POST_MESSAGE_FILTER"] : $arFirstMessage["POST_MESSAGE"];
                         $sFirstMessageURL = CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("UID" => $arFirstMessage["AUTHOR_ID"], "FID" => $arFirstMessage["FORUM_ID"], "TID" => $arFirstMessage["TOPIC_ID"], "MID" => $arFirstMessage["ID"]));
                         $arFieldsForSocnet = array("ENTITY_TYPE" => SONET_ENTITY_GROUP, "ENTITY_ID" => $SOCNET_GROUP_ID, "EVENT_ID" => "forum", "LOG_DATE" => $arFirstMessage["POST_DATE"], "LOG_UPDATE" => $arFirstMessage["POST_DATE"], "TITLE_TEMPLATE" => str_replace("#AUTHOR_NAME#", $arFirstMessage["AUTHOR_NAME"], GetMessage("SONET_FORUM_LOG_TOPIC_TEMPLATE")), "TITLE" => $arTopic["TITLE"], "MESSAGE" => $parser->convert($sFirstMessageText, $arAllow), "TEXT_MESSAGE" => $parser->convert4mail($sFirstMessageText), "URL" => $sFirstMessageURL, "PARAMS" => serialize(array("PATH_TO_MESSAGE" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("TID" => $arFirstMessage["TOPIC_ID"])))), "MODULE_ID" => false, "CALLBACK_FUNC" => false, "SOURCE_ID" => $arFirstMessage["ID"], "RATING_TYPE_ID" => "FORUM_TOPIC", "RATING_ENTITY_ID" => intval($arFirstMessage["TOPIC_ID"]));
                         if (intVal($arFirstMessage["AUTHOR_ID"]) > 0) {
                             $arFieldsForSocnet["USER_ID"] = $arFirstMessage["AUTHOR_ID"];
                         }
                         $log_id = CSocNetLog::Add($arFieldsForSocnet, false);
                         if (intval($log_id) > 0) {
                             CSocNetLog::Update($log_id, array("TMP_ID" => $log_id));
                             CSocNetLogRights::SetForSonet($log_id, $arFieldsForSocnet["ENTITY_TYPE"], $arFieldsForSocnet["ENTITY_ID"], "forum", "view", true);
                         }
                     }
                 }
                 if (intval($log_id) > 0) {
                     $arFieldsForSocnet = array("ENTITY_TYPE" => SONET_ENTITY_GROUP, "ENTITY_ID" => $SOCNET_GROUP_ID, "EVENT_ID" => "forum", "LOG_ID" => $log_id, "=LOG_DATE" => $GLOBALS["DB"]->CurrentTimeFunction(), "MESSAGE" => $parser->convert($body, $arAllow), "TEXT_MESSAGE" => $parser->convert4mail($body), "URL" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("UID" => $AUTHOR_USER_ID, "FID" => $FORUM_ID, "TID" => $TOPIC_ID, "MID" => $MESSAGE_ID)), "MODULE_ID" => false, "SOURCE_ID" => $MESSAGE_ID, "RATING_TYPE_ID" => "FORUM_POST", "RATING_ENTITY_ID" => intval($MESSAGE_ID));
                     if (intVal($AUTHOR_USER_ID) > 0) {
                         $arFieldsForSocnet["USER_ID"] = $AUTHOR_USER_ID;
                     }
                     CSocNetLogComments::Add($arFieldsForSocnet);
                 }
             }
         }
     }
 }
Exemple #11
0
         $arFilter["ID!"] = $ID;
     }
     $db_res = CIBlockSection::GetList(array(), $arFilter);
     if ($db_res && ($res = $db_res->Fetch())) {
         $arError = array("code" => "CODE_EXIST", "title" => GetMessage("P_ERROR_CODE_EXIST"));
     }
 }
 $arFiles = array();
 if (empty($arError) && !empty($_FILES["AVATAR"]) && !empty($_FILES["AVATAR"]["tmp_name"])) {
     include_once $_SERVER["DOCUMENT_ROOT"] . "/" . BX_PERSONAL_ROOT . "/components/bitrix/photogallery.upload/functions.php";
     $arRealFile = $_FILES["AVATAR"];
     $arAlbumSights = array("DETAIL_PICTURE" => array("code" => "album", "notes" => "for_album", "width" => $arParams["GALLERY_AVATAR"]["WIDTH"], "height" => $arParams["GALLERY_AVATAR"]["HEIGHT"]), "PICTURE" => array("code" => "album_thumbs", "notes" => "for_album", "width" => $arParams["GALLERY_AVATAR_THUMBS"]["WIDTH"], "height" => $arParams["GALLERY_AVATAR_THUMBS"]["HEIGHT"]));
     foreach ($arAlbumSights as $key => $Sight) {
         $File = $arRealFile;
         $File["name"] = "avatar_" . $Sight["code"] . $arRealFile["name"];
         $File["tmp_name"] = $File["tmp_name"] = CTempFile::GetFileName() . $File["name"];
         CFile::ResizeImageFile($arRealFile["tmp_name"], $File['tmp_name'], $Sight, BX_RESIZE_IMAGE_EXACT);
         $File["MODULE_ID"] = "iblock";
         $arFiles[$key] = $File;
     }
 }
 if (empty($arError)) {
     $arUserFields = $GLOBALS["USER_FIELD_MANAGER"]->GetUserFields("IBLOCK_" . $arParams["IBLOCK_ID"] . "_SECTION", 0, LANGUAGE_ID);
     if (empty($arUserFields) || empty($arUserFields["UF_DEFAULT"])) {
         $db_res = CUserTypeEntity::GetList(array($by => $order), array("ENTITY_ID" => "IBLOCK_" . $arParams["IBLOCK_ID"] . "_SECTION", "FIELD_NAME" => "UF_DEFAULT"));
         if (!$db_res || !($res = $db_res->GetNext())) {
             $arFields = array("ENTITY_ID" => "IBLOCK_" . $arParams["IBLOCK_ID"] . "_SECTION", "FIELD_NAME" => "UF_DEFAULT", "USER_TYPE_ID" => "string", "MULTIPLE" => "N", "MANDATORY" => "N");
             $arFieldName = array();
             $rsLanguage = CLanguage::GetList($by, $order, array());
             while ($arLanguage = $rsLanguage->Fetch()) {
                 if (LANGUAGE_ID == $arLanguage["LID"]) {
Exemple #12
0
 function AddAttachment($arFields)
 {
     global $DB;
     $strSql = "SELECT ATTACHMENTS FROM b_mail_message WHERE ID=" . IntVal($arFields["MESSAGE_ID"]);
     $dbr = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     if (!($dbr_arr = $dbr->Fetch())) {
         return false;
     }
     $n = IntVal($dbr_arr["ATTACHMENTS"]) + 1;
     if (strlen($arFields["FILE_NAME"]) <= 0) {
         $arFields["FILE_NAME"] = $n . ".";
         if (strpos($arFields["CONTENT_TYPE"], "message/") === 0) {
             $arFields["FILE_NAME"] .= "msg";
         } else {
             $arFields["FILE_NAME"] .= "tmp";
         }
     }
     if (is_set($arFields, "CONTENT_TYPE")) {
         $arFields["CONTENT_TYPE"] = strtolower($arFields["CONTENT_TYPE"]);
     }
     if (strpos($arFields["CONTENT_TYPE"], "image/") === 0 && (!is_set($arFields, "IMAGE_WIDTH") || !is_set($arFields, "IMAGE_HEIGHT")) && is_set($arFields, "FILE_DATA")) {
         $filename = CTempFile::GetFileName(md5(uniqid("")) . '.tmp');
         CheckDirPath($filename);
         if (file_put_contents($filename, $arFields["FILE_DATA"]) !== false) {
             $img_arr = CFile::GetImageSize($filename);
             $arFields["IMAGE_WIDTH"] = $img_arr ? $img_arr[0] : 0;
             $arFields["IMAGE_HEIGHT"] = $img_arr ? $img_arr[1] : 0;
         }
     }
     if (is_set($arFields, "FILE_DATA") && !is_set($arFields, "FILE_SIZE")) {
         $arFields["FILE_SIZE"] = CUtil::BinStrlen($arFields["FILE_DATA"]);
     }
     if (!CMailUtil::IsSizeAllowed(strlen($DB->ForSQL($arFields["FILE_DATA"])) + 100)) {
         return false;
     }
     $ID = $DB->Add("b_mail_msg_attachment", $arFields, array("FILE_DATA"));
     if ($ID > 0) {
         $strSql = "UPDATE b_mail_message SET ATTACHMENTS=" . $n . " WHERE ID=" . IntVal($arFields["MESSAGE_ID"]);
         $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     }
     return $ID;
     /*
     $arFile = Array(
     		"name"=>$filename,
     		"size"=>strlen($part["BODY"]),
     		"type"=>$part["CONTENT-TYPE"],
     		"content"=>$part["BODY"],
     		"MODULE_ID"=>"mail"
     	);
     $file_id = CFile::SaveFile($arFile, "mail");
     */
 }
 function Export($documentId)
 {
     $work_dir = CTempFile::GetDirectoryName();
     CheckDirPath($work_dir);
     $file = "import";
     $file_name = $work_dir . $file . ".xml";
     $file_dir = $file . "_files/";
     $arcname = $work_dir . $file . '.tar.gz';
     if ($fp = fopen($file_name, "ab")) {
         $documentService = $this->workflow->GetService("DocumentService");
         $document = $documentService->GetDocument($documentId);
         $obExport = new CIBlockCMLExport();
         $step = array();
         $PROPERTY_MAP = array();
         $SECTION_MAP = array();
         if ($obExport->Init($fp, $document["IBLOCK_ID"], $step, true, $work_dir, $file_dir)) {
             $obExport->StartExport();
             $obExport->StartExportMetadata();
             $obExport->ExportProperties($PROPERTY_MAP);
             $obExport->ExportSections($SECTION_MAP, time(), 0);
             $obExport->EndExportMetadata();
             $obExport->StartExportCatalog(true, true);
             $obExport->ExportElements($PROPERTY_MAP, $SECTION_MAP, time(), 0, 0, array("SHOW_NEW" => "Y", "IBLOCK_ID" => $document["IBLOCK_ID"], "=ID" => $document["ID"]));
             $obExport->EndExportCatalog();
             $obExport->EndExport();
             fclose($fp);
             include_once $_SERVER["DOCUMENT_ROOT"] . BX_ROOT . '/modules/main/classes/general/tar_gz.php';
             $ob = new CArchiver($arcname);
             $res = $ob->Add('"' . $file_name . '"', false, $work_dir);
             if ($res) {
                 $res = $ob->Add('"' . $work_dir . $file_dir . '"', false, $work_dir);
             }
             if ($res) {
                 return $arcname;
             } else {
                 return '';
             }
         } else {
             return '';
         }
     } else {
         return '';
     }
 }
 if ($arParams["PERMISSION"] >= "W" && ($object == "group" || $object == "user" && $arResult["VARIABLES"]["user_id"] == $USER->GetID())) {
     $arFiles = array();
     if ($object == "user") {
         $dbUser = CUser::GetByID($USER->GetID());
         $arResult["USER"] = $dbUser->GetNext();
         $arResult["USER"]["PERSONAL_PHOTO"] = intVal($arResult["USER"]["PERSONAL_PHOTO"]);
         if ($arResult["USER"]["PERSONAL_PHOTO"] > 0) {
             $arFile = CFile::MakeFileArray($arResult["USER"]["PERSONAL_PHOTO"]);
             if (is_array($arFile)) {
                 $arFile["name"] = preg_replace("/[^a-z_.1-9]/is", "_", $arFile["name"]);
                 include_once $_SERVER["DOCUMENT_ROOT"] . "/" . BX_PERSONAL_ROOT . "/components/bitrix/photogallery.upload/functions.php";
                 $arAlbumSights = array("DETAIL_PICTURE" => array("code" => "album", "notes" => "for_album", "width" => $arParams["PHOTO"]["ALL"]["GALLERY_AVATAR_SIZE"], "height" => $arParams["PHOTO"]["ALL"]["GALLERY_AVATAR_SIZE"]), "PICTURE" => array("code" => "album_thumbs", "notes" => "for_album", "width" => $arParams["PHOTO"]["ALL"]["GALLERY_AVATAR_THUMBS_SIZE"], "height" => $arParams["PHOTO"]["ALL"]["GALLERY_AVATAR_THUMBS_SIZE"]));
                 foreach ($arAlbumSights as $key => $Sight) {
                     $File = $arFile;
                     $File["name"] = "avatar_" . $Sight["code"] . $arFile["name"];
                     $File["tmp_name"] = CTempFile::GetFileName($File["name"]);
                     CheckDirPath($File["tmp_name"]);
                     $res = CFile::ResizeImageFile(CBXVirtualIo::GetInstance()->GetLogicalName($arFile["tmp_name"]), $File["tmp_name"], $Sight, BX_RESIZE_IMAGE_PROPORTIONAL_ALT);
                     $File["MODULE_ID"] = "iblock";
                     $arFiles[$key] = $File;
                 }
                 if ($arFile["image"]) {
                     @imagedestroy($arFile["image"]);
                 }
             }
         }
     }
     $arUserFields = $GLOBALS["USER_FIELD_MANAGER"]->GetUserFields("IBLOCK_" . $arParams["IBLOCK_ID"] . "_SECTION", 0, LANGUAGE_ID);
     if (empty($arUserFields) || empty($arUserFields["UF_DEFAULT"])) {
         $db_res = CUserTypeEntity::GetList(array($by => $order), array("ENTITY_ID" => "IBLOK_" . $arParams["IBLOCK_ID"] . "_SECTION", "FIELD_NAME" => "UF_DEFAULT"));
         if (!$db_res || !($res = $db_res->GetNext())) {
Exemple #15
0
        echo "success\n";
        echo session_name() . "\n";
        echo session_id() . "\n";
        echo bitrix_sessid_get() . "\n";
    }
} elseif (!check_bitrix_sessid()) {
    echo "failure\n", GetMessage("CC_BCIH_ERROR_SOURCE_CHECK");
} elseif (!$USER->IsAuthorized()) {
    echo "failure\n", GetMessage("CC_BCIH_ERROR_AUTHORIZE");
} elseif (!$bUSER_HAVE_ACCESS) {
    echo "failure\n", GetMessage("CC_BCIH_PERMISSION_DENIED");
} elseif (!CModule::IncludeModule('highloadblock')) {
    echo "failure\n", GetMessage("CC_BCIH_ERROR_MODULE");
} elseif ($_GET["mode"] == "init") {
    if ($arParams["USE_TEMP_DIR"] === "Y") {
        $DIR_NAME = CTempFile::GetDirectoryName(6, "1c_highloadblock");
    } else {
        //Cleanup previous import files
        $directory = new \Bitrix\Main\IO\Directory($DIR_NAME);
        if ($directory->isExists()) {
            $directory->delete();
        }
    }
    CheckDirPath($DIR_NAME);
    if (!is_dir($DIR_NAME)) {
        echo "failure\n", GetMessage("CC_BCIH_ERROR_INIT");
    } else {
        $_SESSION["BX_HL_IMPORT"] = array("zip" => $arParams["USE_ZIP"] && function_exists("zip_open"), "TEMP_DIR" => $arParams["USE_TEMP_DIR"] === "Y" ? $DIR_NAME : "", "NS" => array("XMLPOS" => "", "SESSID" => md5($_REQUEST["sessid"])));
        echo "zip=" . ($_SESSION["BX_HL_IMPORT"]["zip"] ? "yes" : "no") . "\n";
        echo "file_limit=" . $arParams["FILE_SIZE_LIMIT"];
    }
Exemple #16
0
 /**
  * <p>Функция выполняет масштабирование файла.</p> <p><b>Примечание</b>: обрабатываются только файлы JPEG, GIF и PNG (зависит от используемой библиотеки GD). Файл указанный в параметре arFile будет перезаписан. <br></p>
  *
  *
  *
  *
  * @param array $arFile  Массив описывающий файл. Это может быть элемент массива $_FILES[имя]
  * (или $HTTP_POST_FILES[имя]), а также результат функции <a
  * href="http://dev.1c-bitrix.ru/api_help/main/reference/cfile/makefilearray.php">CFile::MakeFileArray</a>.
  *
  *
  *
  * @param array $arResize  Массив параметров масштабирования. Содержит следующие ключи:
  * <br><ul> <li>WIDTH - целое число. Размер картинки будет изменен таким
  * образом, что ее ширина не будет превышать значения этого поля. <br>
  * </li> <li>HEIGHT - целое число. Размер картинки будет изменен таким
  * образом, что ее высота не будет превышать значения этого поля. </li>
  * <li>METHOD - возможные значения: resample или пусто. Значение поля равное
  * "resample" приведет к использованию функции масштабирования
  * imagecopyresampled, а не imagecopyresized. Это более качественный метод, но требует
  * больше серверных ресурсов. <br> </li> <li>COMPRESSION - целое от 0 до 100. Если
  * значение больше 0, то для изображений jpeg оно будет использовано
  * как параметр компрессии. 100 соответствует наилучшему качеству
  * при большем размере файла. </li> </ul> Параметры METHOD и COMPRESSION
  * применяются только если происходит изменение размера. Если
  * картинка вписывается в ограничения WIDTH и HEIGHT, то никаких действий
  * над файлом выполнено не будет. <br><br>
  *
  *
  *
  * @return array <p>Массив описывающий файл или строка с сообщением об ошибке.</p>
  *
  *
  * <h4>Example</h4> 
  * <pre>
  * &lt;?<br>AddEventHandler("iblock", "OnBeforeIBlockElementAdd", Array("MyHandlers", "ResizeElementProperty"));<br>AddEventHandler("iblock", "OnBeforeIBlockElementUpdate", Array("MyHandlers", "ResizeElementProperty"));<br><br>class MyHandlers<br>{<br>	function ResizeElementProperty(&amp;$arFields)<br>	{<br>		global $APPLICATION;<br>		//Код инфоблока свойство каторого нуждается в масштабировании<br>		$IBLOCK_ID = 1;<br>		//Идентификатор свойства<br>		$PROPERTY_ID = 15;<br>		//Наш инфоблок и значения свойства в наличии<br>		if(<br>			$arFields["IBLOCK_ID"] == $IBLOCK_ID<br>			&amp;&amp; is_array($arFields["PROPERTY_VALUES"])<br>			&amp;&amp; array_key_exists(15, $arFields["PROPERTY_VALUES"])<br>		)<br>		{<br>			foreach($arFields["PROPERTY_VALUES"][$PROPERTY_ID] as $key =&gt; $arFile)<br>			{<br>				//Изменяем размеры картинки<br>				$arNewFile = CIBlock::ResizePicture($arFile, array(<br>					"WIDTH" =&gt; 100,<br>					"HEIGHT" =&gt; 100,<br>					"METHOD" =&gt; "resample",<br>				));<br>				if(is_array($arNewFile))<br>					$arFields["PROPERTY_VALUES"][$PROPERTY_ID][$key] = $arNewFile;<br>				else<br>				{<br>					//Можно вернуть ошибку<br>					$APPLICATION-&gt;throwException("Ошибка масштабирования изображения в свойстве \"Файлы\":".$arNewFile);<br>					return false;<br>				}<br>			}<br>		}<br>	}<br>}<br>?&gt;
  * </pre>
  *
  *
  *
  * <h4>See Also</h4> 
  * <ul> <li><a href="http://dev.1c-bitrix.ru/api_help/main/reference/cfile/makefilearray.php">CFile::MakeFileArray</a></li>
  * <li><a href="http://dev.1c-bitrix.ru/api_help/iblock/classes/ciblock/SetFields.php">CIBlock::SetFields</a></li> </ul><a
  * name="examples"></a>
  *
  *
  * @static
  * @link http://dev.1c-bitrix.ru/api_help/iblock/classes/ciblock/ResizePicture.php
  * @author Bitrix
  */
 public static function ResizePicture($arFile, $arResize)
 {
     if (strlen($arFile["tmp_name"]) <= 0) {
         return $arFile;
     }
     if (array_key_exists("error", $arFile) && $arFile["error"] !== 0) {
         return GetMessage("IBLOCK_BAD_FILE_ERROR");
     }
     $file = $arFile["tmp_name"];
     if (!file_exists($file) && !is_file($file)) {
         return GetMessage("IBLOCK_BAD_FILE_NOT_FOUND");
     }
     $width = intval($arResize["WIDTH"]);
     $height = intval($arResize["HEIGHT"]);
     if ($width <= 0 && $height <= 0) {
         return $arFile;
     }
     $orig = CFile::GetImageSize($file, true);
     if (!is_array($orig)) {
         return GetMessage("IBLOCK_BAD_FILE_NOT_PICTURE");
     }
     if ($width > 0 && $orig[0] > $width || $height > 0 && $orig[1] > $height) {
         if ($arFile["COPY_FILE"] == "Y") {
             $new_file = CTempFile::GetFileName(basename($file));
             CheckDirPath($new_file);
             $arFile["copy"] = true;
             if (copy($file, $new_file)) {
                 $file = $new_file;
             } else {
                 return GetMessage("IBLOCK_BAD_FILE_NOT_FOUND");
             }
         }
         $width_orig = $orig[0];
         $height_orig = $orig[1];
         if ($width <= 0) {
             $width = $width_orig;
         }
         if ($height <= 0) {
             $height = $height_orig;
         }
         $height_new = $height_orig;
         if ($width_orig > $width) {
             $height_new = $width / $width_orig * $height_orig;
         }
         if ($height_new > $height) {
             $width = $height / $height_orig * $width_orig;
         } else {
             $height = $height_new;
         }
         $image_type = $orig[2];
         if ($image_type == IMAGETYPE_JPEG) {
             $image = imagecreatefromjpeg($file);
         } elseif ($image_type == IMAGETYPE_GIF) {
             $image = imagecreatefromgif($file);
         } elseif ($image_type == IMAGETYPE_PNG) {
             $image = imagecreatefrompng($file);
         } else {
             return GetMessage("IBLOCK_BAD_FILE_UNSUPPORTED");
         }
         $image_p = imagecreatetruecolor($width, $height);
         if ($image_type == IMAGETYPE_JPEG) {
             if ($arResize["METHOD"] === "resample") {
                 imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
             } else {
                 imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
             }
             if ($arResize["COMPRESSION"] > 0) {
                 imagejpeg($image_p, $file, $arResize["COMPRESSION"]);
             } else {
                 imagejpeg($image_p, $file);
             }
         } elseif ($image_type == IMAGETYPE_GIF && function_exists("imagegif")) {
             imagetruecolortopalette($image_p, true, imagecolorstotal($image));
             imagepalettecopy($image_p, $image);
             //Save transparency for GIFs
             $transparentColor = imagecolortransparent($image);
             if ($transparentColor >= 0 && $transparentColor < imagecolorstotal($image)) {
                 $transparentColor = imagecolortransparent($image_p, $transparentColor);
                 imagefilledrectangle($image_p, 0, 0, $width, $height, $transparentColor);
             }
             if ($arResize["METHOD"] === "resample") {
                 imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
             } else {
                 imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
             }
             imagegif($image_p, $file);
         } else {
             //Save transparency for PNG
             $transparentColor = imagecolorallocatealpha($image_p, 0, 0, 0, 127);
             imagefilledrectangle($image_p, 0, 0, $width, $height, $transparentColor);
             $transparentColor = imagecolortransparent($image_p, $transparentColor);
             imagealphablending($image_p, false);
             if ($arResize["METHOD"] === "resample") {
                 imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
             } else {
                 imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
             }
             imagesavealpha($image_p, true);
             imagepng($image_p, $file);
         }
         imagedestroy($image);
         imagedestroy($image_p);
         $arFile["size"] = filesize($file);
         $arFile["tmp_name"] = $file;
         return $arFile;
     } else {
         return $arFile;
     }
 }
Exemple #17
0
 function Update($ID, $arFields, $bResort = true, $bUpdateSearch = true, $bResizePictures = false)
 {
     global $USER, $DB, $APPLICATION;
     $ID = intval($ID);
     $db_record = CIBlockSection::GetList(array(), array("ID" => $ID, "CHECK_PERMISSIONS" => "N"));
     if (!($db_record = $db_record->Fetch())) {
         return false;
     }
     if (is_set($arFields, "EXTERNAL_ID")) {
         $arFields["XML_ID"] = $arFields["EXTERNAL_ID"];
     }
     unset($arFields["GLOBAL_ACTIVE"]);
     unset($arFields["DEPTH_LEVEL"]);
     unset($arFields["LEFT_MARGIN"]);
     unset($arFields["RIGHT_MARGIN"]);
     unset($arFields["IBLOCK_ID"]);
     unset($arFields["DATE_CREATE"]);
     unset($arFields["CREATED_BY"]);
     $arIBlock = CIBlock::GetArrayByID($db_record["IBLOCK_ID"]);
     if ($bResizePictures) {
         $arDef = $arIBlock["FIELDS"]["SECTION_PICTURE"]["DEFAULT_VALUE"];
         if ($arDef["DELETE_WITH_DETAIL"] === "Y" && $arFields["DETAIL_PICTURE"]["del"] === "Y") {
             $arFields["PICTURE"]["del"] = "Y";
         }
         if ($arDef["FROM_DETAIL"] === "Y" && ($arFields["PICTURE"]["size"] <= 0 || $arDef["UPDATE_WITH_DETAIL"] === "Y") && is_array($arFields["DETAIL_PICTURE"]) && $arFields["DETAIL_PICTURE"]["size"] > 0) {
             if ($arFields["PICTURE"]["del"] !== "Y" && $arDef["UPDATE_WITH_DETAIL"] !== "Y") {
                 $arOldSection = $db_record;
             } else {
                 $arOldSection = false;
             }
             if (!$arOldSection || !$arOldSection["PICTURE"]) {
                 $arNewPreview = $arFields["DETAIL_PICTURE"];
                 $arNewPreview["COPY_FILE"] = "Y";
                 $arNewPreview["description"] = $arFields["PICTURE"]["description"];
                 $arFields["PICTURE"] = $arNewPreview;
             }
         }
         if (array_key_exists("PICTURE", $arFields) && is_array($arFields["PICTURE"]) && $arFields["PICTURE"]["size"] > 0 && $arDef["SCALE"] === "Y") {
             $arNewPicture = CIBlock::ResizePicture($arFields["PICTURE"], $arDef);
             if (is_array($arNewPicture)) {
                 $arNewPicture["description"] = $arFields["PICTURE"]["description"];
                 $arFields["PICTURE"] = $arNewPicture;
             } elseif ($arDef["IGNORE_ERRORS"] !== "Y") {
                 unset($arFields["PICTURE"]);
                 $strWarning .= GetMessage("IBLOCK_FIELD_PREVIEW_PICTURE") . ": " . $arNewPicture . "<br>";
             }
         }
         if (array_key_exists("PICTURE", $arFields) && is_array($arFields["PICTURE"]) && $arDef["USE_WATERMARK_FILE"] === "Y") {
             if (strlen($arFields["PICTURE"]["tmp_name"]) > 0 && $arFields["PICTURE"]["tmp_name"] === $arFields["DETAIL_PICTURE"]["tmp_name"]) {
                 $arFields["PICTURE"]["tmp_name"] = CTempFile::GetFileName(basename($arFields["PICTURE"]["tmp_name"]));
                 CheckDirPath($arFields["PICTURE"]["tmp_name"]);
                 copy($arFields["DETAIL_PICTURE"]["tmp_name"], $arFields["PICTURE"]["tmp_name"]);
             }
             CIBLock::FilterPicture($arFields["PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_FILE_POSITION"], "type" => "file", "size" => "real", "alpha_level" => 100 - min(max($arDef["WATERMARK_FILE_ALPHA"], 0), 100), "file" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_FILE"])));
         }
         if (array_key_exists("PICTURE", $arFields) && is_array($arFields["PICTURE"]) && $arDef["USE_WATERMARK_TEXT"] === "Y") {
             if (strlen($arFields["PICTURE"]["tmp_name"]) > 0 && $arFields["PICTURE"]["tmp_name"] === $arFields["DETAIL_PICTURE"]["tmp_name"]) {
                 $arFields["PICTURE"]["tmp_name"] = CTempFile::GetFileName(basename($arFields["PICTURE"]["tmp_name"]));
                 CheckDirPath($arFields["PICTURE"]["tmp_name"]);
                 copy($arFields["DETAIL_PICTURE"]["tmp_name"], $arFields["PICTURE"]["tmp_name"]);
             }
             CIBLock::FilterPicture($arFields["PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_TEXT_POSITION"], "type" => "text", "coefficient" => $arDef["WATERMARK_TEXT_SIZE"], "text" => $arDef["WATERMARK_TEXT"], "font" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_TEXT_FONT"]), "color" => $arDef["WATERMARK_TEXT_COLOR"]));
         }
         $arDef = $arIBlock["FIELDS"]["SECTION_DETAIL_PICTURE"]["DEFAULT_VALUE"];
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["SCALE"] === "Y") {
             $arNewPicture = CIBlock::ResizePicture($arFields["DETAIL_PICTURE"], $arDef);
             if (is_array($arNewPicture)) {
                 $arNewPicture["description"] = $arFields["DETAIL_PICTURE"]["description"];
                 $arFields["DETAIL_PICTURE"] = $arNewPicture;
             } elseif ($arDef["IGNORE_ERRORS"] !== "Y") {
                 unset($arFields["DETAIL_PICTURE"]);
                 $strWarning .= GetMessage("IBLOCK_FIELD_DETAIL_PICTURE") . ": " . $arNewPicture . "<br>";
             }
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["USE_WATERMARK_FILE"] === "Y") {
             if (strlen($arFields["DETAIL_PICTURE"]["tmp_name"]) > 0 && $arFields["DETAIL_PICTURE"]["tmp_name"] === $arFields["PICTURE"]["tmp_name"]) {
                 $arFields["DETAIL_PICTURE"]["tmp_name"] = CTempFile::GetFileName(basename($arFields["DETAIL_PICTURE"]["tmp_name"]));
                 CheckDirPath($arFields["DETAIL_PICTURE"]["tmp_name"]);
                 copy($arFields["PICTURE"]["tmp_name"], $arFields["DETAIL_PICTURE"]["tmp_name"]);
             }
             CIBLock::FilterPicture($arFields["DETAIL_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_FILE_POSITION"], "type" => "file", "size" => "real", "alpha_level" => 100 - min(max($arDef["WATERMARK_FILE_ALPHA"], 0), 100), "file" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_FILE"]), "fill" => "resize"));
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["USE_WATERMARK_TEXT"] === "Y") {
             if (strlen($arFields["DETAIL_PICTURE"]["tmp_name"]) > 0 && $arFields["DETAIL_PICTURE"]["tmp_name"] === $arFields["PICTURE"]["tmp_name"]) {
                 $arFields["DETAIL_PICTURE"]["tmp_name"] = CTempFile::GetFileName(basename($arFields["DETAIL_PICTURE"]["tmp_name"]));
                 CheckDirPath($arFields["DETAIL_PICTURE"]["tmp_name"]);
                 copy($arFields["PICTURE"]["tmp_name"], $arFields["DETAIL_PICTURE"]["tmp_name"]);
             }
             CIBLock::FilterPicture($arFields["DETAIL_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_TEXT_POSITION"], "type" => "text", "coefficient" => $arDef["WATERMARK_TEXT_SIZE"], "text" => $arDef["WATERMARK_TEXT"], "font" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_TEXT_FONT"]), "color" => $arDef["WATERMARK_TEXT_COLOR"]));
         }
     }
     if (is_set($arFields, "PICTURE")) {
         if (strlen($arFields["PICTURE"]["name"]) <= 0 && strlen($arFields["PICTURE"]["del"]) <= 0) {
             unset($arFields["PICTURE"]);
         } else {
             $arFields["PICTURE"]["old_file"] = $db_record["PICTURE"];
             $arFields["PICTURE"]["MODULE_ID"] = "iblock";
         }
     }
     if (is_set($arFields, "DETAIL_PICTURE")) {
         if (strlen($arFields["DETAIL_PICTURE"]["name"]) <= 0 && strlen($arFields["DETAIL_PICTURE"]["del"]) <= 0) {
             unset($arFields["DETAIL_PICTURE"]);
         } else {
             $arFields["DETAIL_PICTURE"]["old_file"] = $db_record["DETAIL_PICTURE"];
             $arFields["DETAIL_PICTURE"]["MODULE_ID"] = "iblock";
         }
     }
     if (is_set($arFields, "ACTIVE") && $arFields["ACTIVE"] != "Y") {
         $arFields["ACTIVE"] = "N";
     }
     if (is_set($arFields, "DESCRIPTION_TYPE") && $arFields["DESCRIPTION_TYPE"] != "html") {
         $arFields["DESCRIPTION_TYPE"] = "text";
     }
     if (isset($arFields["IBLOCK_SECTION_ID"])) {
         $arFields["IBLOCK_SECTION_ID"] = intval($arFields["IBLOCK_SECTION_ID"]);
         if ($arFields["IBLOCK_SECTION_ID"] <= 0) {
             $arFields["IBLOCK_SECTION_ID"] = false;
         }
     }
     $DESC_tmp = is_set($arFields, "DESCRIPTION") ? $arFields["DESCRIPTION"] : $db_record["DESCRIPTION"];
     $DESC_TYPE_tmp = is_set($arFields, "DESCRIPTION_TYPE") ? $arFields["DESCRIPTION_TYPE"] : $db_record["DESCRIPTION_TYPE"];
     $arFields["SEARCHABLE_CONTENT"] = ToUpper((is_set($arFields, "NAME") ? $arFields["NAME"] : $db_record["NAME"]) . "\r\n" . ($DESC_TYPE_tmp == "html" ? HTMLToTxt($DESC_tmp) : $DESC_tmp));
     if (is_object($USER)) {
         if (!isset($arFields["MODIFIED_BY"]) || intval($arFields["MODIFIED_BY"]) <= 0) {
             $arFields["MODIFIED_BY"] = intval($USER->GetID());
         }
     }
     if (!$this->CheckFields($arFields, $ID)) {
         $Result = false;
         $arFields["RESULT_MESSAGE"] =& $this->LAST_ERROR;
     } elseif (!$GLOBALS["USER_FIELD_MANAGER"]->CheckFields("IBLOCK_" . $db_record["IBLOCK_ID"] . "_SECTION", $ID, $arFields)) {
         $Result = false;
         $err = $APPLICATION->GetException();
         if (is_object($err)) {
             $this->LAST_ERROR .= str_replace("<br><br>", "<br>", $err->GetString() . "<br>");
         }
         $arFields["RESULT_MESSAGE"] =& $this->LAST_ERROR;
     } else {
         if (array_key_exists("PICTURE", $arFields)) {
             $SAVED_PICTURE = $arFields["PICTURE"];
             CFile::SaveForDB($arFields, "PICTURE", "iblock");
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields)) {
             $SAVED_DETAIL_PICTURE = $arFields["DETAIL_PICTURE"];
             CFile::SaveForDB($arFields, "DETAIL_PICTURE", "iblock");
         }
         unset($arFields["ID"]);
         $strUpdate = $DB->PrepareUpdate("b_iblock_section", $arFields, "iblock");
         if (array_key_exists("PICTURE", $arFields)) {
             $arFields["PICTURE"] = $SAVED_PICTURE;
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields)) {
             $arFields["DETAIL_PICTURE"] = $SAVED_DETAIL_PICTURE;
         }
         CIBlock::_transaction_lock($db_record["IBLOCK_ID"]);
         if (strlen($strUpdate) > 0) {
             $strSql = "UPDATE b_iblock_section SET " . $strUpdate . " WHERE ID = " . $ID;
             $arBinds = array();
             if (array_key_exists("DESCRIPTION", $arFields)) {
                 $arBinds["DESCRIPTION"] = $arFields["DESCRIPTION"];
             }
             if (array_key_exists("SEARCHABLE_CONTENT", $arFields)) {
                 $arBinds["SEARCHABLE_CONTENT"] = $arFields["SEARCHABLE_CONTENT"];
             }
             $DB->QueryBind($strSql, $arBinds);
         }
         if ($bResort) {
             //Move inside the tree
             if (isset($arFields["SORT"]) && $arFields["SORT"] != $db_record["SORT"] || isset($arFields["NAME"]) && $arFields["NAME"] != $db_record["NAME"] || isset($arFields["IBLOCK_SECTION_ID"]) && $arFields["IBLOCK_SECTION_ID"] != $db_record["IBLOCK_SECTION_ID"]) {
                 //First "delete" from the tree
                 $distance = intval($db_record["RIGHT_MARGIN"]) - intval($db_record["LEFT_MARGIN"]) + 1;
                 $DB->Query("\n\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t,LEFT_MARGIN = -LEFT_MARGIN\n\t\t\t\t\t\t\t,RIGHT_MARGIN = -RIGHT_MARGIN\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tIBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\tAND LEFT_MARGIN >= " . intval($db_record["LEFT_MARGIN"]) . "\n\t\t\t\t\t\t\tAND LEFT_MARGIN <= " . intval($db_record["RIGHT_MARGIN"]) . "\n\t\t\t\t\t");
                 $DB->Query("\n\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t,RIGHT_MARGIN = RIGHT_MARGIN - " . $distance . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tIBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\tAND RIGHT_MARGIN > " . $db_record["RIGHT_MARGIN"] . "\n\t\t\t\t\t");
                 $DB->Query("\n\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t,LEFT_MARGIN = LEFT_MARGIN - " . $distance . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tIBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\tAND LEFT_MARGIN > " . $db_record["LEFT_MARGIN"] . "\n\t\t\t\t\t");
                 //Next insert into the the tree almost as we do when inserting the new one
                 $PARENT_ID = isset($arFields["IBLOCK_SECTION_ID"]) ? intval($arFields["IBLOCK_SECTION_ID"]) : intval($db_record["IBLOCK_SECTION_ID"]);
                 $NAME = isset($arFields["NAME"]) ? $arFields["NAME"] : $db_record["NAME"];
                 $SORT = isset($arFields["SORT"]) ? intval($arFields["SORT"]) : intval($db_record["SORT"]);
                 $arParents = array();
                 $strSql = "\n\t\t\t\t\t\tSELECT BS.ID, BS.ACTIVE, BS.GLOBAL_ACTIVE, BS.DEPTH_LEVEL, BS.LEFT_MARGIN, BS.RIGHT_MARGIN\n\t\t\t\t\t\tFROM b_iblock_section BS\n\t\t\t\t\t\tWHERE BS.IBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\tAND BS.ID in (" . intval($db_record["IBLOCK_SECTION_ID"]) . ", " . $PARENT_ID . ")\n\t\t\t\t\t";
                 $rsParents = $DB->Query($strSql);
                 while ($arParent = $rsParents->Fetch()) {
                     $arParents[$arParent["ID"]] = $arParent;
                 }
                 //Find rightmost child of the parent
                 $strSql = "\n\t\t\t\t\t\tSELECT BS.ID, BS.RIGHT_MARGIN, BS.DEPTH_LEVEL\n\t\t\t\t\t\tFROM b_iblock_section BS\n\t\t\t\t\t\tWHERE BS.IBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\tAND " . ($PARENT_ID > 0 ? "BS.IBLOCK_SECTION_ID=" . $PARENT_ID : "BS.IBLOCK_SECTION_ID IS NULL") . "\n\t\t\t\t\t\tAND (\n\t\t\t\t\t\t\t(BS.SORT < " . $SORT . ")\n\t\t\t\t\t\t\tOR (BS.SORT = " . $SORT . " AND BS.NAME < '" . $DB->ForSQL($NAME) . "')\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND BS.ID <> " . $ID . "\n\t\t\t\t\t\tORDER BY BS.SORT DESC, BS.NAME DESC\n\t\t\t\t\t";
                 $rsChild = $DB->Query($strSql);
                 if ($arChild = $rsChild->Fetch()) {
                     //We found the left neighbour
                     $arUpdate = array("LEFT_MARGIN" => intval($arChild["RIGHT_MARGIN"]) + 1, "DEPTH_LEVEL" => intval($arChild["DEPTH_LEVEL"]));
                 } else {
                     //If we have parent, when take its left_margin
                     if (isset($arParents[$PARENT_ID]) && $arParents[$PARENT_ID]) {
                         $arUpdate = array("LEFT_MARGIN" => intval($arParents[$PARENT_ID]["LEFT_MARGIN"]) + 1, "DEPTH_LEVEL" => intval($arParents[$PARENT_ID]["DEPTH_LEVEL"]) + 1);
                     } else {
                         //We are only one/leftmost section in the iblock.
                         $arUpdate = array("LEFT_MARGIN" => 1, "DEPTH_LEVEL" => 1);
                     }
                 }
                 $move_distance = intval($db_record["LEFT_MARGIN"]) - $arUpdate["LEFT_MARGIN"];
                 $DB->Query("\n\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t,LEFT_MARGIN = LEFT_MARGIN + " . $distance . "\n\t\t\t\t\t\t\t,RIGHT_MARGIN = RIGHT_MARGIN + " . $distance . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tIBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\tAND LEFT_MARGIN >= " . $arUpdate["LEFT_MARGIN"] . "\n\t\t\t\t\t");
                 $DB->Query("\n\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t,LEFT_MARGIN = -LEFT_MARGIN - " . $move_distance . "\n\t\t\t\t\t\t\t,RIGHT_MARGIN = -RIGHT_MARGIN - " . $move_distance . "\n\t\t\t\t\t\t\t" . ($arUpdate["DEPTH_LEVEL"] != intval($db_record["DEPTH_LEVEL"]) ? ",DEPTH_LEVEL = DEPTH_LEVEL - " . ($db_record["DEPTH_LEVEL"] - $arUpdate["DEPTH_LEVEL"]) : "") . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tIBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\tAND LEFT_MARGIN <= " . -intval($db_record["LEFT_MARGIN"]) . "\n\t\t\t\t\t\t\tAND LEFT_MARGIN >= " . -intval($db_record["RIGHT_MARGIN"]) . "\n\t\t\t\t\t");
                 if (isset($arParents[$PARENT_ID])) {
                     $DB->Query("\n\t\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t\t,RIGHT_MARGIN = RIGHT_MARGIN + " . $distance . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tIBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\t\tAND LEFT_MARGIN <= " . $arParents[$PARENT_ID]["LEFT_MARGIN"] . "\n\t\t\t\t\t\t\t\tAND RIGHT_MARGIN >= " . $arParents[$PARENT_ID]["RIGHT_MARGIN"] . "\n\t\t\t\t\t\t");
                 }
             }
             //Check if parent was changed
             if (isset($arFields["IBLOCK_SECTION_ID"]) && $arFields["IBLOCK_SECTION_ID"] != $db_record["IBLOCK_SECTION_ID"]) {
                 $rsSection = CIBlockSection::GetByID($ID);
                 $arSection = $rsSection->Fetch();
                 $strSql = "\n\t\t\t\t\t\tSELECT ID, GLOBAL_ACTIVE\n\t\t\t\t\t\tFROM b_iblock_section\n\t\t\t\t\t\tWHERE IBLOCK_ID = " . $arSection["IBLOCK_ID"] . "\n\t\t\t\t\t\tAND ID = " . intval($arFields["IBLOCK_SECTION_ID"]) . "\n\t\t\t\t\t";
                 $rsParent = $DB->Query($strSql);
                 $arParent = $rsParent->Fetch();
                 //If new parent is not globally active
                 //or we are not active either
                 //we must be not globally active too
                 if ($arParent && $arParent["GLOBAL_ACTIVE"] == "N" || $arFields["ACTIVE"] == "N") {
                     $DB->Query("\n\t\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t\t,GLOBAL_ACTIVE = 'N'\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tIBLOCK_ID = " . $arSection["IBLOCK_ID"] . "\n\t\t\t\t\t\t\t\tAND LEFT_MARGIN >= " . intval($arSection["LEFT_MARGIN"]) . "\n\t\t\t\t\t\t\t\tAND RIGHT_MARGIN <= " . intval($arSection["RIGHT_MARGIN"]) . "\n\t\t\t\t\t\t");
                 } elseif ($arSection["ACTIVE"] == "N" && $arFields["ACTIVE"] == "Y") {
                     $this->RecalcGlobalActiveFlag($arSection);
                 } elseif ((!$arParent || $arParent["GLOBAL_ACTIVE"] == "Y") && $arSection["GLOBAL_ACTIVE"] == "N" && ($arSection["ACTIVE"] == "Y" || $arFields["ACTIVE"] == "Y")) {
                     $this->RecalcGlobalActiveFlag($arSection);
                 }
                 //Otherwise we may not to change anything
             } elseif (isset($arFields["ACTIVE"]) && $arFields["ACTIVE"] != $db_record["ACTIVE"]) {
                 //Make all children globally inactive
                 if ($arFields["ACTIVE"] == "N") {
                     $DB->Query("\n\t\t\t\t\t\t\tUPDATE b_iblock_section SET\n\t\t\t\t\t\t\t\tTIMESTAMP_X=" . ($DB->type == "ORACLE" ? "NULL" : "TIMESTAMP_X") . "\n\t\t\t\t\t\t\t\t,GLOBAL_ACTIVE = 'N'\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tIBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\t\tAND LEFT_MARGIN >= " . intval($db_record["LEFT_MARGIN"]) . "\n\t\t\t\t\t\t\t\tAND RIGHT_MARGIN <= " . intval($db_record["RIGHT_MARGIN"]) . "\n\t\t\t\t\t\t");
                 } else {
                     //Check for parent activity
                     $strSql = "\n\t\t\t\t\t\t\tSELECT ID, GLOBAL_ACTIVE\n\t\t\t\t\t\t\tFROM b_iblock_section\n\t\t\t\t\t\t\tWHERE IBLOCK_ID = " . $db_record["IBLOCK_ID"] . "\n\t\t\t\t\t\t\tAND ID = " . intval($db_record["IBLOCK_SECTION_ID"]) . "\n\t\t\t\t\t\t";
                     $rsParent = $DB->Query($strSql);
                     $arParent = $rsParent->Fetch();
                     //Parent is active
                     //and we changed
                     //so need to recalc
                     if (!$arParent || $arParent["GLOBAL_ACTIVE"] == "Y") {
                         $this->RecalcGlobalActiveFlag($db_record);
                     }
                 }
             }
         }
         if ($arIBlock["RIGHTS_MODE"] === "E") {
             $obSectionRights = new CIBlockSectionRights($arIBlock["ID"], $ID);
             //Check if parent changed with extended rights mode
             if (isset($arFields["IBLOCK_SECTION_ID"]) && $arFields["IBLOCK_SECTION_ID"] != $db_record["IBLOCK_SECTION_ID"]) {
                 $obSectionRights->ChangeParents(array($db_record["IBLOCK_SECTION_ID"]), array($arFields["IBLOCK_SECTION_ID"]));
             }
             if (array_key_exists("RIGHTS", $arFields) && is_array($arFields["RIGHTS"])) {
                 $obSectionRights->SetRights($arFields["RIGHTS"]);
             }
         }
         $uf_updated = $GLOBALS["USER_FIELD_MANAGER"]->Update("IBLOCK_" . $db_record["IBLOCK_ID"] . "_SECTION", $ID, $arFields);
         if ($uf_updated) {
             $DB->Query("UPDATE b_iblock_section SET TIMESTAMP_X = " . $DB->CurrentTimeFunction() . " WHERE ID = " . $ID);
         }
         if (CIBlock::GetArrayByID($db_record["IBLOCK_ID"], "SECTION_PROPERTY") === "Y" && array_key_exists("SECTION_PROPERTY", $arFields) && is_array($arFields["SECTION_PROPERTY"])) {
             CIBlockSectionPropertyLink::DeleteBySection($ID);
             foreach ($arFields["SECTION_PROPERTY"] as $PROPERTY_ID => $arLink) {
                 CIBlockSectionPropertyLink::Add($ID, $PROPERTY_ID, $arLink);
             }
         }
         if ($bUpdateSearch) {
             CIBlockSection::UpdateSearch($ID);
         }
         if ($arIBlock["FIELDS"]["LOG_SECTION_EDIT"]["IS_REQUIRED"] == "Y") {
             $USER_ID = is_object($USER) ? intval($USER->GetID()) : 0;
             $db_events = GetModuleEvents("main", "OnBeforeEventLog");
             $arEvent = $db_events->Fetch();
             if (!$arEvent || ExecuteModuleEventEx($arEvent, array($USER_ID)) === false) {
                 $rsSection = CIBlockSection::GetList(array(), array("=ID" => $ID), false, array("LIST_PAGE_URL", "NAME", "CODE"));
                 $arSection = $rsSection->GetNext();
                 $res = array("ID" => $ID, "CODE" => $arSection["CODE"], "NAME" => $arSection["NAME"], "SECTION_NAME" => $arIBlock["SECTION_NAME"], "USER_ID" => $USER_ID, "IBLOCK_PAGE_URL" => $arSection["LIST_PAGE_URL"]);
                 CEventLog::Log("IBLOCK", "IBLOCK_SECTION_EDIT", "iblock", $arIBlock["ID"], serialize($res));
             }
         }
         $Result = true;
         /*********** QUOTA ***************/
         $_SESSION["SESS_RECOUNT_DB"] = "Y";
         /*********** QUOTA ***************/
     }
     $arFields["ID"] = $ID;
     $arFields["IBLOCK_ID"] = $db_record["IBLOCK_ID"];
     $arFields["RESULT"] =& $Result;
     $events = GetModuleEvents("iblock", "OnAfterIBlockSectionUpdate");
     while ($arEvent = $events->Fetch()) {
         ExecuteModuleEventEx($arEvent, array(&$arFields));
     }
     if (defined("BX_COMP_MANAGED_CACHE")) {
         $GLOBALS["CACHE_MANAGER"]->ClearByTag("iblock_id_" . $arIBlock["ID"]);
     }
     return $Result;
 }
				Input params
********************************************************************/
/***************** BASE ********************************************/
$arParams["IBLOCK_TYPE"] = trim($arParams["IBLOCK_TYPE"]);
$arParams["IBLOCK_ID"] = intVal($arParams["IBLOCK_ID"]);
$arParams["SECTION_ID"] = intVal($arParams["SECTION_ID"]);
$arParams["USER_ALIAS"] = trim($arParams["USER_ALIAS"]);
$arParams["BEHAVIOUR"] = $arParams["BEHAVIOUR"] == "USER" ? "USER" : "SIMPLE";
$arParams["PERMISSION_EXTERNAL"] = trim($arParams["PERMISSION"]);
$arParams["IMAGE_UPLOADER_ACTIVEX_CLSID"] = "718B3D1E-FF0C-4EE6-9F3B-0166A5D1C1B9";
$arParams["IMAGE_UPLOADER_ACTIVEX_CONTROL_VERSION"] = "6,0,20,0";
$arParams["IMAGE_UPLOADER_JAVAAPPLET_VERSION"] = "6.0.20.0";
$arParams["THUMBNAIL_ACTIVEX_CLSID"] = "58C8ACD5-D8A6-4AC8-9494-2E6CCF6DD2F8";
$arParams["THUMBNAIL_ACTIVEX_CONTROL_VERSION"] = "3,5,204,0";
$arParams["THUMBNAIL_JAVAAPPLET_VERSION"] = "1.1.81.0";
$arParams["PATH_TO_TMP"] = CTempFile::GetDirectoryName(12, "uploader");
/***************** URL *********************************************/
$URL_NAME_DEFAULT = array("index" => "", "gallery" => "PAGE_NAME=gallery&USER_ALIAS=#USER_ALIAS#", "section" => "PAGE_NAME=section" . ($arParams["BEHAVIOUR"] == "USER" ? "&USER_ALIAS=#USER_ALIAS#" : "") . "&SECTION_ID=#SECTION_ID#", "section_edit" => "PAGE_NAME=section_edit" . ($arParams["BEHAVIOUR"] == "USER" ? "&USER_ALIAS=#USER_ALIAS#" : "") . "&SECTION_ID=#SECTION_ID#");
foreach ($URL_NAME_DEFAULT as $URL => $URL_VALUE) {
    $arParams[strToUpper($URL) . "_URL"] = trim($arParams[strToUpper($URL) . "_URL"]);
    if (empty($arParams[strToUpper($URL) . "_URL"])) {
        $arParams[strToUpper($URL) . "_URL"] = $APPLICATION->GetCurPage() . "?" . $URL_VALUE;
    }
    $arParams["~" . strToUpper($URL) . "_URL"] = $arParams[strToUpper($URL) . "_URL"];
    $arParams[strToUpper($URL) . "_URL"] = htmlspecialcharsbx($arParams["~" . strToUpper($URL) . "_URL"]);
}
$arParams["SUCCESS_URL"] = CHTTP::urlDeleteParams(CComponentEngine::MakePathFromTemplate($arParams["~SECTION_URL"], array("USER_ALIAS" => $arParams["USER_ALIAS"], "SECTION_ID" => $arParams["SECTION_ID"])), array("sessid", "uploader_redirect"), true);
$arParams["REDIRECT_URL"] = $arParams["ACTION_URL"];
$arParams["REDIRECT_URL"] = CHTTP::urlDeleteParams($arParams["REDIRECT_URL"], array("clear_cache", "bitrix_include_areas", "bitrix_show_mode", "back_url_admin", "bx_photo_ajax", "change_view_mode_data", "sessid", "uploader_redirect"));
$arParams["REDIRECT_URL"] .= (strpos($arParams["REDIRECT_URL"], "?") === false ? "?" : "&") . "uploader_redirect=Y&sessid=" . bitrix_sessid();
$arParams["SIMPLE_FORM_URL"] = $APPLICATION->GetCurPageParam("view_mode=form&" . bitrix_sessid_get(), array("view_mode", "sessid", "uploader_redirect"));
Exemple #19
0
 function Add($arFields, $bWorkFlow = false, $bUpdateSearch = true, $bResizePictures = false)
 {
     global $DB, $USER;
     $arIBlock = CIBlock::GetArrayByID($arFields["IBLOCK_ID"]);
     $bWorkFlow = $bWorkFlow && is_array($arIBlock) && $arIBlock["WORKFLOW"] != "N" && CModule::IncludeModule("workflow");
     $bBizProc = is_array($arIBlock) && $arIBlock["BIZPROC"] == "Y" && IsModuleInstalled("bizproc");
     if (array_key_exists("BP_PUBLISHED", $arFields)) {
         if ($bBizProc) {
             if ($arFields["BP_PUBLISHED"] == "Y") {
                 $arFields["WF_STATUS_ID"] = 1;
                 $arFields["WF_NEW"] = false;
             } else {
                 $arFields["WF_STATUS_ID"] = 2;
                 $arFields["WF_NEW"] = "Y";
                 $arFields["BP_PUBLISHED"] = "N";
             }
         } else {
             unset($arFields["BP_PUBLISHED"]);
         }
     }
     if (array_key_exists("IBLOCK_SECTION_ID", $arFields)) {
         if (!array_key_exists("IBLOCK_SECTION", $arFields)) {
             $arFields["IBLOCK_SECTION"] = array($arFields["IBLOCK_SECTION_ID"]);
         } elseif (is_array($arFields["IBLOCK_SECTION"]) && !in_array($arFields["IBLOCK_SECTION_ID"], $arFields["IBLOCK_SECTION"])) {
             unset($arFields["IBLOCK_SECTION_ID"]);
         }
     }
     $strWarning = "";
     if ($bResizePictures) {
         $arDef = $arIBlock["FIELDS"]["PREVIEW_PICTURE"]["DEFAULT_VALUE"];
         if ($arDef["FROM_DETAIL"] === "Y" && is_array($arFields["DETAIL_PICTURE"]) && $arFields["DETAIL_PICTURE"]["size"] > 0 && ($arDef["UPDATE_WITH_DETAIL"] === "Y" || $arFields["PREVIEW_PICTURE"]["size"] <= 0)) {
             $arNewPreview = $arFields["DETAIL_PICTURE"];
             $arNewPreview["COPY_FILE"] = "Y";
             if (isset($arFields["PREVIEW_PICTURE"]) && is_array($arFields["PREVIEW_PICTURE"]) && isset($arFields["PREVIEW_PICTURE"]["description"])) {
                 $arNewPreview["description"] = $arFields["PREVIEW_PICTURE"]["description"];
             }
             $arFields["PREVIEW_PICTURE"] = $arNewPreview;
         }
         if (array_key_exists("PREVIEW_PICTURE", $arFields) && is_array($arFields["PREVIEW_PICTURE"]) && $arDef["SCALE"] === "Y") {
             $arNewPicture = CIBlock::ResizePicture($arFields["PREVIEW_PICTURE"], $arDef);
             if (is_array($arNewPicture)) {
                 $arNewPicture["description"] = $arFields["PREVIEW_PICTURE"]["description"];
                 $arFields["PREVIEW_PICTURE"] = $arNewPicture;
             } elseif ($arDef["IGNORE_ERRORS"] !== "Y") {
                 unset($arFields["PREVIEW_PICTURE"]);
                 $strWarning .= GetMessage("IBLOCK_FIELD_PREVIEW_PICTURE") . ": " . $arNewPicture . "<br>";
             }
         }
         if (array_key_exists("PREVIEW_PICTURE", $arFields) && is_array($arFields["PREVIEW_PICTURE"]) && $arDef["USE_WATERMARK_FILE"] === "Y") {
             if (strlen($arFields["PREVIEW_PICTURE"]["tmp_name"]) > 0 && ($arFields["PREVIEW_PICTURE"]["tmp_name"] === $arFields["DETAIL_PICTURE"]["tmp_name"] || $arFields["PREVIEW_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["PREVIEW_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["PREVIEW_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["PREVIEW_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["PREVIEW_PICTURE"]["copy"] = true;
                 $arFields["PREVIEW_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["PREVIEW_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_FILE_POSITION"], "type" => "file", "size" => "real", "alpha_level" => 100 - min(max($arDef["WATERMARK_FILE_ALPHA"], 0), 100), "file" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_FILE"])));
         }
         if (array_key_exists("PREVIEW_PICTURE", $arFields) && is_array($arFields["PREVIEW_PICTURE"]) && $arDef["USE_WATERMARK_TEXT"] === "Y") {
             if (strlen($arFields["PREVIEW_PICTURE"]["tmp_name"]) > 0 && ($arFields["PREVIEW_PICTURE"]["tmp_name"] === $arFields["DETAIL_PICTURE"]["tmp_name"] || $arFields["PREVIEW_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["PREVIEW_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["PREVIEW_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["PREVIEW_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["PREVIEW_PICTURE"]["copy"] = true;
                 $arFields["PREVIEW_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["PREVIEW_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_TEXT_POSITION"], "type" => "text", "coefficient" => $arDef["WATERMARK_TEXT_SIZE"], "text" => $arDef["WATERMARK_TEXT"], "font" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_TEXT_FONT"]), "color" => $arDef["WATERMARK_TEXT_COLOR"]));
         }
         $arDef = $arIBlock["FIELDS"]["DETAIL_PICTURE"]["DEFAULT_VALUE"];
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["SCALE"] === "Y") {
             $arNewPicture = CIBlock::ResizePicture($arFields["DETAIL_PICTURE"], $arDef);
             if (is_array($arNewPicture)) {
                 $arNewPicture["description"] = $arFields["DETAIL_PICTURE"]["description"];
                 $arFields["DETAIL_PICTURE"] = $arNewPicture;
             } elseif ($arDef["IGNORE_ERRORS"] !== "Y") {
                 unset($arFields["DETAIL_PICTURE"]);
                 $strWarning .= GetMessage("IBLOCK_FIELD_DETAIL_PICTURE") . ": " . $arNewPicture . "<br>";
             }
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["USE_WATERMARK_FILE"] === "Y") {
             if (strlen($arFields["DETAIL_PICTURE"]["tmp_name"]) > 0 && ($arFields["DETAIL_PICTURE"]["tmp_name"] === $arFields["PREVIEW_PICTURE"]["tmp_name"] || $arFields["DETAIL_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["DETAIL_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["DETAIL_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["DETAIL_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["DETAIL_PICTURE"]["copy"] = true;
                 $arFields["DETAIL_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["DETAIL_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_FILE_POSITION"], "type" => "file", "size" => "real", "alpha_level" => 100 - min(max($arDef["WATERMARK_FILE_ALPHA"], 0), 100), "file" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_FILE"])));
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["USE_WATERMARK_TEXT"] === "Y") {
             if (strlen($arFields["DETAIL_PICTURE"]["tmp_name"]) > 0 && ($arFields["DETAIL_PICTURE"]["tmp_name"] === $arFields["PREVIEW_PICTURE"]["tmp_name"] || $arFields["DETAIL_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["DETAIL_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["DETAIL_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["DETAIL_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["DETAIL_PICTURE"]["copy"] = true;
                 $arFields["DETAIL_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["DETAIL_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_TEXT_POSITION"], "type" => "text", "coefficient" => $arDef["WATERMARK_TEXT_SIZE"], "text" => $arDef["WATERMARK_TEXT"], "font" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_TEXT_FONT"]), "color" => $arDef["WATERMARK_TEXT_COLOR"]));
         }
     }
     $ipropTemplates = new \Bitrix\Iblock\InheritedProperty\ElementTemplates($arFields["IBLOCK_ID"], 0);
     if (is_set($arFields, "PREVIEW_PICTURE")) {
         if (is_array($arFields["PREVIEW_PICTURE"])) {
             if (strlen($arFields["PREVIEW_PICTURE"]["name"]) <= 0 && strlen($arFields["PREVIEW_PICTURE"]["del"]) <= 0) {
                 unset($arFields["PREVIEW_PICTURE"]);
             } else {
                 $arFields["PREVIEW_PICTURE"]["MODULE_ID"] = "iblock";
                 $arFields["PREVIEW_PICTURE"]["name"] = \Bitrix\Iblock\Template\Helper::makeFileName($ipropTemplates, "ELEMENT_PREVIEW_PICTURE_FILE_NAME", $arFields, $arFields["PREVIEW_PICTURE"]);
             }
         } else {
             if (intval($arFields["PREVIEW_PICTURE"]) <= 0) {
                 unset($arFields["PREVIEW_PICTURE"]);
             }
         }
     }
     if (is_set($arFields, "DETAIL_PICTURE")) {
         if (is_array($arFields["DETAIL_PICTURE"])) {
             if (strlen($arFields["DETAIL_PICTURE"]["name"]) <= 0 && strlen($arFields["DETAIL_PICTURE"]["del"]) <= 0) {
                 unset($arFields["DETAIL_PICTURE"]);
             } else {
                 $arFields["DETAIL_PICTURE"]["MODULE_ID"] = "iblock";
                 $arFields["DETAIL_PICTURE"]["name"] = \Bitrix\Iblock\Template\Helper::makeFileName($ipropTemplates, "ELEMENT_DETAIL_PICTURE_FILE_NAME", $arFields, $arFields["DETAIL_PICTURE"]);
             }
         } else {
             if (intval($arFields["DETAIL_PICTURE"]) <= 0) {
                 unset($arFields["DETAIL_PICTURE"]);
             }
         }
     }
     if (is_set($arFields, "ACTIVE") && $arFields["ACTIVE"] != "Y") {
         $arFields["ACTIVE"] = "N";
     }
     if (is_set($arFields, "PREVIEW_TEXT_TYPE") && $arFields["PREVIEW_TEXT_TYPE"] != "html") {
         $arFields["PREVIEW_TEXT_TYPE"] = "text";
     }
     if (is_set($arFields, "DETAIL_TEXT_TYPE") && $arFields["DETAIL_TEXT_TYPE"] != "html") {
         $arFields["DETAIL_TEXT_TYPE"] = "text";
     }
     if (is_set($arFields, "DATE_ACTIVE_FROM")) {
         $arFields["ACTIVE_FROM"] = $arFields["DATE_ACTIVE_FROM"];
     }
     if (is_set($arFields, "DATE_ACTIVE_TO")) {
         $arFields["ACTIVE_TO"] = $arFields["DATE_ACTIVE_TO"];
     }
     if (is_set($arFields, "EXTERNAL_ID")) {
         $arFields["XML_ID"] = $arFields["EXTERNAL_ID"];
     }
     if ($bWorkFlow) {
         $arFields["WF"] = "Y";
         if ($arFields["WF_STATUS_ID"] != 1) {
             $arFields["WF_NEW"] = "Y";
         } else {
             $arFields["WF_NEW"] = "";
         }
     }
     $arFields["SEARCHABLE_CONTENT"] = $arFields["NAME"];
     if (isset($arFields["PREVIEW_TEXT"])) {
         if (isset($arFields["PREVIEW_TEXT_TYPE"]) && $arFields["PREVIEW_TEXT_TYPE"] == "html") {
             $arFields["SEARCHABLE_CONTENT"] .= "\r\n" . HTMLToTxt($arFields["PREVIEW_TEXT"]);
         } else {
             $arFields["SEARCHABLE_CONTENT"] .= "\r\n" . $arFields["PREVIEW_TEXT"];
         }
     }
     if (isset($arFields["DETAIL_TEXT"])) {
         if (isset($arFields["DETAIL_TEXT_TYPE"]) && $arFields["DETAIL_TEXT_TYPE"] == "html") {
             $arFields["SEARCHABLE_CONTENT"] .= "\r\n" . HTMLToTxt($arFields["DETAIL_TEXT"]);
         } else {
             $arFields["SEARCHABLE_CONTENT"] .= "\r\n" . $arFields["DETAIL_TEXT"];
         }
     }
     $arFields["SEARCHABLE_CONTENT"] = ToUpper($arFields["SEARCHABLE_CONTENT"]);
     if (!$this->CheckFields($arFields) || strlen($strWarning)) {
         $this->LAST_ERROR .= $strWarning;
         $Result = false;
         $arFields["RESULT_MESSAGE"] =& $this->LAST_ERROR;
     } else {
         if (array_key_exists("PREVIEW_PICTURE", $arFields)) {
             $SAVED_PREVIEW_PICTURE = $arFields["PREVIEW_PICTURE"];
             if (is_array($arFields["PREVIEW_PICTURE"])) {
                 CFile::SaveForDB($arFields, "PREVIEW_PICTURE", "iblock");
             }
             if ($bWorkFlow) {
                 $COPY_PREVIEW_PICTURE = $arFields["PREVIEW_PICTURE"];
             }
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields)) {
             $SAVED_DETAIL_PICTURE = $arFields["DETAIL_PICTURE"];
             if (is_array($arFields["DETAIL_PICTURE"])) {
                 CFile::SaveForDB($arFields, "DETAIL_PICTURE", "iblock");
             }
             if ($bWorkFlow) {
                 $COPY_DETAIL_PICTURE = $arFields["DETAIL_PICTURE"];
             }
         }
         unset($arFields["ID"]);
         if (is_object($USER)) {
             if (!isset($arFields["CREATED_BY"]) || intval($arFields["CREATED_BY"]) <= 0) {
                 $arFields["CREATED_BY"] = intval($USER->GetID());
             }
             if (!isset($arFields["MODIFIED_BY"]) || intval($arFields["MODIFIED_BY"]) <= 0) {
                 $arFields["MODIFIED_BY"] = intval($USER->GetID());
             }
         }
         $arFields["~TIMESTAMP_X"] = $arFields["~DATE_CREATE"] = $DB->CurrentTimeFunction();
         foreach (GetModuleEvents("iblock", "OnIBlockElementAdd", true) as $arEvent) {
             ExecuteModuleEventEx($arEvent, array($arFields));
         }
         $IBLOCK_SECTION_ID = $arFields["IBLOCK_SECTION_ID"];
         unset($arFields["IBLOCK_SECTION_ID"]);
         $ID = $DB->Add("b_iblock_element", $arFields, array("DETAIL_TEXT", "SEARCHABLE_CONTENT"), "iblock");
         if (array_key_exists("PREVIEW_PICTURE", $arFields)) {
             $arFields["PREVIEW_PICTURE_ID"] = $arFields["PREVIEW_PICTURE"];
             $arFields["PREVIEW_PICTURE"] = $SAVED_PREVIEW_PICTURE;
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields)) {
             $arFields["DETAIL_PICTURE_ID"] = $arFields["DETAIL_PICTURE"];
             $arFields["DETAIL_PICTURE"] = $SAVED_DETAIL_PICTURE;
         }
         if (CIBlockElement::GetIBVersion($arFields["IBLOCK_ID"]) == 2) {
             $DB->Query("INSERT INTO b_iblock_element_prop_s" . $arFields["IBLOCK_ID"] . "(IBLOCK_ELEMENT_ID)VALUES(" . $ID . ")");
         }
         if (!isset($arFields["XML_ID"]) || strlen($arFields["XML_ID"]) <= 0) {
             $arFields["XML_ID"] = $ID;
             $DB->Query("UPDATE b_iblock_element SET XML_ID = " . $ID . " WHERE ID = " . $ID);
         }
         if (is_set($arFields, "PROPERTY_VALUES")) {
             CIBlockElement::SetPropertyValues($ID, $arFields["IBLOCK_ID"], $arFields["PROPERTY_VALUES"]);
         }
         if (is_set($arFields, "IBLOCK_SECTION")) {
             CIBlockElement::SetElementSection($ID, $arFields["IBLOCK_SECTION"], true, $arIBlock["RIGHTS_MODE"] === "E" ? $arIBlock["ID"] : 0, $IBLOCK_SECTION_ID);
         }
         if ($arIBlock["RIGHTS_MODE"] === "E") {
             $obElementRights = new CIBlockElementRights($arIBlock["ID"], $ID);
             if (!is_set($arFields, "IBLOCK_SECTION") || empty($arFields["IBLOCK_SECTION"])) {
                 $obElementRights->ChangeParents(array(), array(0));
             }
             if (array_key_exists("RIGHTS", $arFields) && is_array($arFields["RIGHTS"])) {
                 $obElementRights->SetRights($arFields["RIGHTS"]);
             }
         }
         if (array_key_exists("IPROPERTY_TEMPLATES", $arFields)) {
             $ipropTemplates = new \Bitrix\Iblock\InheritedProperty\ElementTemplates($arIBlock["ID"], $ID);
             $ipropTemplates->set($arFields["IPROPERTY_TEMPLATES"]);
         }
         if ($bUpdateSearch) {
             CIBlockElement::UpdateSearch($ID);
         }
         \Bitrix\Iblock\PropertyIndex\Manager::updateElementIndex($arIBlock["ID"], $ID);
         if (!isset($arFields["WF_PARENT_ELEMENT_ID"]) && $arIBlock["FIELDS"]["LOG_ELEMENT_ADD"]["IS_REQUIRED"] == "Y") {
             $USER_ID = is_object($USER) ? intval($USER->GetID()) : 0;
             $arEvents = GetModuleEvents("main", "OnBeforeEventLog", true);
             if (empty($arEvents) || ExecuteModuleEventEx($arEvents[0], array($USER_ID)) === false) {
                 $rsElement = CIBlockElement::GetList(array(), array("=ID" => $ID), false, false, array("LIST_PAGE_URL", "NAME", "CODE"));
                 $arElement = $rsElement->GetNext();
                 $res = array("ID" => $ID, "CODE" => $arElement["CODE"], "NAME" => $arElement["NAME"], "ELEMENT_NAME" => $arIBlock["ELEMENT_NAME"], "USER_ID" => $USER_ID, "IBLOCK_PAGE_URL" => $arElement["LIST_PAGE_URL"]);
                 CEventLog::Log("IBLOCK", "IBLOCK_ELEMENT_ADD", "iblock", $arIBlock["ID"], serialize($res));
             }
         }
         if ($bWorkFlow && intval($arFields["WF_PARENT_ELEMENT_ID"]) <= 0) {
             // It is completly new element - so make it copy
             unset($arFields["WF_NEW"]);
             $arFields["WF_PARENT_ELEMENT_ID"] = $ID;
             $arNewFields = $arFields;
             $arNewFields["PREVIEW_PICTURE"] = $COPY_PREVIEW_PICTURE;
             $arNewFields["DETAIL_PICTURE"] = $COPY_DETAIL_PICTURE;
             if (is_array($arNewFields["PROPERTY_VALUES"])) {
                 $i = 0;
                 $db_prop = CIBlockProperty::GetList(array(), array("IBLOCK_ID" => $arFields["IBLOCK_ID"], "CHECK_PERMISSIONS" => "N", "PROPERTY_TYPE" => "F"));
                 while ($arProp = $db_prop->Fetch()) {
                     $i++;
                     unset($arNewFields["PROPERTY_VALUES"][$arProp["CODE"]]);
                     unset($arNewFields["PROPERTY_VALUES"][$arProp["ID"]]);
                     $arNewFields["PROPERTY_VALUES"][$arProp["ID"]] = array();
                 }
                 if ($i > 0) {
                     $props = CIBlockElement::GetProperty($arFields["IBLOCK_ID"], $ID, "sort", "asc", array("PROPERTY_TYPE" => "F", "EMPTY" => "N"));
                     while ($arProp = $props->Fetch()) {
                         $arNewFields["PROPERTY_VALUES"][$arProp["ID"]][$arProp['PROPERTY_VALUE_ID']] = array("VALUE" => $arProp["VALUE"], "DESCRIPTION" => $arProp["DESCRIPTION"]);
                     }
                 }
             }
             $WF_ID = $this->Add($arNewFields);
             if ($this->bWF_SetMove) {
                 CIBlockElement::WF_SetMove($WF_ID);
             }
         }
         $Result = $ID;
         $arFields["ID"] =& $ID;
         $_SESSION["SESS_RECOUNT_DB"] = "Y";
         self::$elementIblock[$ID] = $arIBlock['ID'];
     }
     if (isset($arFields["PREVIEW_PICTURE"]) && is_array($arFields["PREVIEW_PICTURE"]) && isset($arFields["PREVIEW_PICTURE"]["COPY_FILE"]) && $arFields["PREVIEW_PICTURE"]["COPY_FILE"] == "Y" && $arFields["PREVIEW_PICTURE"]["copy"]) {
         @unlink($arFields["PREVIEW_PICTURE"]["tmp_name"]);
         @rmdir(dirname($arFields["PREVIEW_PICTURE"]["tmp_name"]));
     }
     if (isset($arFields["DETAIL_PICTURE"]) && is_array($arFields["DETAIL_PICTURE"]) && isset($arFields["DETAIL_PICTURE"]["COPY_FILE"]) && $arFields["DETAIL_PICTURE"]["COPY_FILE"] == "Y" && $arFields["DETAIL_PICTURE"]["copy"]) {
         @unlink($arFields["DETAIL_PICTURE"]["tmp_name"]);
         @rmdir(dirname($arFields["DETAIL_PICTURE"]["tmp_name"]));
     }
     $arFields["RESULT"] =& $Result;
     foreach (GetModuleEvents("iblock", "OnAfterIBlockElementAdd", true) as $arEvent) {
         ExecuteModuleEventEx($arEvent, array(&$arFields));
     }
     CIBlock::clearIblockTagCache($arIBlock['ID']);
     return $Result;
 }
Exemple #20
0
 private static function makeFileArrayFromArray($file_array, $description = null, $options = array())
 {
     $result = false;
     if (is_uploaded_file($file_array["tmp_name"])) {
         $result = $file_array;
         if (!is_null($description)) {
             $result["description"] = $description;
         }
     } elseif (strlen($file_array["tmp_name"]) > 0 && strpos($file_array["tmp_name"], CTempFile::GetAbsoluteRoot()) === 0) {
         $io = CBXVirtualIo::GetInstance();
         $absPath = $io->CombinePath("/", $file_array["tmp_name"]);
         $tmpPath = CTempFile::GetAbsoluteRoot() . "/";
         if (strpos($absPath, $tmpPath) === 0) {
             $result = $file_array;
             $result["tmp_name"] = $absPath;
             $result["error"] = intval($result["error"]);
             if (!is_null($description)) {
                 $result["description"] = $description;
             }
         }
     } elseif (strlen($file_array["tmp_name"]) > 0) {
         $io = CBXVirtualIo::GetInstance();
         $normPath = $io->CombinePath("/", $file_array["tmp_name"]);
         $absPath = $io->CombinePath($_SERVER["DOCUMENT_ROOT"], $normPath);
         $tmpPath = CTempFile::GetAbsoluteRoot() . "/";
         if (strpos($absPath, $tmpPath) === 0) {
             $result = $file_array;
             $result["tmp_name"] = $absPath;
             $result["error"] = intval($result["error"]);
             if (!is_null($description)) {
                 $result["description"] = $description;
             }
         }
     } else {
         $emptyFile = array("name" => null, "type" => null, "tmp_name" => null, "error" => 4, "size" => 0);
         if ($file_array == $emptyFile) {
             $result = $emptyFile;
             if (!is_null($description)) {
                 $result["description"] = $description;
             }
         }
     }
     return $result;
 }
Exemple #21
0
 function ResizePicture($file, $resize, $primaryField, $secondaryField = "")
 {
     static $errorFile = array("tmp_name" => "", "del" => "Y");
     $external_id = md5($file);
     if (strlen($file) <= 0) {
         return $errorFile;
     }
     if (file_exists($this->files_dir . $file) && is_file($this->files_dir . $file)) {
         $file = $this->files_dir . $file;
     } elseif (file_exists($file) && is_file($file)) {
     } elseif (($fileId = $this->CheckFileByName($external_id, array($primaryField))) > 0) {
         return CFile::MakeFileArray($fileId);
     } elseif ($secondaryField && ($fileId = $this->CheckFileByName($external_id, array($secondaryField))) > 0) {
         $storedFile = CFile::MakeFileArray($fileId);
         if ($storedFile) {
             $tempFile = CTempFile::GetFileName(bx_basename($storedFile["tmp_name"]));
             CheckDirPath($tempFile);
             if (copy($storedFile["tmp_name"], $tempFile)) {
                 $storedFile["tmp_name"] = $tempFile;
                 return $storedFile;
             } else {
                 return $errorFile;
             }
         } else {
             return $errorFile;
         }
     } else {
         return $errorFile;
     }
     if (!is_array($resize) || !preg_match("#(\\.)([^./\\\\]+?)\$#", $file)) {
         $arFile = CFile::MakeFileArray($file, false, false, $external_id);
         if ($arFile && $this->iblock_resize) {
             $arFile["COPY_FILE"] = "Y";
         }
         return $arFile;
     }
     $i = 1;
     while (file_exists(preg_replace("#(\\.)([^./\\\\]+?)\$#", ".resize" . $i . ".\\2", $file))) {
         $i++;
     }
     $new_file = preg_replace("#(\\.)([^./\\\\]+?)\$#", ".resize" . $i . ".\\2", $file);
     if (!CFile::ResizeImageFile($file, $new_file, array("width" => $resize[0], "height" => $resize[1]))) {
         return CFile::MakeFileArray($file, false, false, $external_id);
     }
     $this->arTempFiles[] = $new_file;
     return CFile::MakeFileArray($new_file, false, false, $external_id);
 }
Exemple #22
0
 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;
 }
Exemple #23
0
 function __construct($params = array())
 {
     $this->status = new Status("ready");
     global $APPLICATION;
     $this->script = $APPLICATION->GetCurPageParam();
     $this->setParams($params);
     $this->path = \CTempFile::GetDirectoryName(12, array("bxu", md5(serialize(array($this->controlId, bitrix_sessid(), \CMain::GetServerUniqID())))));
     $this->processTime["max"] = intval(ini_get("max_execution_time")) * 0.75;
     $this->processTime["start"] = time();
     $this->log = new Log();
     $this->packLog = new Log();
     $this->http = new HttpClient();
     set_time_limit(0);
     return $this;
 }
Exemple #24
0
	public static function ResizePicture($arFile, $arResize)
	{
		if(strlen($arFile["tmp_name"]) <= 0)
			return $arFile;

		if(array_key_exists("error", $arFile) && $arFile["error"] !== 0)
			return GetMessage("IBLOCK_BAD_FILE_ERROR");

		$file = $arFile["tmp_name"];

		if(!file_exists($file) && !is_file($file))
			return GetMessage("IBLOCK_BAD_FILE_NOT_FOUND");

		$width = intval($arResize["WIDTH"]);
		$height = intval($arResize["HEIGHT"]);

		if($width <= 0 && $height <= 0)
			return $arFile;

		$orig = CFile::GetImageSize($file, true);
		if(!is_array($orig))
			return GetMessage("IBLOCK_BAD_FILE_NOT_PICTURE");

		$width_orig = $orig[0];
		$height_orig = $orig[1];

		$orientation = 0;
		$exifData = array();
		$image_type = $orig[2];
		if($image_type == IMAGETYPE_JPEG)
		{
			$exifData = CFile::ExtractImageExif($file);
			if ($exifData  && isset($exifData['Orientation']))
			{
				$orientation = $exifData['Orientation'];
				if ($orientation >= 5 && $orientation <= 8)
				{
					$width_orig = $orig[1];
					$height_orig = $orig[0];
				}
			}
		}

		if(($width > 0 && $orig[0] > $width) || ($height > 0 && $orig[1] > $height))
		{
			if($arFile["COPY_FILE"] == "Y")
			{
				$new_file = CTempFile::GetFileName(basename($file));
				CheckDirPath($new_file);
				$arFile["copy"] = true;

				if(copy($file, $new_file))
					$file = $new_file;
				else
					return GetMessage("IBLOCK_BAD_FILE_NOT_FOUND");
			}

			if($width <= 0)
				$width = $width_orig;

			if($height <= 0)
				$height = $height_orig;

			$height_new = $height_orig;
			if($width_orig > $width)
				$height_new = $width * $height_orig  / $width_orig;

			if($height_new > $height)
				$width = $height * $width_orig / $height_orig;
			else
				$height = $height_new;

			$image_type = $orig[2];
			if($image_type == IMAGETYPE_JPEG)
			{
				$image = imagecreatefromjpeg($file);
				if ($image === false)
				{
					ini_set('gd.jpeg_ignore_warning', 1);
					$image = imagecreatefromjpeg($file);
				}

				if ($orientation > 1)
				{
					if ($orientation == 7 || $orientation == 8)
						$image = imagerotate($image, 90, null);
					elseif ($orientation == 3 || $orientation == 4)
						$image = imagerotate($image, 180, null);
					elseif ($orientation == 5 || $orientation == 6)
						$image = imagerotate($image, 270, null);

					if (
						$orientation == 2 || $orientation == 7
						|| $orientation == 4 || $orientation == 5
					)
					{
						CFile::ImageFlipHorizontal($image);
					}
				}
			}
			elseif($image_type == IMAGETYPE_GIF)
				$image = imagecreatefromgif($file);
			elseif($image_type == IMAGETYPE_PNG)
				$image = imagecreatefrompng($file);
			else
				return GetMessage("IBLOCK_BAD_FILE_UNSUPPORTED");

			$image_p = imagecreatetruecolor($width, $height);
			if($image_type == IMAGETYPE_JPEG)
			{
				if($arResize["METHOD"] === "resample")
					imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
				else
					imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

				if($arResize["COMPRESSION"] > 0)
					imagejpeg($image_p, $file, $arResize["COMPRESSION"]);
				else
					imagejpeg($image_p, $file);
			}
			elseif($image_type == IMAGETYPE_GIF && function_exists("imagegif"))
			{
				imagetruecolortopalette($image_p, true, imagecolorstotal($image));
				imagepalettecopy($image_p, $image);

				//Save transparency for GIFs
				$transparentColor = imagecolortransparent($image);
				if($transparentColor >= 0 && $transparentColor < imagecolorstotal($image))
				{
					$transparentColor = imagecolortransparent($image_p, $transparentColor);
					imagefilledrectangle($image_p, 0, 0, $width, $height, $transparentColor);
				}

				if($arResize["METHOD"] === "resample")
					imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
				else
					imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
				imagegif($image_p, $file);
			}
			else
			{
				//Save transparency for PNG
				$transparentColor = imagecolorallocatealpha($image_p, 0, 0, 0, 127);
				imagefilledrectangle($image_p, 0, 0, $width, $height, $transparentColor);
				$transparentColor = imagecolortransparent($image_p, $transparentColor);

				imagealphablending($image_p, false);
				if($arResize["METHOD"] === "resample")
					imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
				else
					imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

				imagesavealpha($image_p, true);
				imagepng($image_p, $file);
			}

			imagedestroy($image);
			imagedestroy($image_p);

			$arFile["size"] = filesize($file);
			$arFile["tmp_name"] = $file;
			return $arFile;
		}
		else
		{
			return $arFile;
		}
	}
Exemple #25
0
$strError = '';
$arResult['STEP'] = isset($_POST['step']) ? intval($_POST['step']) : 1;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && check_bitrix_sessid()) {
    if (isset($_POST['next'])) {
        if ($arResult['STEP'] == 1) {
            if ($_FILES['IMPORT_FILE']['error'] > 0) {
                ShowError(GetMessage('CRM_CSV_NF_ERROR'));
            } else {
                $error = CFile::CheckFile($_FILES['IMPORT_FILE'], 0, 0, 'csv,txt');
                if ($error !== '') {
                    ShowError($error);
                } else {
                    if (isset($_SESSION['CRM_IMPORT_FILE'])) {
                        unset($_SESSION['CRM_IMPORT_FILE']);
                    }
                    $sTmpFilePath = CTempFile::GetDirectoryName(12, 'crm');
                    CheckDirPath($sTmpFilePath);
                    $_SESSION['CRM_IMPORT_FILE_SKIP_EMPTY'] = isset($_POST['IMPORT_FILE_SKIP_EMPTY']) && $_POST['IMPORT_FILE_SKIP_EMPTY'] == 'Y' ? true : false;
                    $_SESSION['CRM_IMPORT_FILE_FIRST_HEADER'] = isset($_POST['IMPORT_FILE_FIRST_HEADER']) && $_POST['IMPORT_FILE_FIRST_HEADER'] == 'Y' ? true : false;
                    $_SESSION['CRM_IMPORT_FILE'] = $sTmpFilePath . md5($_FILES['IMPORT_FILE']['tmp_name']) . '.tmp';
                    $_SESSION['CRM_IMPORT_FILE_POS'] = 0;
                    move_uploaded_file($_FILES['IMPORT_FILE']['tmp_name'], $_SESSION['CRM_IMPORT_FILE']);
                    @chmod($_SESSION['CRM_IMPORT_FILE'], BX_FILE_PERMISSIONS);
                    if (isset($_POST['IMPORT_FILE_ENCODING'])) {
                        $fileEncoding = $_POST['IMPORT_FILE_ENCODING'];
                        if ($fileEncoding !== '' && $fileEncoding !== '_' && $fileEncoding !== strtolower(SITE_CHARSET)) {
                            $convertCharsetErrorMsg = '';
                            $fileHandle = fopen($_SESSION['CRM_IMPORT_FILE'], 'rb');
                            $fileContents = fread($fileHandle, filesize($_SESSION['CRM_IMPORT_FILE']));
                            fclose($fileHandle);
                            //HACK: Remove UTF-8 BOM
Exemple #26
0
 /**
  * Exports current user's binded hot keys and using custom codes
  * @return string exported file name
  * */
 public function Export()
 {
     $this->LoadToCache();
     if (!is_array($this->arList) || empty($this->arList)) {
         return false;
     }
     $arForExport = array();
     $tmpDir = CTempFile::GetDirectoryName();
     CheckDirPath($tmpDir);
     $tmpExportFile = $tmpDir . self::$ExpImpFileName;
     foreach ($this->arList as $arHK) {
         $res = self::$codes->GetByID($arHK['CODE_ID']);
         $arTmpCode = $res->Fetch();
         if (!is_array($arTmpCode) || empty($arTmpCode)) {
             continue;
         }
         $arTmpLink = array('KEYS_STRING' => $arHK['KEYS_STRING'], 'CLASS_NAME' => $arTmpCode['CLASS_NAME'], 'NAME' => $arTmpCode['NAME'], 'IS_CUSTOM' => $arTmpCode['IS_CUSTOM']);
         if ($arTmpCode['IS_CUSTOM']) {
             $arTmpLink['CODE'] = $arTmpCode['CODE'];
             $arTmpLink['COMMENTS'] = $arTmpCode['COMMENTS'];
             $arTmpLink['URL'] = $arTmpCode['URL'];
         }
         $arForExport[] = $arTmpLink;
     }
     $result = file_put_contents($tmpExportFile, serialize($arForExport));
     if ($result === false) {
         return false;
     }
     return $tmpExportFile;
 }
Exemple #27
0
 function Update($ID, $arFields, $bWorkFlow = false, $bUpdateSearch = true, $bResizePictures = false, $bCheckDiskQuota = true)
 {
     global $DB, $USER;
     $ID = intval($ID);
     $db_element = CIBlockElement::GetList(array(), array("ID" => $ID, "SHOW_HISTORY" => "Y"), false, false, array("ID", "TIMESTAMP_X", "MODIFIED_BY", "DATE_CREATE", "CREATED_BY", "IBLOCK_ID", "ACTIVE", "ACTIVE_FROM", "ACTIVE_TO", "SORT", "NAME", "PREVIEW_PICTURE", "PREVIEW_TEXT", "PREVIEW_TEXT_TYPE", "DETAIL_PICTURE", "DETAIL_TEXT", "DETAIL_TEXT_TYPE", "WF_STATUS_ID", "WF_PARENT_ELEMENT_ID", "WF_NEW", "WF_COMMENTS", "IN_SECTIONS", "CODE", "TAGS", "XML_ID", "TMP_ID"));
     if (!($ar_element = $db_element->Fetch())) {
         return false;
     }
     $arIBlock = CIBlock::GetArrayByID($ar_element["IBLOCK_ID"]);
     $bWorkFlow = $bWorkFlow && is_array($arIBlock) && $arIBlock["WORKFLOW"] != "N" && CModule::IncludeModule("workflow");
     $ar_wf_element = $ar_element;
     $LAST_ID = 0;
     if ($bWorkFlow) {
         $LAST_ID = CIBlockElement::WF_GetLast($ID);
         if ($LAST_ID != $ID) {
             $db_element = CIBlockElement::GetByID($LAST_ID);
             if (!($ar_wf_element = $db_element->Fetch())) {
                 return false;
             }
         }
         $arFields["WF_PARENT_ELEMENT_ID"] = $ID;
         if (!array_key_exists("PROPERTY_VALUES", $arFields) || !is_array($arFields["PROPERTY_VALUES"])) {
             $arFields["PROPERTY_VALUES"] = array();
         }
         $bFieldProps = array();
         foreach ($arFields["PROPERTY_VALUES"] as $k => $v) {
             $bFieldProps[$k] = true;
         }
         $arFieldProps =& $arFields['PROPERTY_VALUES'];
         $props = CIBlockElement::GetProperty($ar_element["IBLOCK_ID"], $ar_wf_element["ID"]);
         while ($arProp = $props->Fetch()) {
             $pr_val_id = $arProp['PROPERTY_VALUE_ID'];
             if ($arProp['PROPERTY_TYPE'] == 'F' && strlen($pr_val_id) > 0) {
                 if (strlen($arProp["CODE"]) > 0 && is_set($arFieldProps, $arProp["CODE"])) {
                     $pr_id = $arProp["CODE"];
                 } else {
                     $pr_id = $arProp['ID'];
                 }
                 if (array_key_exists($pr_id, $arFieldProps) && array_key_exists($pr_val_id, $arFieldProps[$pr_id]) && is_array($arFieldProps[$pr_id][$pr_val_id])) {
                     $new_value = $arFieldProps[$pr_id][$pr_val_id];
                     if (strlen($new_value['name']) <= 0 && $new_value['del'] != "Y" && strlen($new_value['VALUE']['name']) <= 0 && $new_value['VALUE']['del'] != "Y") {
                         if (array_key_exists('DESCRIPTION', $new_value) && $new_value['DESCRIPTION'] != $arProp['DESCRIPTION']) {
                             $p = array("VALUE" => CFile::MakeFileArray($arProp['VALUE']));
                             $p["DESCRIPTION"] = $new_value["DESCRIPTION"];
                             $p["MODULE_ID"] = "iblock";
                             $arFieldProps[$pr_id][$pr_val_id] = $p;
                         } elseif ($arProp['VALUE'] > 0) {
                             $arFieldProps[$pr_id][$pr_val_id] = array("VALUE" => $arProp['VALUE'], "DESCRIPTION" => $arProp["DESCRIPTION"]);
                         }
                     }
                 } else {
                     $arFieldProps[$pr_id][$pr_val_id] = array("VALUE" => $arProp['VALUE'], "DESCRIPTION" => $arProp["DESCRIPTION"]);
                 }
                 continue;
             }
             if (strlen($pr_val_id) <= 0 || array_key_exists($arProp["ID"], $bFieldProps) || strlen($arProp["CODE"]) > 0 && array_key_exists($arProp["CODE"], $bFieldProps)) {
                 continue;
             }
             $arFieldProps[$arProp["ID"]][$pr_val_id] = array("VALUE" => $arProp['VALUE'], "DESCRIPTION" => $arProp["DESCRIPTION"]);
         }
         if ($ar_wf_element["IN_SECTIONS"] == "Y") {
             $ar_wf_element["IBLOCK_SECTION"] = array();
             $rsSections = CIBlockElement::GetElementGroups($ar_element["ID"], true, array('ID', 'IBLOCK_ELEMENT_ID'));
             while ($arSection = $rsSections->Fetch()) {
                 $ar_wf_element["IBLOCK_SECTION"][] = $arSection["ID"];
             }
         }
         unset($ar_wf_element["DATE_ACTIVE_FROM"]);
         unset($ar_wf_element["DATE_ACTIVE_TO"]);
         unset($ar_wf_element["EXTERNAL_ID"]);
         unset($ar_wf_element["TIMESTAMP_X"]);
         unset($ar_wf_element["ID"]);
         $arFields = $arFields + $ar_wf_element;
     }
     $arFields["WF"] = $bWorkFlow ? "Y" : "N";
     $bBizProc = is_array($arIBlock) && $arIBlock["BIZPROC"] == "Y" && IsModuleInstalled("bizproc");
     if (array_key_exists("BP_PUBLISHED", $arFields)) {
         if ($bBizProc) {
             if ($arFields["BP_PUBLISHED"] == "Y") {
                 $arFields["WF_STATUS_ID"] = 1;
                 $arFields["WF_NEW"] = false;
             } else {
                 $arFields["WF_STATUS_ID"] = 2;
                 $arFields["WF_NEW"] = "Y";
                 $arFields["BP_PUBLISHED"] = "N";
             }
         } else {
             $arFields["WF_NEW"] = false;
             unset($arFields["BP_PUBLISHED"]);
         }
     } else {
         $arFields["WF_NEW"] = false;
     }
     if (is_set($arFields, "ACTIVE") && $arFields["ACTIVE"] != "Y") {
         $arFields["ACTIVE"] = "N";
     }
     if (is_set($arFields, "PREVIEW_TEXT_TYPE") && $arFields["PREVIEW_TEXT_TYPE"] != "html") {
         $arFields["PREVIEW_TEXT_TYPE"] = "text";
     }
     if (is_set($arFields, "DETAIL_TEXT_TYPE") && $arFields["DETAIL_TEXT_TYPE"] != "html") {
         $arFields["DETAIL_TEXT_TYPE"] = "text";
     }
     $strWarning = "";
     if ($bResizePictures) {
         $arDef = $arIBlock["FIELDS"]["PREVIEW_PICTURE"]["DEFAULT_VALUE"];
         if ($arDef["DELETE_WITH_DETAIL"] === "Y" && $arFields["DETAIL_PICTURE"]["del"] === "Y") {
             $arFields["PREVIEW_PICTURE"]["del"] = "Y";
         }
         if ($arDef["FROM_DETAIL"] === "Y" && ($arFields["PREVIEW_PICTURE"]["size"] <= 0 || $arDef["UPDATE_WITH_DETAIL"] === "Y") && is_array($arFields["DETAIL_PICTURE"]) && $arFields["DETAIL_PICTURE"]["size"] > 0) {
             if ($arFields["PREVIEW_PICTURE"]["del"] !== "Y" && $arDef["UPDATE_WITH_DETAIL"] !== "Y") {
                 $rsElement = CIBlockElement::GetList(array("ID" => "DESC"), array("ID" => $ar_wf_element["ID"], "IBLOCK_ID" => $ar_wf_element["IBLOCK_ID"], "SHOW_HISTORY" => "Y"), false, false, array("ID", "PREVIEW_PICTURE"));
                 $arOldElement = $rsElement->Fetch();
             } else {
                 $arOldElement = false;
             }
             if (!$arOldElement || !$arOldElement["PREVIEW_PICTURE"]) {
                 $arNewPreview = $arFields["DETAIL_PICTURE"];
                 $arNewPreview["COPY_FILE"] = "Y";
                 $arNewPreview["description"] = $arFields["PREVIEW_PICTURE"]["description"];
                 $arFields["PREVIEW_PICTURE"] = $arNewPreview;
             }
         }
         if (array_key_exists("PREVIEW_PICTURE", $arFields) && is_array($arFields["PREVIEW_PICTURE"]) && $arFields["PREVIEW_PICTURE"]["size"] > 0 && $arDef["SCALE"] === "Y") {
             $arNewPicture = CIBlock::ResizePicture($arFields["PREVIEW_PICTURE"], $arDef);
             if (is_array($arNewPicture)) {
                 $arNewPicture["description"] = $arFields["PREVIEW_PICTURE"]["description"];
                 $arFields["PREVIEW_PICTURE"] = $arNewPicture;
             } elseif ($arDef["IGNORE_ERRORS"] !== "Y") {
                 unset($arFields["PREVIEW_PICTURE"]);
                 $strWarning .= GetMessage("IBLOCK_FIELD_PREVIEW_PICTURE") . ": " . $arNewPicture . "<br>";
             }
         }
         if (array_key_exists("PREVIEW_PICTURE", $arFields) && is_array($arFields["PREVIEW_PICTURE"]) && $arDef["USE_WATERMARK_FILE"] === "Y") {
             if (strlen($arFields["PREVIEW_PICTURE"]["tmp_name"]) > 0 && ($arFields["PREVIEW_PICTURE"]["tmp_name"] === $arFields["DETAIL_PICTURE"]["tmp_name"] || $arFields["PREVIEW_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["PREVIEW_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["PREVIEW_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["PREVIEW_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["PREVIEW_PICTURE"]["copy"] = true;
                 $arFields["PREVIEW_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["PREVIEW_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_FILE_POSITION"], "type" => "file", "size" => "real", "alpha_level" => 100 - min(max($arDef["WATERMARK_FILE_ALPHA"], 0), 100), "file" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_FILE"])));
         }
         if (array_key_exists("PREVIEW_PICTURE", $arFields) && is_array($arFields["PREVIEW_PICTURE"]) && $arDef["USE_WATERMARK_TEXT"] === "Y") {
             if (strlen($arFields["PREVIEW_PICTURE"]["tmp_name"]) > 0 && ($arFields["PREVIEW_PICTURE"]["tmp_name"] === $arFields["DETAIL_PICTURE"]["tmp_name"] || $arFields["PREVIEW_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["PREVIEW_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["PREVIEW_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["PREVIEW_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["PREVIEW_PICTURE"]["copy"] = true;
                 $arFields["PREVIEW_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["PREVIEW_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_TEXT_POSITION"], "type" => "text", "coefficient" => $arDef["WATERMARK_TEXT_SIZE"], "text" => $arDef["WATERMARK_TEXT"], "font" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_TEXT_FONT"]), "color" => $arDef["WATERMARK_TEXT_COLOR"]));
         }
         $arDef = $arIBlock["FIELDS"]["DETAIL_PICTURE"]["DEFAULT_VALUE"];
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["SCALE"] === "Y") {
             $arNewPicture = CIBlock::ResizePicture($arFields["DETAIL_PICTURE"], $arDef);
             if (is_array($arNewPicture)) {
                 $arNewPicture["description"] = $arFields["DETAIL_PICTURE"]["description"];
                 $arFields["DETAIL_PICTURE"] = $arNewPicture;
             } elseif ($arDef["IGNORE_ERRORS"] !== "Y") {
                 unset($arFields["DETAIL_PICTURE"]);
                 $strWarning .= GetMessage("IBLOCK_FIELD_DETAIL_PICTURE") . ": " . $arNewPicture . "<br>";
             }
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["USE_WATERMARK_FILE"] === "Y") {
             if (strlen($arFields["DETAIL_PICTURE"]["tmp_name"]) > 0 && ($arFields["DETAIL_PICTURE"]["tmp_name"] === $arFields["PREVIEW_PICTURE"]["tmp_name"] || $arFields["DETAIL_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["DETAIL_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["DETAIL_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["DETAIL_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["DETAIL_PICTURE"]["copy"] = true;
                 $arFields["DETAIL_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["DETAIL_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_FILE_POSITION"], "type" => "file", "size" => "real", "alpha_level" => 100 - min(max($arDef["WATERMARK_FILE_ALPHA"], 0), 100), "file" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_FILE"])));
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"]) && $arDef["USE_WATERMARK_TEXT"] === "Y") {
             if (strlen($arFields["DETAIL_PICTURE"]["tmp_name"]) > 0 && ($arFields["DETAIL_PICTURE"]["tmp_name"] === $arFields["PREVIEW_PICTURE"]["tmp_name"] || $arFields["DETAIL_PICTURE"]["COPY_FILE"] == "Y" && !$arFields["DETAIL_PICTURE"]["copy"])) {
                 $tmp_name = CTempFile::GetFileName(basename($arFields["DETAIL_PICTURE"]["tmp_name"]));
                 CheckDirPath($tmp_name);
                 copy($arFields["DETAIL_PICTURE"]["tmp_name"], $tmp_name);
                 $arFields["DETAIL_PICTURE"]["copy"] = true;
                 $arFields["DETAIL_PICTURE"]["tmp_name"] = $tmp_name;
             }
             CIBLock::FilterPicture($arFields["DETAIL_PICTURE"]["tmp_name"], array("name" => "watermark", "position" => $arDef["WATERMARK_TEXT_POSITION"], "type" => "text", "coefficient" => $arDef["WATERMARK_TEXT_SIZE"], "text" => $arDef["WATERMARK_TEXT"], "font" => $_SERVER["DOCUMENT_ROOT"] . Rel2Abs("/", $arDef["WATERMARK_TEXT_FONT"]), "color" => $arDef["WATERMARK_TEXT_COLOR"]));
         }
     }
     $ipropTemplates = new \Bitrix\Iblock\InheritedProperty\ElementTemplates($ar_element["IBLOCK_ID"], $ar_element["ID"]);
     if (array_key_exists("PREVIEW_PICTURE", $arFields) && is_array($arFields["PREVIEW_PICTURE"])) {
         if (strlen($arFields["PREVIEW_PICTURE"]["name"]) <= 0 && strlen($arFields["PREVIEW_PICTURE"]["del"]) <= 0 && !is_set($arFields["PREVIEW_PICTURE"], "description")) {
             unset($arFields["PREVIEW_PICTURE"]);
         } else {
             $arFields["PREVIEW_PICTURE"]["MODULE_ID"] = "iblock";
             $arFields["PREVIEW_PICTURE"]["old_file"] = $ar_wf_element["PREVIEW_PICTURE"];
             $arFields["PREVIEW_PICTURE"]["name"] = \Bitrix\Iblock\Template\Helper::makeFileName($ipropTemplates, "ELEMENT_PREVIEW_PICTURE_FILE_NAME", array_merge($ar_element, $arFields), $arFields["PREVIEW_PICTURE"]);
         }
     }
     if (array_key_exists("DETAIL_PICTURE", $arFields) && is_array($arFields["DETAIL_PICTURE"])) {
         if (strlen($arFields["DETAIL_PICTURE"]["name"]) <= 0 && strlen($arFields["DETAIL_PICTURE"]["del"]) <= 0 && !is_set($arFields["DETAIL_PICTURE"], "description")) {
             unset($arFields["DETAIL_PICTURE"]);
         } else {
             $arFields["DETAIL_PICTURE"]["MODULE_ID"] = "iblock";
             $arFields["DETAIL_PICTURE"]["old_file"] = $ar_wf_element["DETAIL_PICTURE"];
             $arFields["DETAIL_PICTURE"]["name"] = \Bitrix\Iblock\Template\Helper::makeFileName($ipropTemplates, "ELEMENT_DETAIL_PICTURE_FILE_NAME", array_merge($ar_element, $arFields), $arFields["DETAIL_PICTURE"]);
         }
     }
     if (is_set($arFields, "DATE_ACTIVE_FROM")) {
         $arFields["ACTIVE_FROM"] = $arFields["DATE_ACTIVE_FROM"];
     }
     if (is_set($arFields, "DATE_ACTIVE_TO")) {
         $arFields["ACTIVE_TO"] = $arFields["DATE_ACTIVE_TO"];
     }
     if (is_set($arFields, "EXTERNAL_ID")) {
         $arFields["XML_ID"] = $arFields["EXTERNAL_ID"];
     }
     $PREVIEW_tmp = is_set($arFields, "PREVIEW_TEXT") ? $arFields["PREVIEW_TEXT"] : $ar_wf_element["PREVIEW_TEXT"];
     $PREVIEW_TYPE_tmp = is_set($arFields, "PREVIEW_TEXT_TYPE") ? $arFields["PREVIEW_TEXT_TYPE"] : $ar_wf_element["PREVIEW_TEXT_TYPE"];
     $DETAIL_tmp = is_set($arFields, "DETAIL_TEXT") ? $arFields["DETAIL_TEXT"] : $ar_wf_element["DETAIL_TEXT"];
     $DETAIL_TYPE_tmp = is_set($arFields, "DETAIL_TEXT_TYPE") ? $arFields["DETAIL_TEXT_TYPE"] : $ar_wf_element["DETAIL_TEXT_TYPE"];
     $arFields["SEARCHABLE_CONTENT"] = ToUpper((is_set($arFields, "NAME") ? $arFields["NAME"] : $ar_wf_element["NAME"]) . "\r\n" . ($PREVIEW_TYPE_tmp == "html" ? HTMLToTxt($PREVIEW_tmp) : $PREVIEW_tmp) . "\r\n" . ($DETAIL_TYPE_tmp == "html" ? HTMLToTxt($DETAIL_tmp) : $DETAIL_tmp));
     if (is_set($arFields["IBLOCK_SECTION_ID"]) && !is_set($arFields, "IBLOCK_SECTION")) {
         $arFields["IBLOCK_SECTION"] = array($arFields["IBLOCK_SECTION_ID"]);
     }
     $arFields["IBLOCK_ID"] = $ar_element["IBLOCK_ID"];
     if (!$this->CheckFields($arFields, $ID, $bCheckDiskQuota) || strlen($strWarning)) {
         $this->LAST_ERROR .= $strWarning;
         $Result = false;
         $arFields["RESULT_MESSAGE"] =& $this->LAST_ERROR;
     } else {
         unset($arFields["ID"]);
         if (array_key_exists("PREVIEW_PICTURE", $arFields)) {
             $SAVED_PREVIEW_PICTURE = $arFields["PREVIEW_PICTURE"];
         } else {
             $SAVED_PREVIEW_PICTURE = false;
         }
         if (array_key_exists("DETAIL_PICTURE", $arFields)) {
             $SAVED_DETAIL_PICTURE = $arFields["DETAIL_PICTURE"];
         } else {
             $SAVED_DETAIL_PICTURE = false;
         }
         // edit was done in workflow mode
         if ($bWorkFlow) {
             $arFields["WF_PARENT_ELEMENT_ID"] = $ID;
             if (array_key_exists("PREVIEW_PICTURE", $arFields)) {
                 if (is_array($arFields["PREVIEW_PICTURE"])) {
                     if (strlen($arFields["PREVIEW_PICTURE"]["name"]) <= 0 && strlen($arFields["PREVIEW_PICTURE"]["del"]) <= 0) {
                         if (array_key_exists("description", $arFields["PREVIEW_PICTURE"])) {
                             $arFile = CFile::GetFileArray($ar_wf_element["PREVIEW_PICTURE"]);
                             if ($arFields["PREVIEW_PICTURE"]["description"] != $arFile["DESCRIPTION"]) {
                                 //Description updated, so it's new file
                                 $arNewFile = CFile::MakeFileArray($ar_wf_element["PREVIEW_PICTURE"]);
                                 $arNewFile["description"] = $arFields["PREVIEW_PICTURE"]["description"];
                                 $arNewFile["MODULE_ID"] = "iblock";
                                 $arFields["PREVIEW_PICTURE"] = $arNewFile;
                             } else {
                                 $arFields["PREVIEW_PICTURE"] = $ar_wf_element["PREVIEW_PICTURE"];
                             }
                         } else {
                             //File was not changed at all
                             $arFields["PREVIEW_PICTURE"] = $ar_wf_element["PREVIEW_PICTURE"];
                         }
                     } else {
                         unset($arFields["PREVIEW_PICTURE"]["old_file"]);
                     }
                 }
             } else {
                 $arFields["PREVIEW_PICTURE"] = $ar_wf_element["PREVIEW_PICTURE"];
             }
             if (array_key_exists("DETAIL_PICTURE", $arFields)) {
                 if (is_array($arFields["DETAIL_PICTURE"])) {
                     if (strlen($arFields["DETAIL_PICTURE"]["name"]) <= 0 && strlen($arFields["DETAIL_PICTURE"]["del"]) <= 0) {
                         if (array_key_exists("description", $arFields["DETAIL_PICTURE"])) {
                             $arFile = CFile::GetFileArray($ar_wf_element["DETAIL_PICTURE"]);
                             if ($arFields["DETAIL_PICTURE"]["description"] != $arFile["DESCRIPTION"]) {
                                 //Description updated, so it's new file
                                 $arNewFile = CFile::MakeFileArray($ar_wf_element["DETAIL_PICTURE"]);
                                 $arNewFile["description"] = $arFields["DETAIL_PICTURE"]["description"];
                                 $arNewFile["MODULE_ID"] = "iblock";
                                 $arFields["DETAIL_PICTURE"] = $arNewFile;
                             } else {
                                 $arFields["DETAIL_PICTURE"] = $ar_wf_element["DETAIL_PICTURE"];
                             }
                         } else {
                             //File was not changed at all
                             $arFields["DETAIL_PICTURE"] = $ar_wf_element["DETAIL_PICTURE"];
                         }
                     } else {
                         unset($arFields["DETAIL_PICTURE"]["old_file"]);
                     }
                 }
             } else {
                 $arFields["DETAIL_PICTURE"] = $ar_wf_element["DETAIL_PICTURE"];
             }
             $NID = $this->Add($arFields);
             if ($NID > 0) {
                 if ($arFields["WF_STATUS_ID"] == 1) {
                     $DB->Query("UPDATE b_iblock_element SET TIMESTAMP_X=TIMESTAMP_X, WF_NEW=null WHERE ID=" . $ID);
                     $DB->Query("UPDATE b_iblock_element SET TIMESTAMP_X=TIMESTAMP_X, WF_NEW=null WHERE WF_PARENT_ELEMENT_ID=" . $ID);
                     $ar_wf_element["WF_NEW"] = false;
                 }
                 if ($this->bWF_SetMove) {
                     CIBlockElement::WF_SetMove($NID, $LAST_ID);
                 }
                 if ($ar_element["WF_STATUS_ID"] != 1 && $ar_wf_element["WF_STATUS_ID"] != $arFields["WF_STATUS_ID"] && $arFields["WF_STATUS_ID"] != 1) {
                     $DB->Query("UPDATE b_iblock_element SET TIMESTAMP_X=TIMESTAMP_X, WF_STATUS_ID=" . $arFields["WF_STATUS_ID"] . " WHERE ID=" . $ID);
                 }
             }
             //element was not published, so keep original
             if (is_set($arFields, "WF_STATUS_ID") && $arFields["WF_STATUS_ID"] != 1 && $ar_element["WF_STATUS_ID"] == 1 || !is_set($arFields, "WF_STATUS_ID") && $ar_wf_element["WF_STATUS_ID"] != 1) {
                 CIBlockElement::WF_CleanUpHistoryCopies($ID);
                 return true;
             }
             $arFields['WF_PARENT_ELEMENT_ID'] = false;
             $rs = $DB->Query("SELECT PREVIEW_PICTURE, DETAIL_PICTURE from b_iblock_element WHERE ID = " . $NID);
             $ar_new_element = $rs->Fetch();
         } else {
             $ar_new_element = false;
         }
         if ($ar_new_element) {
             if (!intval($ar_new_element["PREVIEW_PICTURE"])) {
                 $arFields["PREVIEW_PICTURE"] = false;
             } else {
                 $arFields["PREVIEW_PICTURE"] = $ar_new_element["PREVIEW_PICTURE"];
             }
             if (!intval($ar_new_element["DETAIL_PICTURE"])) {
                 $arFields["DETAIL_PICTURE"] = false;
             } else {
                 $arFields["DETAIL_PICTURE"] = $ar_new_element["DETAIL_PICTURE"];
             }
             if (is_array($arFields["PROPERTY_VALUES"]) && count($arFields["PROPERTY_VALUES"]) > 0) {
                 $i = 0;
                 $db_prop = CIBlockProperty::GetList(array(), array("IBLOCK_ID" => $arFields["IBLOCK_ID"], "CHECK_PERMISSIONS" => "N", "PROPERTY_TYPE" => "F"));
                 while ($arProp = $db_prop->Fetch()) {
                     $i++;
                     unset($arFields["PROPERTY_VALUES"][$arProp["CODE"]]);
                     unset($arFields["PROPERTY_VALUES"][$arProp["ID"]]);
                     $arFields["PROPERTY_VALUES"][$arProp["ID"]] = array();
                 }
                 if ($i > 0) {
                     //Delete previous files
                     $props = CIBlockElement::GetProperty($arFields["IBLOCK_ID"], $ID, "sort", "asc", array("PROPERTY_TYPE" => "F", "EMPTY" => "N"));
                     while ($arProp = $props->Fetch()) {
                         $arFields["PROPERTY_VALUES"][$arProp["ID"]][$arProp['PROPERTY_VALUE_ID']] = array("VALUE" => array("del" => "Y"), "DESCRIPTION" => false);
                     }
                     //Add copy from history
                     $arDup = array();
                     //This is cure for files duplication bug (just save element one more time)
                     $props = CIBlockElement::GetProperty($arFields["IBLOCK_ID"], $NID, "sort", "asc", array("PROPERTY_TYPE" => "F", "EMPTY" => "N"));
                     while ($arProp = $props->Fetch()) {
                         if (!array_key_exists($arProp["VALUE"], $arDup)) {
                             $arFields["PROPERTY_VALUES"][$arProp["ID"]][$arProp['PROPERTY_VALUE_ID']] = array("VALUE" => $arProp["VALUE"], "DESCRIPTION" => $arProp["DESCRIPTION"]);
                             $arDup[$arProp["VALUE"]] = true;
                             //This is cure for files duplication bug
                         }
                     }
                 }
             }
         } else {
             if (array_key_exists("PREVIEW_PICTURE", $arFields)) {
                 CFile::SaveForDB($arFields, "PREVIEW_PICTURE", "iblock");
             }
             if (array_key_exists("DETAIL_PICTURE", $arFields)) {
                 CFile::SaveForDB($arFields, "DETAIL_PICTURE", "iblock");
             }
         }
         unset($arFields["IBLOCK_ID"]);
         unset($arFields["WF_NEW"]);
         unset($arFields["IBLOCK_SECTION_ID"]);
         $bTimeStampNA = false;
         if (is_set($arFields, "TIMESTAMP_X") && ($arFields["TIMESTAMP_X"] === NULL || $arFields["TIMESTAMP_X"] === false)) {
             $bTimeStampNA = true;
             unset($arFields["TIMESTAMP_X"]);
         }
         $strUpdate = $DB->PrepareUpdate("b_iblock_element", $arFields, "iblock");
         if (strlen($strUpdate) > 0) {
             $strUpdate .= ", ";
         }
         $strSql = "UPDATE b_iblock_element SET " . $strUpdate . ($bTimeStampNA ? "TIMESTAMP_X=TIMESTAMP_X" : "TIMESTAMP_X=now()") . " WHERE ID=" . $ID;
         $DB->Query($strSql, false, "FILE: " . __FILE__ . "<br> LINE: " . __LINE__);
         if (array_key_exists("PROPERTY_VALUES", $arFields) && is_array($arFields["PROPERTY_VALUES"]) && count($arFields["PROPERTY_VALUES"]) > 0) {
             CIBlockElement::SetPropertyValues($ID, $ar_element["IBLOCK_ID"], $arFields["PROPERTY_VALUES"]);
         }
         if (is_set($arFields, "IBLOCK_SECTION")) {
             CIBlockElement::SetElementSection($ID, $arFields["IBLOCK_SECTION"], false, $arIBlock["RIGHTS_MODE"] === "E" ? $arIBlock["ID"] : 0);
         }
         if ($arIBlock["RIGHTS_MODE"] === "E") {
             $obElementRights = new CIBlockElementRights($arIBlock["ID"], $ID);
             if (array_key_exists("RIGHTS", $arFields) && is_array($arFields["RIGHTS"])) {
                 $obElementRights->SetRights($arFields["RIGHTS"]);
             }
         }
         if (array_key_exists("IPROPERTY_TEMPLATES", $arFields)) {
             $ipropTemplates = new \Bitrix\Iblock\InheritedProperty\ElementTemplates($arIBlock["ID"], $ID);
             $ipropTemplates->set($arFields["IPROPERTY_TEMPLATES"]);
         }
         if ($bUpdateSearch) {
             CIBlockElement::UpdateSearch($ID, true);
         }
         if ($bWorkFlow) {
             CIBlockElement::WF_CleanUpHistoryCopies($ID);
         }
         //Restore saved values
         if ($SAVED_PREVIEW_PICTURE !== false) {
             $arFields["PREVIEW_PICTURE_ID"] = $arFields["PREVIEW_PICTURE"];
             $arFields["PREVIEW_PICTURE"] = $SAVED_PREVIEW_PICTURE;
         } else {
             unset($arFields["PREVIEW_PICTURE"]);
         }
         if ($SAVED_DETAIL_PICTURE !== false) {
             $arFields["DETAIL_PICTURE_ID"] = $arFields["DETAIL_PICTURE"];
             $arFields["DETAIL_PICTURE"] = $SAVED_DETAIL_PICTURE;
         } else {
             unset($arFields["DETAIL_PICTURE"]);
         }
         if ($arIBlock["FIELDS"]["LOG_ELEMENT_EDIT"]["IS_REQUIRED"] == "Y") {
             $USER_ID = is_object($USER) ? intval($USER->GetID()) : 0;
             $arEvents = GetModuleEvents("main", "OnBeforeEventLog", true);
             if (empty($arEvents) || ExecuteModuleEventEx($arEvents[0], array($USER_ID)) === false) {
                 $rsElement = CIBlockElement::GetList(array(), array("=ID" => $ID, "CHECK_PERMISSIONS" => "N", "SHOW_NEW" => "Y"), false, false, array("ID", "NAME", "LIST_PAGE_URL", "CODE"));
                 $arElement = $rsElement->GetNext();
                 $res = array("ID" => $ID, "CODE" => $arElement["CODE"], "NAME" => $arElement["NAME"], "ELEMENT_NAME" => $arIBlock["ELEMENT_NAME"], "USER_ID" => $USER_ID, "IBLOCK_PAGE_URL" => $arElement["LIST_PAGE_URL"]);
                 CEventLog::Log("IBLOCK", "IBLOCK_ELEMENT_EDIT", "iblock", $arIBlock["ID"], serialize($res));
             }
         }
         $Result = true;
         /************* QUOTA *************/
         $_SESSION["SESS_RECOUNT_DB"] = "Y";
         /************* QUOTA *************/
     }
     $arFields["ID"] = $ID;
     $arFields["IBLOCK_ID"] = $ar_element["IBLOCK_ID"];
     $arFields["RESULT"] =& $Result;
     if (isset($arFields["PREVIEW_PICTURE"]) && $arFields["PREVIEW_PICTURE"]["COPY_FILE"] == "Y" && $arFields["PREVIEW_PICTURE"]["copy"]) {
         @unlink($arFields["PREVIEW_PICTURE"]["tmp_name"]);
         @rmdir(dirname($arFields["PREVIEW_PICTURE"]["tmp_name"]));
     }
     if (isset($arFields["DETAIL_PICTURE"]) && $arFields["DETAIL_PICTURE"]["COPY_FILE"] == "Y" && $arFields["DETAIL_PICTURE"]["copy"]) {
         @unlink($arFields["DETAIL_PICTURE"]["tmp_name"]);
         @rmdir(dirname($arFields["DETAIL_PICTURE"]["tmp_name"]));
     }
     foreach (GetModuleEvents("iblock", "OnAfterIBlockElementUpdate", true) as $arEvent) {
         ExecuteModuleEventEx($arEvent, array(&$arFields));
     }
     if (defined("BX_COMP_MANAGED_CACHE")) {
         $GLOBALS["CACHE_MANAGER"]->ClearByTag("iblock_id_" . $arIBlock["ID"]);
     }
     return $Result;
 }
 protected function processActionCommit()
 {
     $this->checkRequiredPostParams(array('editSessionId'));
     if ($this->errorCollection->hasErrors()) {
         $this->sendJsonErrorResponse();
     }
     $this->checkUpdatePermissions();
     $currentSession = $this->getEditSessionByCurrentUser((int) $this->request->getPost('editSessionId'));
     if (!$currentSession) {
         $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_FIND_EDIT_SESSION'), self::ERROR_COULD_NOT_FIND_EDIT_SESSION)));
         $this->sendJsonErrorResponse();
     }
     $tmpFile = \CTempFile::getFileName(uniqid('_wd'));
     checkDirPath($tmpFile);
     $fileData = new FileData();
     $fileData->setId($currentSession->getServiceFileId());
     $fileData->setSrc($tmpFile);
     $newNameFileAfterConvert = null;
     if ($this->documentHandler->isNeedConvertExtension($this->file->getExtension())) {
         $newNameFileAfterConvert = getFileNameWithoutExtension($this->file->getName()) . '.' . $this->documentHandler->getConvertExtension($this->file->getExtension());
         $fileData->setMimeType(TypeFile::getMimeTypeByFilename($newNameFileAfterConvert));
     } else {
         $fileData->setMimeType(TypeFile::getMimeTypeByFilename($this->file->getName()));
     }
     $fileData = $this->documentHandler->downloadFile($fileData);
     if (!$fileData) {
         if ($this->documentHandler->isRequiredAuthorization()) {
             $this->sendNeedAuth();
         }
         $this->errorCollection->add($this->documentHandler->getErrors());
         $this->sendJsonErrorResponse();
     }
     $this->deleteEditSession($currentSession);
     $oldName = $this->file->getName();
     //rename in cloud service
     $renameInCloud = $fileData->getName() && $fileData->getName() != $this->file->getName();
     if ($newNameFileAfterConvert || $renameInCloud) {
         if ($newNameFileAfterConvert && $renameInCloud) {
             $newNameFileAfterConvert = getFileNameWithoutExtension($fileData->getName()) . '.' . getFileExtension($newNameFileAfterConvert);
         }
         $this->file->rename($newNameFileAfterConvert);
     }
     $fileArray = \CFile::makeFileArray($tmpFile);
     $fileArray['name'] = $this->file->getName();
     $fileArray['type'] = $fileData->getMimeType();
     $fileArray['MODULE_ID'] = Driver::INTERNAL_MODULE_ID;
     /** @noinspection PhpDynamicAsStaticMethodCallInspection */
     $fileId = \CFile::saveFile($fileArray, Driver::INTERNAL_MODULE_ID);
     if (!$fileId) {
         \CFile::delete($fileId);
         $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_SAVE_FILE'), self::ERROR_COULD_NOT_SAVE_FILE)));
         $this->sendJsonErrorResponse();
     }
     $versionModel = $this->file->addVersion(array('ID' => $fileId, 'FILE_SIZE' => $fileArray['size']), $this->getUser()->getId(), true);
     if (!$versionModel) {
         \CFile::delete($fileId);
         $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_ADD_VERSION'), self::ERROR_COULD_NOT_ADD_VERSION)));
         $this->errorCollection->add($this->file->getErrors());
         $this->sendJsonErrorResponse();
     }
     if ($this->isLastEditSessionForFile()) {
         $this->deleteFile($currentSession, $fileData);
     }
     $this->sendJsonSuccessResponse(array('objectId' => $this->file->getId(), 'newName' => $this->file->getName(), 'oldName' => $oldName));
 }
    function NewMediaObject($params)
    {
        global $USER, $DB;
        $blogId = IntVal(CBlogMetaWeblog::DecodeParams($params[0]["#"]["value"][0]["#"]));
        $user = CBlogMetaWeblog::DecodeParams($params[1]["#"]["value"][0]["#"]);
        $password = CBlogMetaWeblog::DecodeParams($params[2]["#"]["value"][0]["#"]);
        $arImage = $params[3]["#"]["value"][0]["#"]["struct"][0]["#"]["member"];
        foreach ($arImage as $val) {
            $arImageInfo[$val["#"]["name"][0]["#"]] = CBlogMetaWeblog::DecodeParams($val["#"]["value"][0]["#"]);
        }
        if (CBlogMetaWeblog::Authorize($user, $password)) {
            $result = '';
            $userId = $USER->GetID();
            if (IntVal($blogId) > 0) {
                $dbBlog = CBlog::GetList(array(), array("GROUP_SITE_ID" => SITE_ID, "ACTIVE" => "Y", "ID" => $blogId), false, false, array("ID", "URL", "NAME"));
                if ($arBlog = $dbBlog->GetNext()) {
                    $filename = trim(str_replace("\\", "/", trim($arImageInfo["name"])), "/");
                    $DIR_NAME = CTempFile::GetDirectoryName(12);
                    $FILE_NAME = rel2abs($DIR_NAME, "/" . $filename);
                    if (strlen($FILE_NAME) > 1 && $FILE_NAME === "/" . $filename) {
                        $ABS_FILE_NAME = $DIR_NAME . $FILE_NAME;
                    } else {
                        $ABS_FILE_NAME = "";
                    }
                    CheckDirPath($DIR_NAME);
                    if (strlen($ABS_FILE_NAME) > 0 && ($fp = fopen($ABS_FILE_NAME, "ab"))) {
                        $result = fwrite($fp, $arImageInfo["bits"]);
                        if ($result !== (function_exists("mb_strlen") ? mb_strlen($arImageInfo["bits"], 'latin1') : strlen($arImageInfo["bits"]))) {
                            return '<fault>
									<value>
										<struct>
											<member>
												<name>faultCode</name>
												<value><int>3</int></value>
												</member>
											<member>
												<name>faultString</name>
												<value><string>Error on saving media object</string></value>
												</member>
											</struct>
										</value>
									</fault>';
                        }
                        fclose($fp);
                    } else {
                        return '<fault>
								<value>
									<struct>
										<member>
											<name>faultCode</name>
											<value><int>3</int></value>
											</member>
										<member>
											<name>faultString</name>
											<value><string>Error on saving media object</string></value>
											</member>
										</struct>
									</value>
								</fault>';
                    }
                    $arFields = array("BLOG_ID" => $arBlog["ID"], "USER_ID" => $userId, "=TIMESTAMP_X" => $DB->GetNowFunction(), "FILE_ID" => array("name" => $arImageInfo["name"], "tmp_name" => $ABS_FILE_NAME, "MODULE_ID" => "blog", "type" => $arImageInfo["type"]));
                    $imageId = CBlogImage::Add($arFields);
                    $arImg = CBlogImage::GetByID($imageId);
                    $arFile = CFile::GetFileArray($arImg["FILE_ID"]);
                    $path = $arFile["SRC"];
                    $dbSite = CSite::GetByID(SITE_ID);
                    $arSite = $dbSite->Fetch();
                    $serverName = htmlspecialcharsEx($arSite["SERVER_NAME"]);
                    if (strlen($serverName) <= 0) {
                        if (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0) {
                            $serverName = SITE_SERVER_NAME;
                        } else {
                            $serverName = COption::GetOptionString("main", "server_name", "www.bitrixsoft.com");
                        }
                    }
                    if (strlen($path) > 0) {
                        return '<params>
							<param>
								<value>
									<struct>
									<member>
									<name>url</name>
									<value>
									<string>' . CHTTP::URN2URI($path, $serverName) . '</string>
									</value>
									</member>
									</struct>
								</value>
							</param>
						</params>';
                    }
                }
            }
            return '<fault>
				<value>
					<struct>
						<member>
							<name>faultCode</name>
							<value><int>3</int></value>
							</member>
						<member>
							<name>faultString</name>
							<value><string>Error on saving media object</string></value>
							</member>
						</struct>
					</value>
				</fault>';
        } else {
            return '<fault>
				<value>
					<struct>
						<member>
							<name>faultCode</name>
							<value><int>3</int></value>
							</member>
						<member>
							<name>faultString</name>
							<value><string>' . $arAuthResult["MESSAGE"] . '</string></value>
							</member>
						</struct>
					</value>
				</fault>';
        }
    }
Exemple #30
0
 public static function OnFileSave(&$arFile, $strFileName, $strSavePath, $bForceMD5 = false, $bSkipExt = false)
 {
     if (!$arFile["tmp_name"] && !array_key_exists("content", $arFile)) {
         return false;
     }
     if (array_key_exists("bucket", $arFile)) {
         $bucket = $arFile["bucket"];
     } else {
         $bucket = CCloudStorage::FindBucketForFile($arFile, $strFileName);
     }
     if (!is_object($bucket)) {
         return false;
     }
     if (!$bucket->Init()) {
         return false;
     }
     $copySize = false;
     $subDir = "";
     $filePath = "";
     if (array_key_exists("content", $arFile)) {
         $arFile["tmp_name"] = CTempFile::GetFileName($arFile["name"]);
         CheckDirPath($arFile["tmp_name"]);
         $fp = fopen($arFile["tmp_name"], "ab");
         if ($fp) {
             fwrite($fp, $arFile["content"]);
             fclose($fp);
         }
     }
     if (array_key_exists("bucket", $arFile)) {
         $newName = bx_basename($arFile["tmp_name"]);
         $prefix = $bucket->GetFileSRC("/");
         $subDir = substr($arFile["tmp_name"], strlen($prefix));
         $subDir = substr($subDir, 0, -strlen($newName) - 1);
     } else {
         if ($bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N") == "Y") {
             if (COption::GetOptionString("main", "convert_original_file_name", "Y") == "Y") {
                 $newName = CCloudStorage::translit($strFileName);
             } else {
                 $newName = $strFileName;
             }
         } else {
             $strFileExt = $bSkipExt == true ? '' : strrchr($strFileName, ".");
             $newName = md5(uniqid(mt_rand(), true)) . $strFileExt;
         }
         //check for double extension vulnerability
         $newName = RemoveScriptExtension($newName);
         while (true) {
             $strRand = md5(mt_rand());
             $strRand = substr($strRand, 0, 3) . "/" . $strRand;
             if (substr($strSavePath, -1) == "/") {
                 $subDir = $strSavePath . $strRand;
             } else {
                 $subDir = $strSavePath . "/" . $strRand;
             }
             $subDir = ltrim($subDir, "/");
             $filePath = "/" . $subDir . "/" . $newName;
             if (!$bucket->FileExists($filePath)) {
                 break;
             }
         }
         $targetPath = $bucket->GetFileSRC("/");
         if (strpos($arFile["tmp_name"], $targetPath) === 0) {
             $arDbFile = array("SUBDIR" => "", "FILE_NAME" => substr($arFile["tmp_name"], strlen($targetPath)), "CONTENT_TYPE" => $arFile["type"]);
             $copyPath = $bucket->FileCopy($arDbFile, $filePath);
             if (!$copyPath) {
                 return false;
             }
             $copySize = $bucket->GetFileSize("/" . urldecode(substr($copyPath, strlen($targetPath))));
         } else {
             $imgArray = CFile::GetImageSize($arFile["tmp_name"], true, false);
             if (is_array($imgArray) && $imgArray[2] == IMAGETYPE_JPEG) {
                 $exifData = CFile::ExtractImageExif($arFile["tmp_name"]);
                 if ($exifData && isset($exifData['Orientation'])) {
                     $properlyOriented = CFile::ImageHandleOrientation($exifData['Orientation'], $arFile["tmp_name"]);
                     if ($properlyOriented) {
                         $jpgQuality = intval(COption::GetOptionString('main', 'image_resize_quality', '95'));
                         if ($jpgQuality <= 0 || $jpgQuality > 100) {
                             $jpgQuality = 95;
                         }
                         imagejpeg($properlyOriented, $arFile["tmp_name"], $jpgQuality);
                     }
                 }
             }
             if (!$bucket->SaveFile($filePath, $arFile)) {
                 return false;
             }
         }
     }
     $arFile["HANDLER_ID"] = $bucket->ID;
     $arFile["SUBDIR"] = $subDir;
     $arFile["FILE_NAME"] = $newName;
     $arFile["WIDTH"] = 0;
     $arFile["HEIGHT"] = 0;
     if (array_key_exists("bucket", $arFile)) {
         $arFile["WIDTH"] = $arFile["width"];
         $arFile["HEIGHT"] = $arFile["height"];
         $arFile["size"] = $arFile["file_size"];
     } elseif ($copySize !== false) {
         $arFile["size"] = $copySize;
         $bucket->IncFileCounter($copySize);
     } else {
         $bucket->IncFileCounter(filesize($arFile["tmp_name"]));
         $flashEnabled = !CFile::IsImage($arFile["ORIGINAL_NAME"], $arFile["type"]);
         $imgArray = CFile::GetImageSize($arFile["tmp_name"], true, $flashEnabled);
         if (is_array($imgArray)) {
             $arFile["WIDTH"] = $imgArray[0];
             $arFile["HEIGHT"] = $imgArray[1];
         }
     }
     if (isset($arFile["old_file"])) {
         CFile::DoDelete($arFile["old_file"]);
     }
     return true;
 }