<?php

/*
+--------------------------------------------------------------------------
|   Invision Board v1.1
|   ========================================
|   > mod_resize_images function library
|   > Module written by Peter(Pit)
|        > Peter member at ibforen.de, ibresource.de, Pit member at ibresource.com
|        > email: Peter@ibforen.de
|
|   > mod_resize_images Module Version Number: 2.4 (2003-09-22)
|   > <c> 2003 by Peter
+--------------------------------------------------------------------------
*/


$mod_rsi = new mod_resize_images;

require(ROOT_PATH."sources/mods/resize_images/gif.php");

class mod_resize_images {

var $lang = "";
var $gd_support = FALSE;
var $gd_version = 0;
var $gif_read = FALSE;
var $gif_write = FALSE;
var $quality = 80;
var $always_jpeg = FALSE;
var $mem = array();

var $code = 'function gd_info() {
      $array = Array(
                      "GD Version" => "",
                      "FreeType Support" => 0,
                      "FreeType Support" => 0,
                      "FreeType Linkage" => "",
                      "T1Lib Support" => 0,
                      "GIF Read Support" => 0,
                     "GIF Create Support" => 0,
                    "JPG Support" => 0,
                      "PNG Support" => 0,
                      "WBMP Support" => 0,
                      "XBM Support" => 0
                     );
       $gif_support = 0;

      ob_start();
       eval("phpinfo();");
       $info = ob_get_contents();
       ob_end_clean();
     
      foreach(explode("\n", $info) as $line) {
          if(strpos($line, "GD Version")!==false)
              $array["GD Version"] = trim(str_replace("GD Version", "", strip_tags($line)));
           if(strpos($line, "FreeType Support")!==false)
              $array["FreeType Support"] = trim(str_replace("FreeType Support", "", strip_tags($line)));
          if(strpos($line, "FreeType Linkage")!==false)
              $array["FreeType Linkage"] = trim(str_replace("FreeType Linkage", "", strip_tags($line)));
          if(strpos($line, "T1Lib Support")!==false)
              $array["T1Lib Support"] = trim(str_replace("T1Lib Support", "", strip_tags($line)));
          if(strpos($line, "GIF Read Support")!==false)
              $array["GIF Read Support"] = trim(str_replace("GIF Read Support", "", strip_tags($line)));
          if(strpos($line, "GIF Create Support")!==false)
             $array["GIF Create Support"] = trim(str_replace("GIF Create Support", "", strip_tags($line)));
          if(strpos($line, "GIF Support")!==false)
              $gif_support = trim(str_replace("GIF Support", "", strip_tags($line)));
           if(strpos($line, "JPG Support")!==false)
               $array["JPG Support"] = trim(str_replace("JPG Support", "", strip_tags($line)));
           if(strpos($line, "PNG Support")!==false)
               $array["PNG Support"] = trim(str_replace("PNG Support", "", strip_tags($line)));
           if(strpos($line, "WBMP Support")!==false)
               $array["WBMP Support"] = trim(str_replace("WBMP Support", "", strip_tags($line)));
           if(strpos($line, "XBM Support")!==false)
               $array["XBM Support"] = trim(str_replace("XBM Support", "", strip_tags($line)));
       }
       
      if($gif_support==="enabled") {
           $array["GIF Read Support"]   = 1;
           $array["GIF Create Support"] = 1;
       }

       if($array["FreeType Support"]==="enabled"){
          $array["FreeType Support"] = 1;    }

      if($array["T1Lib Support"]==="enabled")
          $array["T1Lib Support"] = 1;    
     
      if($array["GIF Read Support"]==="enabled"){
         $array["GIF Read Support"] = 1;    }

      if($array["GIF Create Support"]==="enabled")
          $array["GIF Create Support"] = 1;    

      if($array["JPG Support"]==="enabled")
          $array["JPG Support"] = 1;
           
      if($array["PNG Support"]==="enabled")
          $array["PNG Support"] = 1;
           
      if($array["WBMP Support"]==="enabled")
          $array["WBMP Support"] = 1;
           
      if($array["XBM Support"]==="enabled")
          $array["XBM Support"] = 1;
       
       return $array;
   }';

function mod_resize_images() {
    ob_start();
    eval("phpinfo();");
    $info = ob_get_contents();
    ob_end_clean();
    if (preg_match("`GD Support`im",$info)) {
        if(!function_exists("gd_info")) eval($this->code);
        $gd = gd_info();
        if (preg_match("`[0-9].*[0-9]`", $gd['GD Version'], $matches)) {
            $this->gd_version = preg_replace("`(.+?\.+?)(.+?)(\.)(.*)`","\\1\\2\\4",$matches[0]);
            if ($this->gd_version >= 2) {
                $this->gd_support = TRUE;
                $this->gif_read = $gd['GIF Read Support']; 
                $this->gif_write = $gd['GIF Create Support']; 
            }
        }
    }
}

function set_quality($quality = "") {
    if ($quality != "") $this->quality = $quality; 
}

function set_jpeg($jpeg = "") {
    if ($jpeg != "") $this->always_jpeg = $jpeg; 
}

