<?PHP

if($member_db[1] > 3 or ($member_db[1] != 1 and $action == "doimagedelete")){ msg("error", "Доступ запрещен", "Вы не можете выполнять операции с картинками"); }



$allowed_extensions = array("gif", "jpg", "png", "bmp", "jpe", "jpeg");






// ********************************************************************************

// Show Preview of Image

// ********************************************************************************
if($action == "preview"){

echo <<<PREVIEWHTML


<HTML>
        <HEAD>
                <TITLE>Вставить картинку</TITLE>
                <script language='javascript'>
                        var NS = (navigator.appName=="Netscape")?true:false;

                        function fitPic() {
                                iWidth = (NS)?window.innerWidth:document.body.clientWidth;
                                iHeight = (NS)?window.innerHeight:document.body.clientHeight;
                                iWidth = document.images[0].width - iWidth;
                                iHeight = document.images[0].height - iHeight;
                                window.resizeBy(iWidth, iHeight-1);
                                self.focus();
                        };
                </script>
        </HEAD>
        <BODY bgcolor="#FFFFFF" onload='fitPic();' topmargin="0" marginheight="0" leftmargin="0" marginwidth="0">
                <script language='javascript'>
                        document.write( "<img src='$config_http_script_dir/data/upimages/$image' border=0>" );
                </script>
        </BODY>

</HTML>


PREVIEWHTML;

}
// ********************************************************************************

// Show Images List

// ********************************************************************************

elseif($action != "doimagedelete")

