bitrix

CSV Выгрузка

21.11.2012 Bitrix, php, php скрипты , , ,

<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");

	CModule::IncludeModule("iblock");

		$handle = fopen("tb.csv", "r");
		$csv    = array();

		while ( !feof( $handle ) ) {

			$line  = fgets($handle);
			$data  = explode(";", $line);
			$csv[] = $data;

		}

		$rs = new CDBResult;
		$el = new CIBlockElement;

		$rs->InitFromArray($csv);
		$rs->NavStart(1);

		$naumberPageGet = $rs->NavNum;
		$thisPage       = $_GET["PAGEN_".$naumberPageGet];

		if( !isset( $_GET["PAGEN_".$naumberPageGet] ) ){

			$nextPge = "PAGEN_".$naumberPageGet."=2";

		}else{

			if($rs->NavPageCount > $thisPage){
				$thisPage+=1;
				$nextPge = "PAGEN_".$naumberPageGet."=".$thisPage;
			}

		}

		if($rs->IsNavPrint())
		{
			 echo "<p>"; $rs->NavPrint("Элементы"); echo "</p>";
		}

		####
		$clearArray = array();

		$el = new CIBlockElement;

		while($test = $rs->Fetch()){

			$PROP = array();
			$PROP['RATE_GROUP']     = $test[0];
			$PROP['SUM']            = $test[1];
			$PROP['COEFF_DAMAGE'][] = Array("VALUE" => $test[2],"DESCRIPTION" => "");
			$PROP['COEFF_DAMAGE'][] = Array("VALUE" => $test[3],"DESCRIPTION" => "");
			$PROP['COEFF_DAMAGE'][] = Array("VALUE" => $test[4],"DESCRIPTION" => "");
			$PROP['COEFF_DAMAGE'][] = Array("VALUE" => $test[5],"DESCRIPTION" => "");
			$PROP['COEFF_DAMAGE'][] = Array("VALUE" => $test[6],"DESCRIPTION" => "");
			$PROP['COEFF_DAMAGE'][] = Array("VALUE" => $test[7],"DESCRIPTION" => "");

			$arLoadProductArray     = Array(
				"MODIFIED_BY"       => $USER->GetID(), // элемент изменен текущим пользователем
				"IBLOCK_SECTION_ID" => false,          // элемент лежит в корне раздела
				"IBLOCK_ID"         => 34,
				"PROPERTY_VALUES"   => $PROP,
				"NAME"              => $test[0],
				"ACTIVE"            => "Y",            // активен
			);

			// if($PRODUCT_ID = $el->Add($arLoadProductArray))
				// itdbg("New ID: ".$PRODUCT_ID);
			// else
				// itdbg("Error: ".$el->LAST_ERROR,true);

			itdbg($arLoadProductArray,false,2);
			echo '<pre>';
			var_dump($arLoadProductArray);
			echo '</pre>';

		}
		###

		$nPage = $rs->NavPageNomer;

		if($thisPage == $nPage){
			itdbg('exi',true, 2);
		}
?>
		<script>
		function second_passed() {
			window.document.location.href = "<?=$APPLICATION->GetCurPageParam($nextPge, array("PAGEN_".$naumberPageGet,"MUS_IMPORT","MUS_TYPE_PROCEDURE")); ?>";
		}
		setTimeout(second_passed, 1000);
		</script>

BITRIX копирование ИБ

09.11.2012 Bitrix, php скрипты No comments ,