function Resize_this_image($replace_template, $imagesizes, $maxwidth = 0, $maxheight_sig = 1000000, $maxwidth_sig = 1000000) {
    global $ibforums;

    if ($maxwidth_sig != 1000000) {
        $scale = $maxwidth_sig/((float) $imagesizes[3]);
        $scale1 = $maxwidth/((float) $imagesizes[3]);
        if ($scale1 < $scale) $scale = $scale1;
    }
    else {
        $scale = $maxwidth/((float) $imagesizes[3]);
   }
    $scale_height = min($scale, $maxheight_sig/ ((float) $imagesizes[5])); 
    if ($scale < 1 OR ($scale > $scale_height AND ($scale < 1 OR $scale_height < 1)) ) {
        if ($scale > $scale_height) {
            if ($ibforums->vars['do_resize_images'] == "Limit_to_Iframe") {
                $newwidth = (string) round($imagesizes[3]*$scale);
            } else {
                $newwidth = (string) round($imagesizes[3]*$scale_height);
            }
            $newheight = $maxheight_sig;
        } else {
            $newheight = (string) round($imagesizes[5]*$scale);
            $newwidth = (string) round($imagesizes[3]*$scale);
        }
        $searchtext = $imagesizes[0];
        $replacetext = $imagesizes[0];
        if ($ibforums->vars['do_resize_images'] == "Limit_to_Iframe") {
            $newheight = (string) max($newheight, 60);
            $iframe_search = $imagesizes[1];
            preg_match("#(<a href.+\'(.+?)>)(.+?)(src.+\'(.+?)\')(.+?)alt(.+?)/aimg-->#U",$imagesizes[1], $src_url);
			$iframe_replace = "<table border = '0' cellspacing='0' cellpadding='0'><tr><td>";
            $iframe_replace .= "<iframe ".$src_url[4]." width='".$newwidth."' height='".$newheight."' name='Image in I-Frame'";
            $iframe_replace .= "align='left'  scrolling='yes' marginheight='0' marginwidth='0' frameborder='1' framespacing='0' border='1' >";
            $iframe_replace .= "<p>".$this->lang['resize_images_iframe_alt'];
            $iframe_replace .= $src_url[1].$this->lang['resize_images_iframe_info']."</a></p></iframe></td></tr><tr><td>";
            $iframe_replace .= $src_url[1]."<font size='1'><b>".$this->lang['resize_images_iframe_hint']."</b></font><br /></a></td></tr></table>";
            $replacetext = str_replace($iframe_search, $iframe_replace,$replacetext);
        } else {
            $replacetext = preg_replace("/width(' '|=)+\'[0-9]+\'/","width = '$newwidth'",$replacetext);
            $replacetext = preg_replace("/height(' '|=)+\'[0-9]+\'/","height = '$newheight'",$replacetext);
        }
        $replacetext = preg_replace( "#<!--Resize_Images_Hint_Text-->#"  , "<br /><b>".$this->lang['Resize_Images_Hint_Text']."</b><br />"  , $replacetext );
		$replacetext = preg_replace( "#--Resize_Images_Alt_Text--#"  , $this->lang['Resize_Images_Alt_Text']."' title = '".$this->lang['Resize_Images_Alt_Text'], $replacetext );
        $replacetext = preg_replace("#<!--aimg-->(.+?)<!--/aimg-->#","\\1" ,$replacetext);
        $replace_template = str_replace($searchtext,$replacetext, $replace_template);
        return $replace_template;
    } else {
		$searchtext = $imagesizes[0];
        $replacetext = preg_replace("#<!--aimg-->.+?(<img.+?class='attach' />).+?<!--/aimg-->#","\\1" ,$imagesizes[0]);
        $replace_template =  str_replace($searchtext,$replacetext, $replace_template);
        return str_replace( "#--Resize_Images_Alt_Text--#"  , $this->lang['Resize_Images_User_Posted']  , $replace_template );
    }
}

