<?php
include_once $GLOBALS['binn_include_path'].'prog/init.php';
include_once $GLOBALS['binn_include_path'].'prog/pl_site_users/list_site_users.inc.php';
require_once $GLOBALS['binn_include_path'].'cms/lang/ru/kernel.lng.php';

if (!isset($_SESSION['binn_file_rights']))
    $_SESSION['binn_file_rights'] = $GLOBALS['binn_file_rights'];
if (!isset($_SESSION['binn_cms_lib_path']))
    $_SESSION['binn_cms_lib_path'] = $GLOBALS['binn_include_path'].'cms/lib';
    
require_once $_SESSION['binn_cms_lib_path'].'/binnUploader.inc.php';
require_once $_SESSION['binn_cms_lib_path'].'/binnFunctions.inc.php';
    
//   
function resizeImage($srcImage, $srcPath, $destImage, $destPath, $newWidth, $newHeight)
{
    //  jpeg-
    $regs = substr($srcImage, strrpos($srcImage,".")+1, 4);
    error_reporting(E_ALL);
    $regs = strtolower($regs);
    switch($regs)
    {
        case "jpe":
        case "jpeg":
        case "jpg": $srcImg = imagecreatefromjpeg($srcPath.$srcImage); break;
        case "png": $srcImg = imagecreatefrompng($srcPath.$srcImage); break;
        case "gif":
        if (function_exists('imagecreatefromgif'))
        {
            $srcImg = imagecreatefromgif($srcPath.$srcImage); break;
        }
        default: return false;
    }
    //      
    $srcWidth = ImageSX( $srcImg );
    $srcHeight = ImageSY( $srcImg );

    //       
    //      , 
    //     

    $ratioWidth = $srcWidth/$newWidth;
    $ratioHeight = $srcHeight/$newHeight;

    if ($srcWidth > $newWidth || $srcHeight > $newHeight)
    {
        if($ratioWidth < $ratioHeight)
        {
            $destHeight = $newHeight;
            $destWidth = round($srcWidth/$ratioHeight, 0);
        }
        else
        {
            $destHeight = round($srcHeight/$ratioWidth, 0);
            $destWidth = $newWidth;
        }
    }
    else
    {
        $destHeight = $srcHeight;
        $destWidth = $srcWidth;
    }

    //         
    $destImg = function_exists('imagecreatetruecolor') ? imagecreatetruecolor($destWidth, $destHeight) : imagecreate($destWidth, $destHeight);
    //  srcImage ()  destImage ()
    imagecopyresampled($destImg, $srcImg, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);

    //    jpeg   90%(   )
    ImageJPEG($destImg, $destPath.$destImage, 90);

    //  
    ImageDestroy($srcImg);
    ImageDestroy($destImg);
    return true;
}

function checkFileType($type)
{
    $error = true;
    switch ($type)
    {
        case 'image/bmp':
        case 'image/pjpeg':
        case 'image/jpeg':
        case 'image/png':
            $error = false;
            break;
        case 'image/gif':
            if (function_exists('imagecreatefromgif'))
            {
                $error = false;
            }
            break;
    }
    
    return $error;
}

function uploadFile($imgIdent, $imgId, $imgPath, $iAllowedTypes)
{
    $iUploader = new binnUploader;
    $iSuccess = false;
    
    $imgExt = 'jpg';
    switch ($_FILES[$imgIdent]['type'])
    {
        case 'image/bmp':
            $imgExt = 'bmp';
            break;
        case 'image/png':
            $imgExt = 'png';
            break;
        case 'image/gif':
            $imgExt = 'gif';
            break;        
    }
    
    switch ($imgIdent)
    {
        case 'pl_imagelib_big':
            $imgName = $imgId.'.'.$imgExt;
            break;

        case 'pl_imagelib_middle':
            $imgName = $imgId.'_m.'.$imgExt;
            break;

        case 'pl_imagelib_small':
            $imgName = $imgId.'_s.'.$imgExt;
            break;
    }

    if ($iUploader->upload($imgIdent, $iAllowedTypes))
    {
        $iSuccess = $iUploader->save_file($imgPath, $imgName, 1);
    }    
    
    if ($iSuccess)
    {
        return $imgName;
    }
    else
    {
        return false;
    }
}