require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
CModule::IncludeModule("iblock");
    if(intval($_REQUEST["IBLOCK_ID_FIELDS"])>0){
        $bError = false;
        $IBLOCK_ID = intval($_REQUEST["IBLOCK_ID_FIELDS"]);
        $ib = new CIBlock;
        $arFields = CIBlock::GetArrayByID($IBLOCK_ID);
        $arFields["GROUP_ID"] = CIBlock::GetGroupPermissions($IBLOCK_ID);
        $arFields["NAME"] = $arFields["NAME"]."_new";
        unset($arFields["ID"]);
        if($_REQUEST["IBLOCK_TYPE_ID"]!="empty")
            $arFields["IBLOCK_TYPE_ID"]=$_REQUEST["IBLOCK_TYPE_ID"];
        $ID = $ib->Add($arFields);
            if(intval($ID)<=0)
                $bError = true;        
        if($_REQUEST["IBLOCK_ID_PROPS"]!="empty")
            $iblock_prop=intval($_REQUEST["IBLOCK_ID_PROPS"]);
        else
            $iblock_prop=$IBLOCK_ID;

        $iblock_prop_new = $ID;
        $ibp = new CIBlockProperty;
        $properties = CIBlockProperty::GetList(Array("sort"=>"asc", "name"=>"asc"), Array("ACTIVE"=>"Y", "IBLOCK_ID"=>$iblock_prop));
        while ($prop_fields = $properties->GetNext()){
            if($prop_fields["PROPERTY_TYPE"] == "L"){
                $property_enums = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$iblock_prop, "CODE"=>$prop_fields["CODE"]));
                while($enum_fields = $property_enums->GetNext()){
                    $prop_fields["VALUES"][] = Array(
                      "VALUE" => $enum_fields["VALUE"],
                      "DEF" => $enum_fields["DEF"],
                      "SORT" => $enum_fields["SORT"]
                    );
                }
            }
            $prop_fields["IBLOCK_ID"]=$iblock_prop_new;
            unset($prop_fields["ID"]);
            foreach($prop_fields as $k=>$v){
                if(!is_array($v))$prop_fields[$k]=trim($v);
                if($k{0}=='~') unset($prop_fields[$k]);
            }
            $PropID = $ibp->Add($prop_fields);
            if(intval($PropID)<=0)
                $bError = true;
        }
        if(!$bError && $IBLOCK_ID>0)
            LocalRedirect($APPLICATION->GetCurPageParam("success=Y",array("success","IBLOCK_ID_FIELDS")));
        else 
            LocalRedirect($APPLICATION->GetCurPageParam("error=Y",array("success","IBLOCK_ID_FIELDS")));
    }
    $str .='<form action='.$APPLICATION->GetCurPageParam().' method="post"><table>';    
    if($_REQUEST["success"]=="Y") $str .='<tr><td colspan="2"><font color="green">ИБ успешно скопирован</font><br/></td></tr>';
    elseif($_REQUEST["error"]=="Y") $str .='<tr><td colspan="2"><font color="red">Произошла ошибка</font><br/></td></tr>';
    $str .='<tr><td colspan="2"><b>Копируем мета данные ИБ в новый ИБ</b><br/></td></tr>';
    $res = CIBlock::GetList(Array(),Array(),true);
        while($ar_res = $res->Fetch())
            $arRes[]=$ar_res;
    $str .='<tr><td>Копируем ИБ:<br><select name="IBLOCK_ID_FIELDS">';
    foreach($arRes as $vRes)    
        $str .= '<option value='.$vRes['ID'].'>'.$vRes['NAME'].' ['.$vRes["ID"].']</option>';
    $str .='</select></td>';
    $str .='<td>Копируем в новый ИБ свойства другого ИБ: *<br><select name="IBLOCK_ID_PROPS">';
    $str .='<option value="empty">';
    foreach($arRes as $vRes)    
        $str .= '<option value='.$vRes['ID'].'>'.$vRes['NAME'].' ['.$vRes["ID"].']</option>';
    $str .='</select></td></tr>';
    $str .='<tr><td colspan="2">Копируем ИБ в тип:<br><select name="IBLOCK_TYPE_ID">';
    $str .='<option value="empty">';
    $db_iblock_type = CIBlockType::GetList();
    while($ar_iblock_type = $db_iblock_type->Fetch()){
       if($arIBType = CIBlockType::GetByIDLang($ar_iblock_type["ID"], LANG))
          $str .= '<option value='.$ar_iblock_type["ID"].'>'.htmlspecialcharsex($arIBType["NAME"])."</option>";
    }
    $str .='</select></td></tr>';
    $str .='<tr><td colspan="2"><br/>* если значение не указано мета данные ИБ секции "Свойства" берутся из ИБ первого поля</td></tr>';
    $str .='<tr><td colspan="2"><input type="submit" value="копируем"></td></tr>';
    $str .='</table></form>';    
    echo $str;

Транслитерация и создание символьного кода свойства

25.10.2012 Bitrix No comments , , ,

AddEventHandler("iblock", "OnBeforeIBlockPropertyAdd", Array("IblockModifer", "OnBeforeIBlockPropertyAddHandler"));
AddEventHandler("iblock", "OnBeforeIBlockPropertyUpdate", Array("IblockModifer", "OnBeforeIBlockPropertyUpdateHandler"));

class IblockModifer
{
    public function OnBeforeIBlockPropertyAddHandler(&$arFields)
    {
        if($arFields['IBLOCK_ID'] == 10 and empty($arFields["CODE"])){
            $arParams = array("replace_space"=>"_","replace_other"=>"_", 'change_case' => 'U', 'max_len' => 20);
            $tempCode = Cutil::translit($arFields['NAME'],"ru",$arParams);
            $arFields['CODE'] = $tempCode;
        }
    }

    public function OnBeforeIBlockPropertyUpdateHandler(&$arFields)
    {
            if($arFields['IBLOCK_ID'] == 10 and empty($arFields["CODE"])){
            $arParams = array("replace_space"=>"_","replace_other"=>"_", 'change_case' => 'U', 'max_len' => 20);
            $tempCode = Cutil::translit($arFields['NAME'],"ru",$arParams);
            $arFields['CODE'] = $tempCode;
        }
    }
}

Вставка баннеров в закешированный контент

25.10.2012 Bitrix 2 комментария , ,