function get_resize_methods() {
	global $std, $ibforums, $DB;
    $this->lang = $std->load_words($this->lang, 'mod_resize_images_lang', $ibforums->lang_id);

    $sig = $ibforums->vars['do_resize_images_subject'] == "Do_Resize_Sig";
    $post = $ibforums->vars['do_resize_images_subject'] == "Do_Resize_Post";
	if ($ibforums->vars['do_resize_images'] == 'No_Resizing') {
		$ibforums->skin['template'] = preg_replace( "#--Resize_Images_Alt_Text--#"  , $this->lang['Resize_Images_User_Posted']  , $ibforums->skin['template'] );
        $ibforums->skin['template'] = preg_replace("#<!--aimg-->.+?(<img.+?class='attach' />).+?<!--/aimg-->#","\\1", $ibforums->skin['template']);
	} elseif ($ibforums->vars['do_resize_images'] == 'Limit_to_Window') {
		$ibforums->skin['template'] = preg_replace("/<\/body>/i",$this->limit_images_to_window()."</body>", $ibforums->skin['template']);
		$ibforums->skin['template'] = preg_replace( "#--Resize_Images_Alt_Text--#"  , $this->lang['Resize_Images_Alt_Text']."' title = '".$this->lang['Resize_Images_Alt_Text'], $ibforums->skin['template'] );
	} else {
		if (file_exists(ROOT_PATH."Skin/".$ibforums->skin_id."/mod_resize_images_skin.php")) {
            $DB->connect();
            if (class_exists("mod_resize_images_skin")) {
       	   		$mod_rsi_skin = new mod_resize_images_skin;
            } else {
       	   		$mod_rsi_skin = $std->load_template('mod_resize_images_skin');
            }
		} else {
			die("Could not fetch the template from skin directory. Template File 'mod_resize_images_skin.php', Skin ID {$ibforums->skin_rid}");			
		}
		$maxwidth = (float) preg_replace("/<!--.+?-->/ie","",$mod_rsi_skin->get_max_image_width());
		$maxheight_sig = (float) preg_replace("/<!--.+?-->/ie","",$mod_rsi_skin->get_max_image_height_signature());
		$maxwidth_sig = (float) preg_replace("/<!--.+?-->/ie","",$mod_rsi_skin->get_max_image_width_signature());
        
		preg_match_all("#<!-- THE POST.+?<!-- THE POST -->#s",$ibforums->skin['template'],$messages, PREG_SET_ORDER);

        // parse all images in message
		for ($j=0;$j<count($messages);$j++) {
            $replace_template = $messages[$j][0];
            // first in signatures
       		preg_match_all("#<!--Signature-->(.+?)<!--E-Signature-->#Us",$messages[$j][0],$imagesizes, PREG_SET_ORDER);
            if ($sig or (!$sig and !$post)){
           		preg_match_all("#(<!--aimg.+<img.+width(' '|=)+\'([0-9]+)\'.+height(' '|=)+\'([0-9]+)\'.+/aimg-->)#Us",$imagesizes[0][1], $signature_images, PREG_SET_ORDER);
           		for ($i=0;$i<count($signature_images);$i++) {
                    $imagesizes[0][0] = $this->Resize_this_image($imagesizes[0][0], $signature_images[$i], $maxwidth, $maxheight_sig, $maxwidth_sig);
                }
                $replace_template = preg_replace("#<!--Signature-->(.+?)<!--E-Signature-->#Us", $imagesizes[0][0],$replace_template);
            }

            // are there signature images left ?
            $replacetext = preg_replace("#<!--aimg-->.+?(<img.+?class='attach' />).+?<!--/aimg-->#","\\1" ,$imagesizes[0][0]);

            $replace_template = preg_replace("#<!--Signature-->(.+?)<!--E-Signature-->#Us",$replacetext, $replace_template);

            // resize the rest, this must be in posts
            if ($post or (!$sig and !$post)){
        		preg_match_all("#(<!--aimg.+<img.+width(' '|=)+\'([0-9]+)\'.+height(' '|=)+\'([0-9]+)\'.+/aimg-->)#Us",$messages[$j][0],$imagesizes, PREG_SET_ORDER);
           		for ($i=0;$i<count($imagesizes);$i++) {
                    $replace_template = $this->Resize_this_image($replace_template, $imagesizes[$i], $maxwidth);
                }
            }
    		$search_template = $messages[$j][0];
  			$ibforums->skin['template'] = str_replace($search_template,$replace_template, $ibforums->skin['template']);
		}	
        if ($ibforums->vars['do_resize_images_edit_mode']) {
            // Are we in edit mode ?
    		preg_match_all("#<!-- TopicSummaryTop -->.+?<!-- TopicSummaryBottom -->#s",$ibforums->skin['template'],$messages, PREG_SET_ORDER);
    
            // parse all images in TopicSummary
    		for ($j=0;$j<count($messages);$j++) {
                $replace_template = $messages[$j][0];
                if ($post or (!$sig and !$post)){
            		preg_match_all("#(<!--aimg.+<img.+width(' '|=)+\'([0-9]+)\'.+height(' '|=)+\'([0-9]+)\'.+/aimg-->)#Us",$messages[$j][0],$imagesizes, PREG_SET_ORDER);
               		for ($i=0;$i<count($imagesizes);$i++) {
                        $replace_template = $this->Resize_this_image($replace_template, $imagesizes[$i], $maxwidth);
                    }
                }
        		$search_template = $messages[$j][0];
      			$ibforums->skin['template'] = str_replace($search_template,$replace_template, $ibforums->skin['template']);
    		}	
        }

        if ($ibforums->vars['do_resize_images_preview']) {
            // Are we in preview mode ?
    		preg_match_all("#<!-- Post Preview-->.+?<!-- End Post Preview-->#s",$ibforums->skin['template'],$messages, PREG_SET_ORDER);
    
            // parse all images in Preview
    		for ($j=0;$j<count($messages);$j++) {
                $replace_template = $messages[$j][0];
                if ($post or (!$sig and !$post)){
            		preg_match_all("#(<!--aimg.+<img.+width(' '|=)+\'([0-9]+)\'.+height(' '|=)+\'([0-9]+)\'.+/aimg-->)#Us",$messages[$j][0],$imagesizes, PREG_SET_ORDER);
               		for ($i=0;$i<count($imagesizes);$i++) {
                        $replace_template = $this->Resize_this_image($replace_template, $imagesizes[$i], $maxwidth);
                    }
                }
        		$search_template = $messages[$j][0];
      			$ibforums->skin['template'] = str_replace($search_template,$replace_template, $ibforums->skin['template']);
    		}	
        }

		$ibforums->skin['template'] = preg_replace( "#--Resize_Images_Alt_Text--#"  , $this->lang['Resize_Images_User_Posted']  , $ibforums->skin['template'] );
	    if ($ibforums->vars['do_resize_images'] == 'Limit_to_Maximum_with_JS') {
			$ibforums->skin['template'] = preg_replace("/<\/body>/i",$this->limit_images_to_maximum($maxwidth)."</body>", $ibforums->skin['template']);
		}
	}
}