{

        if($action == "quick")

    {

            echo"<html>

                        <head>

                        <title>Insert Image</title>

                        <style type=\"text/css\">

                        <!--

                        select, option, textarea, input {

                         BORDER: #808080 1px solid;

                         COLOR: #000000;

                         FONT-SIZE: 11px;

                         FONT-FAMILY: Verdana; BACKGROUND-COLOR: #ffffff

                        }

                        BODY, TD {text-decoration: none; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt;}

                                    a:active,a:visited,a:link {font-size : 10px; color: #808080; font-family: verdana; text-decoration: none;}

                                    a:hover {font-size : 10px; color: darkblue; font-weight:bold; text-decoration: none; }
                                    .panel                { border: 1px dotted silver; background-color: #F7F6F4;}


                        -->

                        </style>

                        </head>

                        <body bgcolor=#FFFFFF>

                        <script language=\"javascript\" type=\"text/javascript\">

                        <!--

                        function insertimage(selectedImage) {
                         var area = '$area';

                                alternativeText = document.forms['properties'].alternativeText.value;
                                imageAlign = document.forms['properties'].imageAlign.value;
                                imageBorder = document.forms['properties'].imageBorder.value;


                                //finalImage = \" <img style=\\\"border:\"+ imageBorder +\"; vertical-align:\"+ imageAlign +\";\\\" alt=\\\"\"+ alternativeText +\"\\\" src=\\\"$config_http_script_dir/data/upimages/\"+ selectedImage +\"\\\">\";

                               finalImage = \" <img border=\\\"\"+ imageBorder +\"\\\" align=\\\"\"+ imageAlign +\"\\\" alt=\\\"\"+ alternativeText +\"\\\" src=\\\"$config_http_script_dir/data/upimages/\"+ selectedImage +\"\\\">\";
                        ";

                        if($wysiwyg){

                      echo"
                      MYRTE=window.opener.document.getElementById(area).contentWindow;
                      window.opener.currentRTE=area; MYRTE.document.execCommand('InsertImage', false, '-my-temp-img-url-');
                      replacement = \"$config_http_script_dir/data/upimages/\" + selectedImage + \"\\\" alt=\\\"\" + alternativeText + \"\\\" border=\\\"\" + imageBorder + \"\\\" align=\\\"\" + imageAlign;
                      MYRTE.document.body.innerHTML = MYRTE.document.body.innerHTML.replace(/-my-temp-img-url-/gi,replacement);

                      ";


                        }
                        else{ echo"opener.document.getElementById(area).value += finalImage;"; }

//                      echo"alert(finalImage);";

                        echo"

                                window.close();
                                //opener.document.getElementById(area).focus();


                        }

                        function PopupPic(sPicURL) {
                                window.open('$PHP_SELF?mod=images&action=preview&image='+sPicURL, '', 'resizable=1,HEIGHT=200,WIDTH=200');
                        }

                                window.resizeTo(410, 550);
                                self.focus();

                        //-->

                        </script>";

    }else{ echoheader("images","Manage Images"); }



// ********************************************************************************

// Upload Image(s)

// ********************************************************************************

if($subaction == "upload")
{



for ($image_i = 1; $image_i < ($images_number+1); $image_i++) {
     $current_image = 'image_'.$image_i;

     $image = $_FILES[$current_image]['tmp_name'];
     $image_name = $_FILES[$current_image]['name'];
     $image_name = str_replace(" ", "_", $image_name);

     $img_name_arr = explode(".",$image_name);
     $type = end($img_name_arr);


     if($image_name == ""){ $img_result .= "<br><font color=red>$current_image -> Укажите загружаемую картинку !!!</font>"; }
     elseif( !isset($overwrite) and file_exists($config_path_image_upload."/".$image_name)){ $img_result .= "<br><font color=red>$image_name -> Такая картинка уже есть !!!</font>";}
     elseif( !(in_array($type, $allowed_extensions) or in_array(strtolower($type), $allowed_extensions)) ){
               $img_result .= "<br><font color=red>$image_name ->Этот тип файла не позволяется!!!</font>";
     }
     else{  //Image is OK, upload it

              @copy($image, $config_path_image_upload."/".$image_name) or $img_result .= "<br><font color=red>$image_name ->Невозможно залить картинку на сервер.</font><br />Проверьте, есть ли такой тип файлов в php.ini вашего сервера.";
                    if(file_exists($config_path_image_upload."/".$image_name))
                    {
                     $img_result .= "<br><font color=green>$image_name -> Картинка загружена.</font>";
                     if($action == "quick"){
                        $img_result .= " <a title=\"Inser this image in the $my_area\" href=\"javascript:insertimage('$image_name');\">[insert it]</a>";
                     }
                    }//if file is uploaded succesfully

     }
}



}


//
// Add the JS for multyple image upload.
//
echo<<<HTMLJS

<script language='javascript'>

function AddRowsToTable() {
     var tbl = document.getElementById('tblSample');
     var lastRow = tbl.rows.length;

     // if there's no header row in the table, then iteration = lastRow + 1
     var iteration = lastRow+1;
     var row = tbl.insertRow(lastRow);

     var cellRight = row.insertCell(0);
     var el = document.createElement('input');
     el.setAttribute('type', 'file');
     el.setAttribute('name', 'image_' + iteration);
     el.setAttribute('size', '30');
     el.setAttribute('value', iteration);
     cellRight.appendChild(el);

     document.getElementById('images_number').value = iteration;
}
function RemoveRowFromTable() {
     var tbl = document.getElementById('tblSample');
     var lastRow = tbl.rows.length;
     if (lastRow > 1){
              tbl.deleteRow(lastRow - 1);
               document.getElementById('images_number').value =  document.getElementById('images_number').value - 1;
     }
}

</script>

HTMLJS;



echo<<<HTML
<form name="form" id="form" action="$PHP_SELF?mod=images" method="post" enctype="multipart/form-data">


<table border=0 cellpading=0 cellspacing=0  width=100%>
    <td height=33>
    <b>Загрузьте Изображение </b>
<table border=0 cellpading=0 cellspacing=0 class="panel" cellpadding=8>
    <tr>
    <td height=25>

<table  border="0" cellspacing="0" cellpadding="0" id="tblSample">
 <tr id="row">
  <td width="1" colspan="2"><input type="file" size="30" name="image_1"></td>
</tr>
</table>
<table border="0" cellspacing="0" cellpadding="0" style="margin-top:5px;">
 <tr>
  <td>
  <INPUT TYPE="SUBMIT" name="submit" VALUE="Загрузить" style="font-weight:bold;"> &nbsp;
   <input type=button value='-' style="font-weight:bold; width:22px;" title='Remove last file input box' onClick="RemoveRowFromTable();return false;">
   <input type=button value='+' style="font-weight:bold; width:22px;" title='Add another file input box' onClick="AddRowsToTable();return false;"> &nbsp;
   <input style="border:0px; background-color:#F7F6F4;" type=checkbox name=overwrite id=overwrite value=1><label title='Overwrite file(s) if exist' for=overwrite> Наложение</label>

</td>
 </tr>
</table>
$img_result
</table>

     <input type=hidden name=wysiwyg value='$wysiwyg'>
     <input type=hidden name=subaction value=upload>
     <input type=hidden name=area value='$area'>
    <input type=hidden name=action value='$action'>
    <input type=hidden name='images_number' id='images_number' value='1'>
 </form>

HTML;


if($action == "quick"){
echo"
<form name=properties>
<table style='margin-top:10px;' border=0 cellpading=0 cellspacing=0  width=100%>

     <td height=33>
     <b>Image Properties</b>
 <table border=0 cellpading=0 cellspacing=0 class=\"panel\" style='padding:5px'width=290px; >


      <tr>
       <td width=80>Alt. Text: </td>
       <td><input tabindex=1 type=text name=alternativeText style=\"width:150;\"></td>
      </tr>

      <tr>
       <td>Image Align</td>
       <td>
        <select name='imageAlign' style='width:150'>
          <option value=none>None</option>
          <option value=left>Left</option>
          <option value=right>Right</option>
        </select>
       </td>
      </tr>

      <tr>
       <td>Border</td>
       <td><input type=text value='0' name=imageBorder style=\"width:35\"> pixels</td>
      </tr>

     </table>
</table></form>";
}



echo"<tr><td><img height=1 style=\"height: 13px !important; height: 1px;\" border=0 src=\"skins/images/blank.gif\" width=1></tr><tr><td>
    <b>Загруженные картинки</b>
    </tr>

    <tr >

        <td height=1>
<FORM action='$PHP_SELF?mod=images' METHOD='POST'>
  <table width=100% height=100% cellspacing=0 cellpadding=0>";

        $img_dir = opendir($config_path_image_upload);



        $i = 0;

    while ($file = readdir($img_dir))
    {
         //Yes we'll store them in array for sorting
         $images_in_dir[] = $file;
    }
    natcasesort($images_in_dir);
    reset($images_in_dir);
    foreach ($images_in_dir as $file) {




        $img_name_arr = explode(".",$file);
            $img_type          = end($img_name_arr);


                if ( (in_array($img_type, $allowed_extensions) or in_array(strtolower($img_type), $allowed_extensions)) and $file != ".." and $file != "." and is_file($config_path_image_upload."/".$file))

            {

            $i++;

            $this_size =  filesize($config_path_image_upload."/".$file);

                $total_size += $this_size;

            $img_info = getimagesize($config_path_image_upload."/".$file);

            if( $i%2 != 0 ){ $bg = "bgcolor=#F7F6F4"; }

                    else{ $bg = ""; }



            if($action == "quick")

            {

                $my_area = str_replace("_", " ", $area);

                echo"

                <tr $bg><td height=16 width=1px> <a title='Preview this image' href=\"javascript:PopupPic('$file')\"><img style='border:0px;' src='skins/images/view_image.gif'></a>
                <td height=16 width=100%>

                <a title=\"Insert this image in the $my_area\" href=\"javascript:insertimage('$file')\">$file</a>



                <td height=16 align=right>

                            $img_info[0]x$img_info[1]&nbsp;&nbsp;



                            <td height=16 align=right>

                        &nbsp;". formatsize($this_size) ."

                            </tr>";

            }

            else

            {

                    echo"<tr $bg><td height=16>

                            &nbsp;

                            <td height=16 width=63% >

                            <a target=_blank href=\"". $config_path_image_upload ."/$file\">$file</a>



                <td height=16 align=right>

                            $img_info[0]x$img_info[1]



                            <td height=16 align=right>

                        &nbsp;". formatsize($this_size) ."

                        <td width=70 height=16 align=right>
                <input type=checkbox name=images[$file] value=\"$file\">

                            </tr>";

            }

            }

        }



    if($i > 0){

            echo"<tr ><td height=16>";


                if($action != "quick"){
                           echo" <td colspan=4 align=right>
                   <br><input type=submit value='Удалить выделенне картинки'>
                            </tr>";

                }

            echo"<tr heigh=1>
                <td  width=14>
                &nbsp;
                <td >
                <br /><b>Полный размер </b>
            <td>&nbsp;
            <td align=right>

                <br /><b>". formatsize($total_size) .'</b>

                </tr>';

        }

    echo'
   </table><input type=hidden name=action value=doimagedelete></form></table>';

    if($action != "quick"){ echofooter(); }

}

// ********************************************************************************

// Delete Image

// ********************************************************************************

elseif($action == "doimagedelete")

{
if(!isset($images)){         msg("info","Нет выделеных картинок","Вы должны выделить картинки для удаления", "$PHP_SELF?mod=images"); }
//        if(!file_exists($config_path_image_upload."/".$image) or !$image){ msg("error","Ошибка !!!","Невозможно удалить каритнку!", "$PHP_SELF?mod=images"); }
        foreach($images as $image){
                unlink($config_path_image_upload."/".$image) or print("Невозможно удалить каритнку <b>$file</b>");
        }
        msg("info","Картинка удалена","Картинка была успешно удалена.", "$PHP_SELF?mod=images");

}



?>