AddEventHandler("main", "OnEndBufferContent", "ShowBannerInsideNews");
function ShowBannerInsideNews(&$content){
	if (CModule::IncludeModule("advertising")){
		if (strpos($content, '#BANNER_INSIDE_INSTS_LIST#') !== false){
			$crop_content = explode('<span>#BANNER_INSIDE_INSTS_LIST#</span>',$content);
			$aEarsAdv = array();
			for($i=0,$j=1; $i<$j; $i++){
				$sAdv = CAdvBanner::GetRandom('insts_list');
				if(!empty($sAdv)){
					$AdvWeightSort[] = $sAdv['WEIGHT'];
					$AdvIdSort[] = $sAdv['ID'];
					$aEarsAdv[] = $sAdv;
					$j++;
				}
				else
					break;
			}

			array_multisort($AdvWeightSort,SORT_ASC,$AdvIdSort,SORT_ASC,$aEarsAdv);

			$content = null;
			foreach($crop_content as $croped_key=>$croped){
				$banner = CAdvBanner::GetHTML($aEarsAdv[$croped_key]);
				$content .= $croped.$banner;
			}
		}
	}
}

Быстрое удаление секций

25.10.2012 Bitrix No comments

require($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_admin_before.php'); 

CModule::IncludeModule('iblock'); 
$arFilter=array('IBLOCK_ID'=>ID_инфоблока); 
$rsItems=CIBlockSection::GetList(array(), $arFilter, false, array('ID'));
$rsItems->NavStart(50);
$count=0; 
while($arItem = $rsItems->GetNext(false, false)) 
{ 
   $count++; 
   if(CIBlockSection::Delete($arItem['ID']))
       echo '<div>Удален раздел '.$arItem['ID'].'</div>'; 
   else 
       echo '<div>Ошибка удаления раздела '.$arItem['ID'].'</div>'; 
} 
    
if($count==0) 
    echo '<div>Все!</div>'; 
else 
    die('<div>Удаление разделов... </div> <script>document.location="?delete";</script>'); 

BITRIX 404

12.10.2012 Bitrix, php скрипты No comments ,

AddEventHandler("main", "OnEpilog", "Redirect404");
function Redirect404() {
	if(defined('ERROR_404')){
		@define("PATH_TO_404", "/404.php");
	}
	
    if(!defined('ADMIN_SECTION') &&  defined("ERROR_404") &&  defined("PATH_TO_404") &&  file_exists($_SERVER["DOCUMENT_ROOT"].PATH_TO_404))
	{
        //LocalRedirect("/404.php", "404 Not Found");
        global $APPLICATION;
        $APPLICATION->RestartBuffer();
        CHTTP::SetStatus("404 Not Found");
        include($_SERVER["DOCUMENT_ROOT"].SITE_TEMPLATE_PATH."/header.php");
        include($_SERVER["DOCUMENT_ROOT"].PATH_TO_404);
        include($_SERVER["DOCUMENT_ROOT"].SITE_TEMPLATE_PATH."/footer.php");
    }
}

cphpcache bitrix $obCACHE = new CPHPCache; пример 2

03.10.2012 Bitrix No comments ,

$obCACHE = new CPHPCache;
$iCACHE_TIME=3600;
$strCACHE_ID="AreaMaxPlot";
$strCACHE_PATH = "/object.area";
if (isset($_REQUEST['clear_cache']) && $_REQUEST['clear_cache']=="Y"){ $obCACHE->Clean($strCACHE_ID,$strCACHE_PATH); }
if($obCACHE->InitCache($iCACHE_TIME,$strCACHE_ID,$strCACHE_PATH)) 
    {    
        $arrRESULT = $obCACHE->GetVars();
        $arrAreaMaxDat  = $arrRESULT['AreaMaxDat'];
    }else
        {
            $arrAreaMaxDat='test';
        }
 
if($obCACHE->StartDataCache()) {
    $obCACHE->EndDataCache(array("AreaMaxDat"=>$arrAreaMaxDat));
}

bitrix $obCACHE = new CPHPCache; пример

03.10.2012 Bitrix No comments ,

bitrix $obCACHE = new CPHPCache; пример

$obCACHE = new CPHPCache;
$iCACHE_TIME=3600;
$strCACHE_ID="AreaMaxPlot";
$strCACHE_PATH = "/object.area";
if (isset($_REQUEST['clear_cache']) && $_REQUEST['clear_cache']=="Y"){ $obCACHE->Clean($strCACHE_ID,$strCACHE_PATH); }
if($iCACHE_TIME > 0 && $obCACHE->InitCache($iCACHE_TIME,$strCACHE_ID,$strCACHE_PATH)) 
    {    
        $arrRESULT = $obCACHE->GetVars();
        $arrAreaMaxDat  = $arrRESULT['AreaMaxDat'];
    }
if(!is_array($arrAreaMaxDat) || !count($arrAreaMaxDat)){
 $arrAreaMaxDat[] = 'test';
 $obCACHE->StartDataCache($iCACHE_TIME, $strCACHE_ID, $strCACHE_PATH);
 $obCACHE->EndDataCache(array("AreaMaxDat"=>$arrAreaMaxDat));
}	

bitrix jquery

27.09.2012 Bitrix, javascript No comments , , ,

bitrix jquery

CJSCore::Init(Array("jquery"));

Авторизация

12.09.2012 Bitrix No comments ,

$USER->Authorize(1);