function ad_settings() {
	global $INFO, $SKIN, $ADMIN, $IN, $std;
    $lang = $std->load_words($lang, 'mod_resize_images_lang', $INFO['default_language']==""?'tw':$INFO['default_language']);
	$lang['resize_images_method_info'] = str_replace("{board_url}",$INFO['board_url'],$lang['resize_images_method_info']); 
	$lang['resize_images_method_info'] = str_replace("{php_ext}",$INFO['php_ext'],$lang['resize_images_method_info']); 
	$lang['resize_images_method_info'] = str_replace("{AD_SESS}",$IN['AD_SESS'],$lang['resize_images_method_info']); 

	$ADMIN->html .= $SKIN->add_td_basic( '<b>ÌÖÂÛÇøËõÍ¼Éè¶¨</b>', 'left', 'catrow2' );

	$ADMIN->html .= $SKIN->add_td_row( array( $lang['resize_images_method_info'],
									  $SKIN->form_dropdown( 'do_resize_images', 
									  						array( 
									  							 0 => array('No_Resizing', $lang['resize_images_method_1']  ), 
																 1 => array('Limit_to_Window', $lang['resize_images_method_2'] ), 
																 2 => array('Limit_to_Maximum_with_JS', $lang['resize_images_method_3'] ), 
																 3 => array('Limit_to_Maximum', $lang['resize_images_method_4'] ), 
																 4 => array('Limit_to_Iframe', $lang['resize_images_method_5'] ), 
									  						 	  ),
																 $INFO['do_resize_images'] ),
							 )      );
	$ADMIN->html .= $SKIN->add_td_row( array( $lang['resize_images_subject_info'],
									  $SKIN->form_dropdown( 'do_resize_images_subject', 
									  						array( 
									  							 0 => array('Do_Resize_All', $lang['resize_images_subject_1']  ), 
									  							 1 => array('Do_Resize_Post', $lang['resize_images_subject_2']  ), 
									  							 2 => array('Do_Resize_Sig', $lang['resize_images_subject_3']  ), 
									  						 	  ),
																 $INFO['do_resize_images_subject'] ),
							 )      );

	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Resize_Images_Edit_Mode'],
                                     $SKIN->form_yes_no( "do_resize_images_edit_mode", $INFO['do_resize_images_edit_mode']  )
                                     ) );
	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Resize_Images_Preview'],
                                     $SKIN->form_yes_no( "do_resize_images_preview", $INFO['do_resize_images_preview']  )
                                     ) );
	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Resize_Images_Manage_Old_Posts_info'],
                                     $SKIN->form_yes_no( "do_resize_images_old_posts", 0  )
                                     ) );
	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Resize_Images_Manage_Old_Posts_Limit_info'],
                                     $SKIN->form_simple_input( "do_resize_images_old_posts_limit", $INFO['do_resize_images_old_posts_limit'], 5 )
                                     ) );

    if ($this->gd_support == 1) {
        $support = $this->gif_read?$lang['Scale_Images_Gif_Read']:"";
        $support .= $this->gif_write?$lang['Scale_Images_Gif_Write']:"";

    	$ADMIN->html .= $SKIN->add_td_basic( $lang['Scale_Images_Menu_Desc'].$support,
                                             'left', '' );
    	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Images'],
                                         $SKIN->form_yes_no( "do_scale_images_edit", $INFO['do_scale_images_edit']  )
                                         ) );
    	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Jpeg_Quality'],
                                         $SKIN->form_simple_input( "do_scale_images_quality", $INFO['do_scale_images_quality'], 3  )
                                         ) );
    	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Images_Always_Jpeg'],
                                         $SKIN->form_yes_no( "do_scale_images_jpeg", $INFO['do_scale_images_jpeg'] )
                                         ) );
        if (!$this->gif_read) {
        	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Images_Command'],
                                             $SKIN->form_input( "do_scale_images_command", $INFO['do_scale_images_command']  )
                                             ) );
        }
    	$ADMIN->html .= $SKIN->add_td_basic( $lang['Scale_Images_Tool'],'left', '' );
    	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Images_Uploads'],
                                         $SKIN->form_yes_no( "do_scale_images_uploads", 0 )
                                         ) );
    	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Images_Uploads_Width'],
                                         $SKIN->form_simple_input("do_scale_images_uploads_width", $INFO['do_scale_images_uploads_width'], 5 )
                                         ) );
    	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Images_Uploads_Height'],
                                         $SKIN->form_simple_input("do_scale_images_uploads_height", $INFO['do_scale_images_uploads_height'], 5 )
                                         ) );
    	$ADMIN->html .= $SKIN->add_td_row( array( $lang['Scale_Images_Thumbs_Uploads'],
                                         $SKIN->form_yes_no( "do_scale_images_thumbs_uploads", 0 )
                                         ) );
    } else {
    	$ADMIN->html .= $SKIN->add_td_basic( $lang['Scale_Images_Menu_Desc_No'], 'left', '' );
    }
}