function binn_imagelib_add_form($im_cat_id, $temp_id, $im_big_width, $im_big_height, $im_middle_width, $im_middle_height, $im_small_width, $im_small_height, $auto_resize, $pre_moderate)
{
    if ($temp_id != -1)
    {
        //    
        $result = sql_query("SELECT it_add_form FROM binn_imagelib_templ WHERE it_id = '$temp_id'");
        if ($result)
        {
            list($it_add_form) = $result[0];
            $result = sql_query("SELECT bsm_system_code, bsm_template FROM binn_system_messages WHERE bsm_cat_ident='pl_imagelib' AND bsm_id_temp='$temp_id'");
            for($i=0;$i<count($result);$i++)
            {
                list($bsm_system_code, $bsm_template) = $result[$i];
                $sys_codes[$bsm_system_code] = $bsm_template;
            }
        }
        else
        {
            echo 'Fatal Error: No template selected!';
            return;
        }
    }
    else
    {
        echo 'Fatal Error: No template selected!';
        return;
    }

    //    ,   ,   
    $iAllowedTypes = array ("image/bmp" => " ", "image/gif" => " ", "image/pjpeg" => " ", "image/jpeg" => " ", "image/png" => " ");

    $system_msg = '';
    $user_id = 0;
    $user_name = $sys_codes['SMC_IMAGELIB_ANONYM'];
    $im_gal = ($pre_moderate == 1 ? 0 : 1);
    $im_title = '';
    $im_desc = '';
    
    //   
    $result = sql_query('SELECT cat_left, cat_right FROM binn_categs WHERE cat_id = '.$im_cat_id);
    list($c_left, $c_right) = $result[0];

    $result = sql_query("SELECT cat_id, cp_title, cat_level FROM binn_categs INNER JOIN binn_catprops ON (cat_prop_id = cp_id) WHERE cat_left >= $c_left AND cat_right <= $c_right AND cat_ident = 'pl_imagelib' ORDER BY cat_left");
    $im_category_options = '';
    for($i = 0; $i < count($result); $i++)
    {
        list($cat_id, $cp_title, $cat_level) = $result[$i];
        if ($i == 0) 
        {
            $postfix = $cat_level;
        }
        
        $cp_title = str_repeat('&nbsp;&nbsp;&nbsp;', $cat_level - $postfix).$cp_title;

        $im_category_options .= '<option value='.$cat_id.' '.(isset($_POST['pl_imagelib_categ']) && $_POST['pl_imagelib_categ'] == $cat_id ? 'selected' : '').'>'.$cp_title.'</option>';
    }

    //     
    if(isset($_SESSION['su_login']) && isset($_SESSION['su_id']))
    {
        $user_id = $_SESSION['su_id'];
        $user_name = $_SESSION['su_login'];
    }

    // ,    
    if(isset($_GET['imagelib_action']) && $_GET['imagelib_action'] == 'add')
    {
        $error = false;
        if(isset($_POST['pl_imagelib_categ']))
        {
            if (is_numeric($_POST['pl_imagelib_categ']))
            {
                $im_cat_id = intval($_POST['pl_imagelib_categ']);
            }
            else
            {
                $error = true;
            }
        }
     
        // ,             
        $res = sql_query("SELECT props.cp_closed FROM binn_categs categs, binn_catprops props WHERE categs.cat_id='$im_cat_id' AND props.cp_id=categs.cat_prop_id;");
        list($closed) = $res[0];
        if ($closed)
        {
            $rights_arr = array();
            $rights_arr['pl_imagelib_1']['value'] = 'pl_imagelib_add'; 
            $rights_arr['pl_imagelib_1']['name'] = ''; 
            $rights = binn_site_users_get_rights($im_cat_id, $rights_arr); 
            if (count($rights) == 0 || $rights['pl_imagelib_add'] == 0)
            {
                $system_msg = $sys_codes['SMC_IMAGELIB_NO_RIGHTS'];
                $error = true;
            }
        }
    
        //    .
        if((@is_uploaded_file($_FILES['pl_imagelib_big']['tmp_name']) && checkFileType($_FILES['pl_imagelib_big']['type'])) || (@is_uploaded_file($_FILES['pl_imagelib_small']['tmp_name']) && checkFileType($_FILES['pl_imagelib_small']['type'])) || (@is_uploaded_file($_FILES['pl_imagelib_middle']['tmp_name']) && checkFileType($_FILES['pl_imagelib_middle']['type'])))
        {
            $error = true;
        }

        $im_title = (isset($_POST['pl_imagelib_title']) ? strip_tags($_POST['pl_imagelib_title']) : '');
        $im_desc = (isset($_POST['pl_imagelib_desc']) ? strip_tags($_POST['pl_imagelib_desc']) : '');
            
        //   ,    
        if(!$error)
        {
            //  ,  ,    .     .
            $iLibPath = $GLOBALS['binn_imagelib_save_path'].'/'.$im_cat_id.'/';
            $iPath = str_replace('//', '/', $GLOBALS['binn_basedir'].$iLibPath);
            if (!file_exists($iPath))
                binn_mkpath($iLibPath, $GLOBALS['binn_file_rights']);
            
            $iAllowedTypes = array ("image/bmp" => " ", "image/gif" => " ", "image/pjpeg" => " ", "image/jpeg" => " ", "image/png" => " ");
            
            sql_query("INSERT INTO binn_imagelib (im_title, im_desc, im_gal, im_user_id, im_small, im_middle, im_big) VALUES ('$im_title', '$im_desc', '$im_gal', '$user_id', '', '', '')");
            $id = $GLOBALS['binnDbSql']->getInsertId();

            //    
            $i_big = '';
            $i_middle = '';
            $i_small = '';
            
            if(@is_uploaded_file($_FILES['pl_imagelib_big']['tmp_name']))
            {
                $i_big = uploadFile('pl_imagelib_big', $id, $iPath, $iAllowedTypes);
                if ($i_big)
                {
                    if ($auto_resize)
                    {
                        resizeImage($i_big, $iPath, $i_big, $iPath, $im_big_width, $im_big_height);
                    }
                    sql_query('UPDATE binn_imagelib SET im_big="'.$iLibPath.$i_big.'" WHERE im_id='.$id);
                }
                else
                {
                    $error = true;
                }
            }
            
            if (!$error)
            {
                if(@is_uploaded_file($_FILES['pl_imagelib_middle']['tmp_name']))
                {
                    $i_middle = uploadFile('pl_imagelib_middle', $id, $iPath, $iAllowedTypes);
                    if ($i_middle)
                    {
                        if ($auto_resize)
                        {
                            resizeImage($i_middle, $iPath, $i_middle, $iPath, $im_middle_width, $im_middle_height);
                        }
                        sql_query('UPDATE binn_imagelib SET im_middle="'.$iLibPath.$i_middle.'" WHERE im_id='.$id);
                    }
                    else
                    {
                        $error = true;
                    }
                }
                elseif ($i_big)
                {
                    $fname = explode('.', $i_big);
                    $i_middle = $fname[0].'_m.'.$fname[1];
                    resizeImage($i_big, $iPath, $i_middle, $iPath, $im_middle_width, $im_middle_height);
                    sql_query('UPDATE binn_imagelib SET im_middle="'.$iLibPath.$i_middle.'" WHERE im_id='.$id);
                }   
            }
            
            if (!$error)
            {
                if(@is_uploaded_file($_FILES['pl_imagelib_small']['tmp_name']))
                {
                    $i_small = uploadFile('pl_imagelib_small', $id, $iPath, $iAllowedTypes);
                    if ($i_small)
                    {
                        if ($auto_resize)
                        {
                            resizeImage($i_small, $iPath, $i_small, $iPath, $im_small_width, $im_small_height);
                        }
                        sql_query('UPDATE binn_imagelib SET im_small="'.$iLibPath.$i_small.'" WHERE im_id='.$id);
                    }
                    else
                    {
                        $error = true;
                    }
                }
                elseif ($i_big || $i_middle)
                {
                    $i_name = $i_big ? $i_big : $i_middle;
                    $fname = explode('.', $i_name);
                    $i_small = $fname[0].'_s.'.$fname[1];
                    resizeImage($i_name, $iPath, $i_small, $iPath, $im_small_width, $im_small_height);
                    sql_query('UPDATE binn_imagelib SET im_small="'.$iLibPath.$i_small.'" WHERE im_id='.$id);
                }   
            }
            
            if(!$i_middle && !$i_small && !$i_big)
            {
                $error = true;
            }
            if (!$i_big && !$error)
            {
                $i_big = $i_middle ? $i_middle : $i_small;
                sql_query('UPDATE binn_imagelib SET im_big="'.$iLibPath.$i_big.'" WHERE im_id='.$id);
            }
            if (!$i_middle && !$error)
            {
                sql_query('UPDATE binn_imagelib SET im_middle="'.$iLibPath.$i_small.'" WHERE im_id='.$id);
            }
            
            if (!$error)
            {
                sql_query("INSERT INTO binn_catlinks (cat_id, el_id, el_change_login, el_change_date, el_link) VALUES ('$im_cat_id', '$id', '$user_name', '".mktime()."', 0)");
                $system_msg = $sys_codes['SMC_IMAGELIB_IMAGE_ADDED'];
            }
            else
            {
                sql_query('DELETE FROM binn_imagelib WHERE im_id='.$id);
            }
        }
        
        if ($error && $system_msg == '')
        {
            $system_msg = $sys_codes['SMC_IMAGELIB_IMAGE_NOT_ADDED'];
        }
        else
        {
            $im_title = '';
            $im_desc = '';
        }
    }

    //    
    $it_add_form = str_replace(
        array('{SYSTEM_MESSAGE}', '{GLOBAL_USER_NAME}', '{GLOBAL_USER_ID}', '{FORM_ACTION}', '{ELEM_TITLE_VALUE}', '{ELEM_DESCR_VALUE}', '{ELEM_CATEGS_SELECT_OPTIONS}'),
        array($system_msg, $user_name, $user_id, $_SERVER['PHP_SELF'].'?'.($_SERVER['QUERY_STRING'] != '' ? $_SERVER['QUERY_STRING'].'&imagelib_action=add' : 'imagelib_action=add'), $im_title, $im_desc, $im_category_options),
        $it_add_form);
        
    echo eval('?> '.$it_add_form.'<?php ');
}
?>