function update_db($filename, $new_filename, $path){
    global $DB;
    
    if ($new_filename == $filename) return;
    @unlink ($path.$filename );
    
    $query = "UPDATE ibf_posts SET attach_id = '$new_filename', attach_type='image/pjpeg', attach_file=REPLACE(attach_file, '.gif', '.jpg')  WHERE attach_id = '$filename' ";
    $id1 = $DB->query($query);

    $query = "UPDATE ibf_posts SET post=REPLACE(post, '$filename', '$new_filename') WHERE (post LIKE '%<a%".$filename."%>%') OR (post LIKE '%<img%".$filename."%>%')";
    $id1 = $DB->query($query);
    return ($id1 + $id2);
}

function scale_upload_dir($create_thumbs = FALSE) {
    global $ADMIN, $IN, $INFO, $SKIN, $std;

    $lang = $std->load_words($lang, 'mod_resize_images_lang', $INFO['default_language']==""?'tw':$INFO['default_language']);

    if (!$create_thumbs) {
        if (!$INFO['do_scale_images_uploads_width'] OR $INFO['do_scale_images_uploads_width'] <= 0 OR
            !$INFO['do_scale_images_uploads_height'] OR  $INFO['do_scale_images_uploads_height'] <= 0) 
            $ADMIN->error($lang['Scale_Images_Uploads_Error']);
    } 
    else {
        if ( !$INFO['siu_width'] OR !$INFO['siu_height'] ) 
            $ADMIN->error($lang['Scale_Images_Thumbs_Uploads_Error']);
    }
    $current_version = (int)str_replace('.', '', phpversion());
    if ($current_version  < 420) {
        $mod_scale_images_timeout = ini_get ('max_execution_time');
    } else {
        $a = ini_get_all();
        $mod_scale_images_timeout = $a['max_execution_time']['global_value'];
        unset ($a);
    }
    $mod_scale_images_start_time = time();

    $files = array();
    $dir = $INFO['base_dir']."/uploads";
    $done = 0;
    $done_posts = 0;
    $num = 0;
    if ( is_dir($dir) ) {
        $handle = opendir($dir);
        while (($filename = readdir($handle)) !== false AND  (time() - $mod_scale_images_start_time  + 5) < $mod_scale_images_timeout) {
            if (($filename != ".") && ($filename != "..") && !is_dir($dir."/".$filename)) {
                $file_info = pathinfo($filename);
                $ext = explode("|",strtolower($INFO['img_ext']));
                if (!(array_search(strtolower($file_info['extension']), $ext) === FALSE)) {
                    $num++;
                    $size = @getimagesize(ROOT_PATH."uploads/". $filename,$info);
                    if ($create_thumbs) {
                        if (!preg_match("`.*_thumb\..*`",$filename)) {
                            $dest_file = ROOT_PATH."uploads/".preg_replace("`(.*)\.(.*)`", "\\1_thumb.\\2", $filename);
                            if (!file_exists($dest_file) AND copy(ROOT_PATH."uploads/".$filename, $dest_file)) {
                                $scale = $INFO['siu_width']/((float) $size[0]);
                                $scale1 = $INFO['siu_height']/((float) $size[1]);
                                if ($scale1 < $scale) $scale = $scale1;
                                if ($scale < 1 AND $new_filename = $this->scale_image($dest_file, $scale)) {
                                    $done++;
                                    if (preg_match("`.gif$`ie", $filename) AND preg_match("`.jpg$`ie", $new_filename)) {
                                        $new_filename = $this->scale_image(ROOT_PATH."uploads/". $filename, 1, TRUE);
                                        $done_posts += $this->update_db($filename, str_replace(ROOT_PATH."uploads/", "", $new_filename),ROOT_PATH."uploads/");
                                    }
                                } 
                                else {
                                    @unlink($dest_file);
                                }
                            }
                        }
                    }
                    else {
                        if ($size[0] > $INFO['do_scale_images_uploads_width'] OR
                            $size[1] > $INFO['do_scale_images_uploads_height']) {
                            $scale = min($INFO['do_scale_images_uploads_width']/((float) $size[0]), 
                                         $INFO['do_scale_images_uploads_height']/((float) $size[1]));
                            if ($scale < 1 AND $new_filename = $this->scale_image(ROOT_PATH."uploads/". $filename, $scale)) {
                                $done++;
                                $done_posts += $this->update_db($filename, str_replace(ROOT_PATH."uploads/", "", $new_filename),ROOT_PATH."uploads/");
                            }
                        }
                    }
                }
            }
        }
        closedir($handle);
    }

	$lang['Scale_Images_Total_Results'] = str_replace("{num}",$num,$lang['Scale_Images_Total_Results']); 
	$lang['Scale_Images_Done_Results'] = str_replace("{done}",$done,$lang['Scale_Images_Done_Results']); 
	$lang['Scale_Images_Done_Posts_Results'] = str_replace("{done_posts}",$done_posts,$lang['Scale_Images_Done_Posts_Results']); 
    $html = $SKIN->print_top($lang['Scale_Images_Title'], $lang['Scale_Images_Desc']);
	$html .= $SKIN->start_table($lang['Scale_Images_Results']);
    $html .= $SKIN->add_td_basic( $lang['Scale_Images_Total_Results'], 'left', 'catrow2' );
    $html .= $SKIN->add_td_basic( $lang['Scale_Images_Done_Results'], 'left', 'catrow2' );
    $html .= $SKIN->add_td_basic( $lang['Scale_Images_Done_Posts_Results'], 'left', 'catrow2' );
	$base_url = $INFO['board_url']."/admin.".$INFO['php_ext']."?adsess=".$IN['AD_SESS']."&act=op";
    if ($create_thumbs)
        $html .= $SKIN->add_td_basic( "<a href='".$base_url."&code=dopost&do_scale_images_thumbs_uploads=1'>".$lang['Scale_Images_Doit_again']."</a>", 'left', 'catrow2' ); 
    else
        $html .= $SKIN->add_td_basic( "<a href='".$base_url."&code=dopost&do_scale_images_uploads=1'>".$lang['Scale_Images_Doit_again']."</a>", 'left', 'catrow2' ); 
    $html .= $SKIN->add_td_basic( "<a href='".$base_url."&code=post'>".$lang['Scale_Images_Back_To_Posts']."</a>", 'left', 'catrow2' ); 
	$html .= $SKIN->end_table();
    $html .= $SKIN->print_foot();
    print $html;
}

function scale_image($src_file = "", $scale = 1, $override = FALSE) {
    global $ibforums;
    if ((!$override AND abs($scale - 1) < 0.001) OR $src_file == "") return;
    $size = @getimagesize($src_file,$info);
    $src_parts = explode(".", $src_file);
    $pos = count($src_parts);
    if ($pos > 1) $pos--;
    switch ($size[2]) {
        case '1' :
                $src_parts[$pos] = $this->gif_write?"gif":"jpg";
                break;
        case '2' :
                $src_parts[$pos] = "jpg";
                break;
        case '3' :
                $src_parts[$pos] = "png";
                break;
        default : 
                $src_parts[$pos] = "jpg";
                break;
    }
    if ($this->always_jpeg)$src_parts[$pos] = "jpg";
    $dest_file = implode(".", $src_parts);
    $src_parts[$pos-1] .= "_temp";
    $src_parts[$pos] = "jpg";
    $temp_file = implode(".", $src_parts);

    switch ($size[2]) {
        case '1' :
                if ($this->gif_read) {
                    $src = ImageCreateFromGif ($src_file);
                    if ($this->always_jpeg) @unlink($src_file);
                } else {
                    if ($command = $ibforums->vars['do_scale_images_command']) {
                        $command = str_replace("\$source", $src_file, strtolower($command));
                        $command = str_replace("\$dest", $dest_file, strtolower($command));
                        @unlink($dest_file);
                        if (getenv("OS") == "Windows_NT") $command = preg_replace("#([^ ])/([^ ])#i", "$1"."chr(92)"."$2", $command);
                        $command = str_replace("chr(92)", "\\", $command);
                        $mstrng = exec($command);
                        $mstrng = ereg_replace( "Content-type: text/html", "", $mstrng );
                        if (file_exists($dest_file)) {
                            $size = @getimagesize($dest_file,$info);
                            $src = ImageCreateFromJpeg ($dest_file);
                        } else {
                            return;
                        }
                    } else {
                        if ($gif = gif_loadFile($src_file)) {
                    		if (gif_outputAsPng($gif, $temp_file)) {
                                $src = ImageCreateFromPng ($temp_file);
                                @unlink ($temp_file);
                            } else {
                                return;
                            }
                        } else {
                            return;
                        }
                    }
                }
                break;
        case '2' :
                $src = ImageCreateFromJpeg ($src_file);
                break;
        case '3' :
                $src = ImageCreateFromPng ($src_file);
                break;
        default : 
                return;
                break;
    }
    if ($size[0] > 0) {
        $dest = imagecreatetruecolor(round($size[0]*$scale),round($size[1]*$scale));
        imagecopyresampled ($dest,$src,0,0,0,0,round($size[0]*$scale),round($size[1]*$scale),$size[0],$size[1]);
        imagedestroy($src);
        imageinterlace($dest);
        if ($this->always_jpeg) $size[2] = '2';
        switch ($size[2]) {
            case '1' :
                    $gd = gd_info();
                    if ($this->gif_write) {
                        imagegif($dest,$dest_file);
                    } else {
                        imagejpeg($dest,$dest_file, $this->quality);
                    }
                    break;
            case '2' :
                    imagejpeg($dest,$dest_file, $this->quality);
                    break;
            case '3' :
                    imagepng($dest,$dest_file);
                    break;
            default : 
                    imagejpeg($dest,$dest_file, $this->quality);
                    break;
        }
        imagedestroy($dest);
    }
    return $dest_file;
}

function do_manage_old_posts() {
	global $DB, $SKIN, $std, $INFO, $IN, $HTTP_POST_VARS;

    $current_version = (int)str_replace('.', '', phpversion());
    if ($current_version  < 420) {
        $mod_resize_images_timeout = ini_get ('max_execution_time');
    } else {
        $a = ini_get_all();
        $mod_resize_images_timeout = $a['max_execution_time']['global_value'];
        unset ($a);
    }
    $mod_resize_images_start_time = time();
    $limit = $INFO['do_resize_images_old_posts_limit']?$INFO['do_resize_images_old_posts_limit']:"-1";
    $DB->query('SELECT pid,post FROM ibf_posts WHERE NOT (post LIKE "%<!--aimg-->%") AND NOT (post LIKE "%<!-- ACP_stats%") AND (post LIKE "%<img%src%") LIMIT 0,'
               .$limit);
    $num = $DB->get_num_rows();
    $done = 0;
    if ($num > 0) {
        $search = "#<img src=[\'\"](.+?)[\'\"](.+?)alt=[\'\"](.+?)[\'\"](.*?)>#"; 
        while ($p = $DB->fetch_row() AND  (time() - $mod_resize_images_start_time  + 2) < $mod_resize_images_timeout) {
            preg_match_all ($search, $p['post'], $images, PREG_SET_ORDER); 
            $do_update = FALSE;
            $post['post'] = $p['post'];
            for ($i = 0; $i < count($images); $i++) {
                $url = $images[$i][1];
                $size = @getimagesize($url, $info);
                if ($size[0] > 0) {
                    $replace = "<!--aimg--><a href='$url' target='_blank'>".
                                "<img src='$url' {$images[$i][2]} alt='--Resize_Images_Alt_Text--' width='$size[0]' height='$size[1]'{$images[$i][4]}></a>".
                                "<!--Resize_Images_Hint_Text--><!--/aimg-->";
                    $post['post'] = str_replace($images[$i][0], $replace, $post['post']);
                    $do_update = TRUE;
                }
            }
            if ( $do_update ) {
                $db_string = $DB->compile_db_update_string( $post );
                $id = $DB->query_id;
                $DB->query("UPDATE ibf_posts SET $db_string WHERE pid='".$p['pid']."'");
                $DB->query_id = $id;
                $done++;
            }
            unset ($p);
            unset ($post);
            unset ($images);
        }
    }
    $lang = $std->load_words($lang, 'mod_resize_images_lang', $INFO['default_language']==""?'tw':$INFO['default_language']);
	$lang['Resize_Images_Total_Results'] = str_replace("{num}",$num,$lang['Resize_Images_Total_Results']); 
	$lang['Resize_Images_Done_Results'] = str_replace("{done}",$done,$lang['Resize_Images_Done_Results']); 
    $html = $SKIN->print_top($lang['Resize_Images_Title'], $lang['Resize_Images_Manage_Old_Posts_Desc']);
	$html .= $SKIN->start_table($lang['Resize_Images_Results']);
    $html .= $SKIN->add_td_basic( $lang['Resize_Images_Total_Results'], 'left', 'catrow2' );
    $html .= $SKIN->add_td_basic( $lang['Resize_Images_Done_Results'], 'left', 'catrow2' );
	$base_url = $INFO['board_url']."/admin.".$INFO['php_ext']."?adsess=".$IN['AD_SESS']."&act=op&code=dopost";
    if ($done < $num) {
        $html .= $SKIN->add_td_basic( "<a href='".$base_url."&do_resize_images_old_posts=1'>".$lang['Resize_Images_Doit_again']."</a>", 'left', 'catrow2' ); 
        $html .= $SKIN->add_td_basic( "<a href='".$base_url."&code=post'>".$lang['Scale_Images_Back_To_Posts']."</a>", 'left', 'catrow2' ); 
    } else {
        $IN['do_resize_images_old_posts'] = '0';
        $HTTP_POST_VARS['do_resize_images_old_posts'] = '0';
    }
	$html .= $SKIN->end_table();
    $html .= $SKIN->print_foot();
    print $html;
}

function save_config() {
    global $ADMIN, $HTTP_POST_VARS, $DB, $INFO, $IN;
    if (isset($HTTP_POST_VARS['do_resize_images'])) {
        if ($HTTP_POST_VARS['do_resize_images_old_posts']) {
            $HTTP_POST_VARS['do_scale_images_uploads'] = '0';        
        }
        if ($HTTP_POST_VARS['do_scale_images_uploads']) {
            $HTTP_POST_VARS['do_resize_images_old_posts'] = '0';        
        }
        $master['do_resize_images'] = $HTTP_POST_VARS['do_resize_images'];
        $master['do_resize_images_subject'] = $HTTP_POST_VARS['do_resize_images_subject'];
//        $master['do_resize_images_old_posts'] = $HTTP_POST_VARS['do_resize_images_old_posts'];
        $master['do_resize_images_old_posts_limit'] = $HTTP_POST_VARS['do_resize_images_old_posts_limit'];
        $master['do_resize_images_edit_mode'] = $HTTP_POST_VARS['do_resize_images_edit_mode'];
        $master['do_resize_images_edit_mode'] = $HTTP_POST_VARS['do_resize_images_edit_mode'];
        $master['do_scale_images_quality'] = $HTTP_POST_VARS['do_scale_images_quality'];
        $master['do_scale_images_jpeg'] = $HTTP_POST_VARS['do_scale_images_jpeg'];
        $master['do_resize_images_preview'] = $HTTP_POST_VARS['do_resize_images_preview'];
        $master['do_scale_images_edit'] = $HTTP_POST_VARS['do_scale_images_edit'];
        $master['do_scale_images_uploads_width'] = $HTTP_POST_VARS['do_scale_images_uploads_width'];
        $master['do_scale_images_uploads_height'] = $HTTP_POST_VARS['do_scale_images_uploads_height'];
        $master['do_scale_images_command'] = $HTTP_POST_VARS['do_scale_images_command'];
        
        $ADMIN->rebuild_config($master);
        $ADMIN->save_log("Board Settings <b>Resize Images</b> Updated, Back Up Written");
        require ROOT_PATH."conf_global.php";
    }    
    if ($HTTP_POST_VARS['do_resize_images_old_posts'] or $IN['do_resize_images_old_posts']) {
         $this->do_manage_old_posts($this->base_url."&act=dopost");
    }
    if ( !$INFO['siu_thumb'] AND ($HTTP_POST_VARS['do_scale_images_uploads'] OR $IN['do_scale_images_uploads'])) {
         $this->scale_upload_dir(FALSE);
    }
    if ( $INFO['siu_thumb'] AND ($HTTP_POST_VARS['do_scale_images_thumbs_uploads'] OR $IN['do_scale_images_thumbs_uploads'])) {
         $this->scale_upload_dir(TRUE);
    }
}

function limit_images_to_window() {
return <<<EOF
<!-- mod_resize_images begin -->
<script language='javascript'>
<!--
function IsMS () {
  var temp = navigator.appName;
  return temp.search(/microsoft/i);
}

var standard_width = 0.8;
var temp_image = new Image();
var Post_Cell = document.getElementById("Post_Cell");
if (Post_Cell != null) { 
    if (window.innerWidth) {
        var max_width = parseFloat(Post_Cell.width)*window.innerWidth/100;
    } else {
        var max_width = parseFloat(Post_Cell.width)*document.body.offsetWidth/100;
    }
} else {
    if (window.innerWidth) {
        var max_width = Math.round(standard_width*window.innerWidth);
    } else {
        var max_width = Math.round(standard_width*document.body.offsetWidth);
    }
}
for (var i=0; i<document.images.length; i++) {
  temp_image.src = document.images[i].src;
  scale = document.images[i].width/max_width;
  if (scale == 0)  { scale = temp_image.width/max_width; }
  if (scale > 1) {
    if (IsMS() == -1) {
      document.images[i].height = Math.round(document.images[i].height/scale);
      document.images[i].width = Math.round(document.images[i].width/scale);
    } else {
      document.images[i].height = Math.round(temp_image.height/scale);
      document.images[i].width = Math.round(temp_image.width/scale);
    }
  }
}

//-->
</script>
<!-- mod_resize_images end -->

EOF;
}

function limit_images_to_maximum($max_width) {
return <<<EOF
<!-- mod_resize_images begin -->
<script language='javascript'>
<!--
function IsMS () {
  var temp = navigator.appName;
  return temp.search(/microsoft/i);
}

var temp_image = new Image();
scale = 1024/document.body.offsetWidth;
for (var i = 0; i < document.images.length; i++) {
  temp_image.src = document.images[i].src;
  scale = document.images[i].width/$max_width;
  if (scale == 0)  { scale = temp_image.width/$max_width; }
  if (scale > 1) {
    if (IsMS() == -1 || temp_image.width != document.images[i].width) {
      document.images[i].height = Math.round(document.images[i].height/scale);
      document.images[i].width = Math.round(document.images[i].width/scale);
    } else {
      document.images[i].height = Math.round(temp_image.height/scale);
      document.images[i].width = Math.round(temp_image.width/scale);
    }
  }
}

//-->
</script>
<!-- mod_resize_images end -->

EOF;
}

}
?>
