============================================================================================================================
Modification Title: Multi-Attachments and Image Resize Control

Version1.1

Author: John Briggs, Scan

Description:
This modification will provide a multiple attachments feature with more advanced admin controls per forum and settings.

Copyright:  2010 John Briggs. All Rights Reserved.

Compatability: XMB 1.9.5 SP1

Updated by: WormHole

Install Note: Before adding this modification to your forum, you should back up all files related to this modification.

License Note: This modification is released under the GPL License v3. A copy is provided with this software package.

Author Note:
You downloaded this modification from XMBGarage.com, the #1 source for XMB related downloads.
Please visit http://www.xmbgarage.com/ for support.
============================================================================================================================
=======
Step 1:
=======
===================================
Go To Administration Panel --> Insert raw SQL
===================================
==========================
Paste Code And Submit Changes:
==========================

ALTER TABLE `$table_attachments` ADD `fileheight` varchar(5) NOT NULL default '';
ALTER TABLE `$table_attachments` ADD `filewidth` varchar(5) NOT NULL default '';
ALTER TABLE `$table_settings` ADD `max_attheight` smallint(5) NOT NULL default '350';
ALTER TABLE `$table_settings` ADD `max_attwidth` smallint(5) NOT NULL default '350';
ALTER TABLE `$table_settings` add `attach_num_default` tinyint(2) NOT NULL default '3';
ALTER TABLE `$table_forums` add `attachnum` tinyint(2) NOT NULL default '3';
UPDATE `$table_attachments` SET fileheight='350' WHERE fileheight='';
UPDATE `$table_attachments` SET filewidth='350' WHERE filewidth='';

============================================================================================================================
=======
Step 2:
=======
==============
Edit File: cp.php
==============
==========
Find Code:
==========

        $avchecked[0] = $avchecked[1] = $avchecked[2] = false;
        if (!empty($avatarlist)) {
            $avchecked[1] = true;
        } elseif (!empty($avataroff)) {
            $avchecked[2] = true;
        } else {
            $avchecked[0] = true;
        }

===============
Add Code Below:
===============

        // Multi-Attachments and Image Resize Control Mod Begin
        if ($SETTINGS['attach_num_default'] <= 0) {
            $attach_num = 0;
        } else {
            $attach_num = $SETTINGS['attach_num_default'];
        }
        // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

        printsetting2($lang['textmpp'], "memberperpagenew", $SETTINGS['memberperpage'], 3);

===============
Add Code Below:
===============

        // Multi-Attachments and Image Resize Control Mod Begin
        printsetting2($lang['attach_numdefault'], 'attachnumnew', $attach_num, 2);
        // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

        $lang['spell_checker'] .= $spell_off_reason;

===============
Add Code Below:
===============

        // Multi-Attachments and Image Resize Mod Begin
        $SETTINGS['max_attheight'] = (int) $SETTINGS['max_attheight'];
        $SETTINGS['max_attwidth'] = (int) $SETTINGS['max_attwidth'];
        // Multi-Attachments and Image Resize Mod End

==========
Find Code:
==========

        printsetting1($lang['attachimginpost'], "attachimgpostnew", $attachimgposton, $attachimgpostoff);

===============
Add Code Below:
===============

        // Multi-Attachments and Image Resize Mod Begin
        printsetting2($lang['max_attheight'], 'max_attheightnew', $SETTINGS['max_attheight'], 3);
        printsetting2($lang['max_attwidth'], 'max_attwidthnew', $SETTINGS['max_attwidth'], 3);
        // Multi-Attachments and Image Resize Mod End

==========
Find Code:
==========

        $max_avatar_size_w_new = (int) $max_avatar_size_w_new;
        $max_avatar_size_h_new = (int) $max_avatar_size_h_new;

===============
Add Code Below:
===============

        // Multi-Attachments and Image Resize Mod Begin
        $max_attheightnew = (int) $max_attheightnew;
        $max_attwidthnew = (int) $max_attwidthnew;
        // Multi-Attachments and Image Resize Mod End

==========
Find Code:
==========

        $db->query("UPDATE $table_settings SET langfile='$langfilenew',

==============================
Find Code At End Of Above Statement:
==============================

");

================
Replace Code With:
================

, attach_num_default='$attachnumnew', max_attheight='$max_attheightnew', max_attwidth='$max_attheightnew'");

==========
Find Code:
==========

        <tr class="tablerow">
        <td bgcolor="<?php echo $altbg1?>"><?php echo $lang['texttheme']?></td>
        <td bgcolor="<?php echo $altbg2?>"><?php echo $themelist?></td>
        </tr>

===============
Add Code Above:
===============

        <!-- Multi-Attachments and Image Resize Control Mod Begin -->
        <tr class="tablerow">
        <td bgcolor="<?php echo $altbg1?>"><?php echo $lang['attach_multiattach']?></td>
        <td bgcolor="<?php echo $altbg2?>"><input type="text" name="attachnumnew" size="2" value="<?php echo ($forum['attachnum'] > 0 ? $forum['attachnum'] : $SETTINGS['attach_num_default'])?>" /></td>
        </tr>
        <!-- Multi-Attachments and Image Resize Control Mod End -->

==========
Find Code:
==========

            if ($newfname != $lang['textnewforum']) {
                $newfname = addslashes($newfname);
                $db->query("INSERT INTO $table_forums ( type, fid, name, status, lastpost, moderator, displayorder, private, description, allowhtml, allowsmilies, allowbbcode, userlist, theme, posts, threads, fup, postperm, allowimgcode, attachstatus, pollstatus, password, guestposting ) VALUES ('forum', '', '$newfname', '$newfstatus', '', '', '$newforder', '1', '', 'no', 'yes', 'yes', '', '', '0', '0', '$newffup', '1|1', 'yes', 'on', 'on', '', 'off')");
            }

===============================
Find Code IN-LINE in Above Statement:
===============================

) VALUES ('forum',

================
Replace Code With:
================

, attachnum ) VALUES ('forum',

==============================
Find Code At End Of Above Statement:
==============================

)");

================
Replace Code With:
================

, '$SETTINGS[attach_num_default]')");

==========
Find Code:
==========

            if ($newgname != $lang['textnewgroup']) {
                $newgname = addslashes($newgname);
                $db->query("INSERT INTO $table_forums ( type, fid, name, status, lastpost, moderator, displayorder, private, description, allowhtml, allowsmilies, allowbbcode, userlist, theme, posts, threads, fup, postperm, allowimgcode, attachstatus, pollstatus, password, guestposting ) VALUES ('group', '', '$newgname', '$newgstatus', '', '', '$newgorder', '', '', '', '', '', '', '', '0', '0', '', '', '', '', '', '', 'off')");
            }

===============================
Find Code IN-LINE in Above Statement:
===============================

) VALUES ('group',

================
Replace Code With:
================

, attachnum ) VALUES ('group',

==============================
Find Code At End Of Above Statement:
==============================

)");

================
Replace Code With:
================

, '$SETTINGS[attach_num_default]')");

==========
Find Code:
==========

            if ($newsubname != $lang['textnewsubf']) {
                $newsubname = addslashes($newsubname);
                $db->query("INSERT INTO $table_forums ( type, fid, name, status, lastpost, moderator, displayorder, private, description, allowhtml, allowsmilies, allowbbcode, userlist, theme, posts, threads, fup, postperm, allowimgcode, attachstatus, pollstatus, password, guestposting ) VALUES ('sub', '', '$newsubname', '$newsubstatus', '', '', '$newsuborder', '1', '', 'no', 'yes', 'yes', '', '', '0', '0', '$newsubfup', '1|1', 'yes', 'on', 'on', '', 'off')");
            }

===============================
Find Code IN-LINE in Above Statement:
===============================

) VALUES ('sub',

================
Replace Code With:
================

, attachnum ) VALUES ('sub',

==============================
Find Code At End Of Above Statement:
==============================

)");

================
Replace Code With:
================

, '$SETTINGS[attach_num_default]')");

==========
Find Code:
==========

            $descnew = addslashes($descnew);

===============
Add Code Below:
===============

            // Multi-Attachments and Image Resize Control Mod Begin
            $attachnumnew = (int) ($attachnumnew);
            // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

$db->query("UPDATE $table_forums SET name='$namenew', description='$descnew',

==============================
Find Code At End Of Above Statement:
==============================

 WHERE fid='$fdetails'");

================
Replace Code With:
================

, attachnum='$attachnumnew' WHERE fid='$fdetails'");

============================================================================================================================
=======
Step 3:
=======
================
Open File: cp2.php
================
==========
Find Code:
==========

            <td bgcolor="<?php echo $altbg2?>" class="tablerow" valign="top"><input type="text" name="filename<?php echo $attachment['aid']?>" value="<?php echo $attachment['filename']?>"><br /><span class="smalltxt"><a href="viewthread.php?action=attachment&amp;tid=<?php echo $attachment['tid']?>&amp;pid=<?php echo $attachment['pid']?>" target="_blank"><?php echo $lang['textdownload']?></a></td>

================
Replace Code With:
================

            <td bgcolor="<?php echo $altbg2?>" class="tablerow" valign="top"><input type="text" name="filename<?php echo $attachment['aid']?>" value="<?php echo $attachment['filename']?>" /><br /><span class="smalltxt"><a href="viewthread.php?action=attachment&amp;tid=<?php echo $attachment['tid']?>&amp;pid=<?php echo $attachment['pid']?>&amp;aid=<?php echo $attachment['aid']?>" target="_blank"><?php echo $lang['textdownload']?></a></td>

============================================================================================================================
=======
Step 3:
=======
================
Edit File: header.php
================
==========
Find Code:
==========

$filesize = 0;
$filename = '';
$filetype = '';

================
Replace Code With:
================

$attachscript = '';
$filename = '';
$filetype = '';
$fileheight = '';
$filewidth = '';
$filesize = 0;

============================================================================================================================
=======
Step 4:
=======
==================
Edit File: functions.php
==================
==========
Find Code:
==========

function get_attached_file($file, $attachstatus, $max_size=1000000) {
    global $lang, $filename, $filetype, $filesize;

    $filename = $filetype = '';
    $filesize = 0;

    if ($file['name'] != 'none' && !empty($file['name']) && $attachstatus != 'off' && is_uploaded_file($file['tmp_name'])) {
        if (!isValidFilename($file['name'])) {
            error($lang['invalidFilename'], false, '', '', false, false, false, false);
            return false;
        }

        $filesize = intval(filesize($file['tmp_name'])); // fix bad filesizes
        if ($file['size'] > $max_size) {
            error($lang['attachtoobig'], false, '', '', false, false, false, false);
            return false;
        } else {
            $attachment = addslashes(fread(fopen($file['tmp_name'], 'rb'), filesize($file['tmp_name'])));
            $filename = $file['name'];
            $filetype = $file['type'];
            $filesize = $file['size'];

            if ($filesize == 0) {
                return false;
            } else {
                return $attachment;
            }
        }
    } else {
        return false;
    }
}

==================
Replace Code With:
==================

// Multi-Attachments and Image Resize Control Mod Begin
function get_attached_file($file, $attachstatus, $max_size=1000000) {
    global $db, $forum, $lang, $filename, $filetype, $filesize, $fileheight, $filewidth;

    $filename = $filetype = $fileheight = $filewidth = '';
    $filesize = 0;

    if (is_array($file) && $file['name'] != 'none' && $file['name']!= '' && $forum['attachstatus'] != 'off' && is_uploaded_file($file['tmp_name'])) {
        if (!isValidFilename($file['name'])) {
            error($lang['attach_invalidfilename'], false, '', '', false, false, false, false);
            return false;
        }

        $filesize = intval(filesize($file['tmp_name']));
        if ($filesize > $max_size) {
            error($lang['attachtoobig'], false, '', '', false, false, false, false);
            return false;
        }

        $attachment = addslashes(fread(fopen($file['tmp_name'], 'rb'), filesize($file['tmp_name'])));
        $filename = checkInput($file['name']);
        $filetype = checkInput($file['type']);

        $extention = strtolower(substr(strrchr($file['name'],'.'),1));
        if ($extention == 'jpg' || $extention == 'jpeg' || $extention == 'jpe' || $extention == 'gif' || $extention == 'png' || $extention == 'bmp') {
            $exsize = getimagesize($file['tmp_name']);
            $fileheight = $exsize[1];
            $filewidth = $exsize[0];
        }

        if ($filesize !== 0) {
            return $attachment;
        }
    }
    return false;
}

function get_attached_file_multi($file, $i, $attachstatus, $max_size=1000000) {
    global $db, $forum, $lang, $filename, $filetype, $filesize, $fileheight, $filewidth;

    $filename = $filetype = $fileheight = $filewidth = '';
    $filesize = 0;

    if ($file['name'] != 'none' && $file['name'][$i] != '' && $forum['attachstatus'] != 'off' && is_uploaded_file($file['tmp_name'][$i])) {
        if (!isValidFilename($file['name'][$i])) {
            error($lang['attach_invalidfilename'], false, '', '', false, false, false, false);
            return false;
        }

        $filesize = intval(filesize($file['tmp_name'][$i]));
        if ($filesize > $max_size) {
            error($lang['attachtoobig'], false, '', '', false, false, false, false);
            return false;
        }

        $attachment = addslashes(fread(fopen($file['tmp_name'][$i], 'rb'), filesize($file['tmp_name'][$i])));
        $filename = checkInput($file['name'][$i]);
        $filetype = checkInput($file['type'][$i]);

        $extention = strtolower(substr(strrchr($file['name'][$i],'.'),1));
        if ($extention == 'jpg' || $extention == 'jpeg' || $extention == 'jpe' || $extention == 'gif' || $extention == 'png' || $extention == 'bmp') {
            $exsize = getimagesize($file['tmp_name'][$i]);
            $fileheight = $exsize[1];
            $filewidth = $exsize[0];
        }

        if ($filesize !== 0) {
            return $attachment;
        }
    }
    return false;
}
// Multi-Attachments and Image Resize Control Mod End

============================================================================================================================
=======
Step 5:
=======
===============
Edit File: post.php
===============
==========
Find Code:
==========

loadtemplates(

================
Replace Code With:
================

loadtemplates(
'post_attach_edit_js',
'post_edit_attach_js',
'post_edit_attachment',

==========
Find Code:
==========

$fid = (isset($fid) ? (int) $fid : 0);

===============
Add Code Below:
===============

// Multi-Attachments and Image Resize Control Mod Begin
$aid = (isset($aid) ? (int) $aid : 0);
// Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

        // Insert Attachment if there is one
        // Do this last so if it errors out it doesn't break anything important
        if (isset($_FILES['attach']) && ($attachedfile = get_attached_file($_FILES['attach'], $forums['attachstatus'], $max_attach_size)) !== false) {
            $db->query("INSERT INTO $table_attachments ( aid, tid, pid, filename, filetype, filesize, attachment, downloads ) VALUES ('', '$tid', '$pid', '$filename', '$filetype', '$filesize', '$attachedfile', '0')");
        }

================
Replace Code With:
================

        // Multi-Attachments and Image Resize Control Mod Begin
        // Insert Attachment if there is one
        // Do this last so if it errors out it doesn't break anything important
        for ($i = 0; $i < $forum['attachnum']; $i++) {
            if (isset($_FILES['attach']) && ($attachment = get_attached_file_multi($_FILES['attach'], $i, $forums['attachstatus'], $max_attach_size)) === false) {
                continue;
            } else {
                if (isset($attachment)) {
                    $db->query("INSERT INTO $table_attachments (tid, pid, filename, filetype, filesize, attachment, downloads, fileheight, filewidth) VALUES ('$tid', '$pid', '$filename', '$filetype', '$filesize', '$attachment', '0', '$fileheight', '$filewidth')");
                }
            }
        }
        // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

            // Insert Attachment if there is one
            // Insert this last so if it errors out it doesn't break something
            if (($attachedfile = get_attached_file($_FILES['attach'], $forums['attachstatus'], $max_attach_size)) !== false) {
                $db->query("INSERT INTO $table_attachments ( aid, tid, pid, filename, filetype, filesize, attachment, downloads ) VALUES ('', '$tid', '$pid', '$filename', '$filetype', '$filesize', '$attachedfile', '0')");
            }

        }

================
Replace Code With:
================

            // Multi-Attachments and Image Resize Control Mod Begin
            // Insert Attachment if there is one
            // Insert this last so if it errors out it doesn't break something
            for ($i = 0; $i < $forum['attachnum']; $i++) {
                if (isset($_FILES['attach']) && ($attachment = get_attached_file_multi($_FILES['attach'], $i, $forums['attachstatus'], $max_attach_size)) === false) {
                    continue;
                } else {
                    if (isset($attachment)) {
                        $db->query("INSERT INTO $table_attachments (aid, tid, pid, filename, filetype, filesize, attachment, downloads, fileheight, filewidth) VALUES ('', '$tid', '$pid', '$filename', '$filetype', '$filesize', '$attachment', '0', '$fileheight', '$filewidth')");
                    }
                }
            }
        }
        // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

if ( $action == "newthread") {

===============
Add Code Below:
===============

    // Multi-Attachments and Image Resize Control Mod Begin
    $fattachnum = (int) $forum['attachnum'];
    eval('$attachscript = "'.template('post_attach_edit_js').'";');
    // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

}elseif ( $action == "reply") {

===============
Add Code Below:
===============

    // Multi-Attachments and Image Resize Control Mod Begin
    $fattachnum = (int) $forum['attachnum'];
    eval('$attachscript = "'.template('post_attach_edit_js').'";');
    // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

}elseif ( $action == "edit") {

===============
Add Code Below:
===============

    // Multi-Attachments and Image Resize Control Mod Begin
    eval('$attachscript = "'.template('post_edit_attach_js').'";');
    // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

            if (isset($_FILES['attach']) && ($file = get_attached_file($_FILES['attach'], $forums['attachstatus'], $max_attach_size)) !== false) {
                $db->query("INSERT INTO $table_attachments ( tid, pid, filename, filetype, filesize, attachment, downloads ) VALUES ('$tid', '$pid', '$filename', '$attach[type]', '$filesize', '$file', '0')");
            }

            if (isset($attachment) && is_array($attachment)) {
                switch($attachment['action']) {
                    case 'replace':
                        if (isset($_FILES['attachment_replace']) && ($file = get_attached_file($_FILES['attachment_replace'], $forums['attachstatus'], $max_attach_size)) !== false) {
                            $db->query("DELETE FROM $table_attachments WHERE pid='$pid'");
                            $db->query("INSERT INTO $table_attachments ( aid, tid, pid, filename, filetype, filesize, attachment, downloads ) VALUES ('', '$tid', '$pid', '$filename', '$attachment_replace[type]', '$filesize', '$file', '0')");
                        }
                        break;
                    case 'rename':
                        $name = basename($attach_name);
                        if (strlen($name) < 2 || preg_match('#^[^a-z0-9]+$#', $name) == 1) {
                            break;
                        } else {
                            $db->query("UPDATE $table_attachments SET filename='$name' WHERE pid='$pid'");
                        }
                        break;
                    case 'delete':
                        $db->query("DELETE FROM $table_attachments WHERE pid='$pid'");
                        break;

                    default:
                        break;
                }
            }

==================
Replace Code With:
==================

            // Multi-Attachments and Image Resize Control Mod Begin
            if (isset($attach_edit) && is_array($attach_edit)) {
                for ($i = 0; $i < count($attach_edit); $i++) {
                    switch ($attach_edit[$i]) {
                        case 'replace':
                            $attachment = get_attached_file_multi($_FILES['attach_edit_file'], $i, $forum['attachstatus'], $max_attach_size);
                            if (!$attachment) {
                                break;
                            } else {
                                $db->query("DELETE FROM $table_attachments WHERE pid='$pid' AND aid='$attach_edit_aid[$i]'");
                                $db->query("INSERT INTO $table_attachments (aid, tid, pid, filename, filetype, filesize, attachment, downloads, fileheight, filewidth) VALUES ('', '$tid', '$pid', '$filename', '$filetype', '$filesize', '$attachment', '0', '$fileheight', '$filewidth')");
                            }
                            break;
                        case 'rename':
                            $name = basename($attach_edit_name[$i]);
                            if (strlen(trim($name)) > 2 || preg_match('#^[^a-z0-9]+$#', $name) == 1) {
                                $db->query("UPDATE $table_attachments SET filename='$name' WHERE pid='$pid' AND aid='$attach_edit_aid[$i]'");
                            }
                            break;
                        case 'delete':
                            $db->query("DELETE FROM $table_attachments WHERE pid='$pid' AND aid='$attach_edit_aid[$i]'");
                            break;
                        default:
                            break;
                    }
                }
            }

            $attach_edit = (isset($attach_edit) ? $attach_edit : '');
            $fattachnum = $forum['attachnum'] - count($attach_edit);
            for ($i = 0; $i < $fattachnum; $i++) {
                if (isset($_FILES['attach']) && ($attachment = get_attached_file_multi($_FILES['attach'], $i, $forums['attachstatus'], $max_attach_size)) === false) {
                    continue;
                } else {
                    if (isset($attachment)) {
                        $db->query("INSERT INTO $table_attachments (aid, tid, pid, filename, filetype, filesize, attachment, downloads, fileheight, filewidth) VALUES ('', '$tid', '$pid', '$filename', '$filetype', '$filesize', '$attachment', '0', '$fileheight', '$filewidth')");
                    }
                }
            }
            // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

            $query = $db->query("SELECT filename, filesize, downloads FROM $table_attachments WHERE pid='$pid' AND tid='$tid'");

================
Replace Code With:
================

            $query = $db->query("SELECT filename, filesize, downloads, fileheight, filewidth FROM $table_attachments WHERE pid='$pid' AND tid='$tid'");

==========
Find Code:
==========

            $query = $db->query("SELECT a.filename, a.filesize, a.downloads, p.* FROM $table_posts p LEFT JOIN $table_attachments a  ON (a.pid = p.pid) WHERE p.pid='$pid' AND p.tid='$tid' AND p.fid='$forum[fid]'");

================
Replace Code With:
================

            $query = $db->query("SELECT p.* FROM $table_posts p WHERE p.pid='$pid' AND p.tid='$tid' AND p.fid='$forum[fid]'");

==========
Find Code:
==========

        if ( $postinfo['filename'] != '') {
            eval("\$attachment = \"".template('post_edit_attachment')."\";");
        }else{
            $attachment = $attachfile;
        }
        eval("\$edit = \"".template("post_edit")."\";");
        echo $edit;

==================
Replace Code With:
==================

        
        // Multi-Attachments and Image Resize Control Mod Begin
        $q = $db->query("SELECT * FROM $table_attachments WHERE pid='$pid'");
        $i = 0;
        if ($db->num_rows($q) > 0) {
            while ($attach = $db->fetch_array($q)) {
                eval('$attachment[] = "'.template('post_edit_attachment').'";');
                $i++;
            }
            $attachment = implode("\n", $attachment);
            $db->free_result($q);
        } else {
            $attachment = '';
        }

        $fattachnum = $forum['attachnum'] - $i;
        if ($fattachnum > 0 && isset($forums['attachstatus']) && $forums['attachstatus'] != 'off') {
            eval('$attachment .= "'.template('post_attachmentbox').'";');
        }
        eval('echo "'.template('post_attach_edit_js').template('post_edit').'";');
        // Multi-Attachments and Image Resize Control Mod End

============================================================================================================================
=======
Step 6:
=======
===================
Edit File: viewthread.php
===================
==========
Find Code:
==========

$fid = (isset($fid) && is_numeric($fid)) ? (int) $fid : 0;

===============
Add Code Below:
===============

// Multi-Attachments and Image Resize Control Mod Begin
$aid = (isset($aid) && is_numeric($aid)) ? (int) $aid : 0;
// Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

smcwcache();

===============
Add Code Above:
===============

// Multi-Attachments and Image Resize Control Mod Begin
class Attachments {
    var $attachments;

    function get_attachments($tid) {
        global $db, $start_limit, $ppp, $table_posts, $table_attachments;

        $pids = array();
        $q = $db->query("SELECT pid FROM $table_posts WHERE tid='$tid' ORDER BY pid LIMIT $start_limit, $ppp");
        while ($row = $db->fetch_array($q)) {
            $pids[] = $row['pid'];
        }
        $pids = "'".implode("', '", $pids)."'";

        $this->attachments = array();
        $q = $db->query("SELECT * FROM $table_attachments WHERE pid in($pids)");
        while ($row = $db->fetch_array($q)) {
            $this->attachments[] = $row;
        }
        $db->free_result($q);
    }

    function format_attach($bytes) {
        if ($bytes >= 1073741824) {
            $bytes = round($bytes / 1073741824 * 100) / 100 . "gb";
        } elseif ($bytes >= 1048576) {
            $bytes = round($bytes / 1048576 * 100) / 100 . "mb";
        } elseif ($bytes >= 1024) {
            $bytes = round($bytes / 1024 * 100) / 100 . "kb";
        } else {
            $bytes = $bytes . "b";
        }
        return $bytes;
    }

    function upgrade_attachment(& $attach) {
        global $db, $table_attachments;

        $aid = intval($attach['aid']);
        if ($aid == 0 || ini_get('safe_mode')) {
            return false;
        }

        $tempfn = tempnam("","");
        $temp = fopen($tempfn, "w");
        fwrite($temp, $attach['attachment']);
        fclose($temp);
        $exsize = getimagesize($tempfn);
        unlink($tempfn);

        $attach['fileheight'] = intval($exsize[1]);
        $attach['filewidth'] = intval($exsize[0]);

        $db->query("UPDATE $table_attachments SET fileheight=".$attach['fileheight'].", filewidth=".$attach['filewidth']." WHERE aid=".$aid);
    }

    function get_post_attachments($pid) {
        global $SETTINGS, $lang, $post, $forum, $tid, $n_height, $n_width, $attach;
        global $THEME, $bordercolor, $borderwidth, $tablespace, $cattext, $altbg1, $altbg2, $tablewidth;

        reset($this->attachments);
        $retval = '';
        foreach ($this->attachments as $attach) {
            if ((intval($attach['fileheight']) == 0 || intval($attach['filewidth']) == 0) && strpos($attach['filetype'], 'image') !== false) {
                $this->upgrade_attachment($attach);
            }
            if ($attach['pid'] == $pid) {
                $post['filename'] = htmlspecialchars($attach['filename']);
                if ($attach['filename'] != '' && isset($forum['attachstatus']) && $forum['attachstatus'] != 'off') {
                    $extention = strtolower(substr(strrchr($post['filename'],'.'),1));
                    $attachsize = $this->format_attach($attach['filesize']);
                    $downloadcount = $attach['downloads'];
                    if ($downloadcount == '') {
                        $downloadcount = 0;
                    }

                    if ($SETTINGS['attachimgpost'] == 'on' && ($extention == 'jpg' || $extention == 'jpeg' || $extention == 'jpe' || $extention == 'gif' || $extention == 'png' || $extention == 'bmp')) {
                        if ($attach['fileheight'] != '' && $attach['filewidth'] != '') {
                            $SETTINGS['max_attheight'] = (int) $SETTINGS['max_attheight'];
                            $SETTINGS['max_attwidth'] = (int) $SETTINGS['max_attwidth'];
                            $h_ratio = $SETTINGS['max_attheight'] / $attach['fileheight'];
                            $w_ratio = $SETTINGS['max_attwidth'] / $attach['filewidth'];
                            if (($attach['fileheight'] <= $SETTINGS['max_attheight']) && ($attach['filewidth'] <= $SETTINGS['max_attwidth'])) {
                                $n_height = $attach['fileheight'];
                                $n_width = $attach['filewidth'];
                            } elseif (($w_ratio * $attach['fileheight']) < $SETTINGS['max_attheight']) {
                                $n_height = ceil($w_ratio * $attach['fileheight']);
                                $n_width = $SETTINGS['max_attwidth'];
                            } else {
                                $n_height = $SETTINGS['max_attheight'];
                                $n_width = ceil($h_ratio * $attach['filewidth']);
                            }
                        }
                        eval("\$post['message'] .= \"".template('viewthread_post_attachmentimage')."\";");
                    } else {
                        eval("\$post['message'] .= \"".template('viewthread_post_attachment')."\";");
                    }
                }
            }
        }
    }
}
// Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========
    $querypost = $db->query("SELECT a.aid, a.filename, a.filetype, a.filesize, a.downloads, p.*, m.*,w.time FROM $table_posts p LEFT JOIN $table_members m ON m.username=p.author LEFT JOIN $table_attachments a ON a.pid=p.pid LEFT JOIN $table_whosonline w ON w.username=p.author WHERE p.fid='$fid' AND p.tid='$tid' GROUP BY p.pid ORDER BY p.pid ASC LIMIT $start_limit, $ppp");

================
Replace Code With:
================

    // Multi-Attachments and Image Resize Control Mod Begin
    $attachments = new Attachments;
    $attachments->get_attachments($tid);
    $querypost = $db->query("SELECT p.*, m.*,w.time FROM $table_posts p LEFT JOIN $table_members m ON m.username=p.author LEFT JOIN $table_whosonline w ON p.author=w.username WHERE p.fid='$fid' AND p.tid='$tid' $querypostsql ORDER BY p.pid ASC LIMIT $start_limit, $ppp");
    // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

        // Deal with the attachment if there is one
        if ($post['filename'] != '' && $forum['attachstatus'] != 'off') {
            $attachsize = $post['filesize'];
            if ($attachsize >= 1073741824) {
                $attachsize = round($attachsize / 1073741824 * 100) / 100 . "gb";
            } elseif ($attachsize >= 1048576) {
                $attachsize = round($attachsize / 1048576 * 100) / 100 . "mb";
                } elseif ($attachsize >= 1024) {
                $attachsize = round($attachsize / 1024 * 100) / 100 . "kb";
            } else {
                $attachsize = $attachsize . "b";
            }

            $extention = strtolower(substr(strrchr($post['filename'],"."),1));
            if ($attachimgpost == 'on' && ($extention == 'jpg' || $extention == 'jpeg' || $extention == 'jpe' || $extention == 'gif' || $extention == 'png' || $extention == 'bmp')) {
                eval("\$post['message'] .= \"".template('viewthread_post_attachmentimage')."\";");
            } else {
                $downloadcount = $post['downloads'];
                if ($downloadcount == '') {
                    $downloadcount = 0;
                }
                eval("\$post['message'] .= \"".template('viewthread_post_attachment')."\";");
            }
        }

================
Replace Code With:
================

        // Multi-Attachments and Image Resize Control Mod Begin
        $attachment = $attachments->get_post_attachments($post['pid']);
        // Multi-Attachments and Image Resize Control Mod End

==========
Find Code:
==========

} elseif ($action == "attachment" && $forum['attachstatus'] != 'off' && $pid > 0 && $tid > 0) {
    pwverify($forum['password'], 'viewthread.php?tid='.$tid, $fid, true);

    $query = $db->query("SELECT * FROM $table_attachments WHERE pid='$pid' and tid='$tid'");
    $file = $db->fetch_array($query);
    $db->free_result($query);

    $db->query("UPDATE $table_attachments SET downloads=downloads+1 WHERE pid='$pid'");

    if ($file['filesize'] != strlen($file['attachment'])) {
        error($lang['filecorrupt']);
    }

    $type = strtolower($file['filetype']);
    $name = $file['filename'];
    $size = (int) $file['filesize'];

    $type = ($type == 'text/html') ? 'text/plain' : $type;

    header("Content-type: $type");
    header("Content-length: $size");
    header("Content-Disposition: attachment; filename=$name");
    header("Content-Description: XMB Attachment");
    header("Cache-Control: public; max-age=604800");
    header("Expires: 604800");

    echo $file['attachment'];

    exit();

================
Replace Code With:
================

// Multi-Attachments and Image Resize Control Mod Begin
} elseif ($action == 'attachment' && isset($forum['attachstatus']) && $forum['attachstatus'] != 'off' && $pid > 0 && $tid > 0 && $aid > 0) {
    pwverify($forum['password'], 'viewthread.php?tid='.$tid, $fid, true);

    $query = $db->query("SELECT * FROM $table_attachments WHERE pid='$pid' AND tid='$tid' AND aid='$aid'");
    $file = $db->fetch_array($query);
    $db->free_result($query);

    $db->query("UPDATE $table_attachments SET downloads=downloads+1 WHERE pid='$pid' AND aid='$aid'");

    // Check if file is corrupt
    if ($file['filesize'] != strlen($file['attachment'])) {
        error($lang['attach_corrupt']);
    }

    // Generate $type, $name and $size vars
    $type = $file['filetype'];
    $name = str_replace(' ', '_', $file['filename']);
    $size = (int) $file['filesize'];

    // Make sure text/html types can't be run...
    $type = (strtolower($type) == 'text/html') ? 'text/plain' : $type;

    // Put out headers for mime-type, filesize, forced-download, description and no-cache.
    header("Content-type: $type");
    header("Content-length: $size");
    header("Content-Disposition: inline; filename = $name");
    header("Content-Description: PHP Generated Attachments");
    header("Cache-Control: public; max-age=604800");
    header("Expires: 604800");

    // Start file download
    echo $file['attachment'];

    // End download
    exit();
    // Multi-Attachments and Image Resize Control Mod End

============================================================================================================================
=======
Step 7:
=======
=======================
Edit File: lang/English.lang.php
=======================
==========
Find Code:
==========

$lang['textdownloadcount2'] = "times";

================
Replace Code With:
================

// Multi-Attachments and Image Resize Control Mod Begin
$lang['textdownloadcount2'] = "time(s)";
// Multi-Attachments and Image Resize Control Mod End

============================
Add Code To End Of File Above  ?>
============================

// Multi-Attachments and Image Resize Control Mod Begin
$lang['attach_numdefault'] = "Default max number of attachments allowed:";
$lang['attach_multiattach'] = "Max attachments allowed in this forum per post:";
$lang['attach_leave'] = "- Leave untouched -";
$lang['attach_replace'] = "- Replace with -";
$lang['attach_rename'] = "- Rename to -";
$lang['attach_add'] = "- Add attachment -";
$lang['attach_nomore'] = "No more than ";
$lang['attach_nomore2'] = " attachment(s) per post are allowed in this forum";
$lang['attach_delete'] = "- Delete attachment -";
$lang['attach_download'] = "Download:";
$lang['attach_image'] = "Image:";
$lang['attach_remove'] = " - Remove";
$lang['attach_invalidfilename'] = "Attachment upload aborted! Invalid filename!";
$lang['attach_corrupt'] = "The file you are trying to download appears corrupt. File download aborted!";
$lang['max_attheight'] = "Maximum height ration in pixels for attachments to display in posts.";
$lang['max_attwidth'] = "Maximum width ration in pixels for attachments to display in posts.";
$lang['thumbEnlarge'] = "Click Image To Enlarge";
// Multi-Attachments and Image Resize Control Mod End

============================================================================================================================
=======
Step 8:
=======
===============================
Go To Administration Panel --> Templates
===============================
================================
Create New Template: post_attach_edit_js
================================
=======================
Add Code & Submit Changes:
=======================

<script language="JavaScript" type="text/javascript">
var clicked    = 0;
var attachName = '';
var newFiles   = '';

function saveScrollPos(offset) {
    scrollPosVert = (document.all)?document.body.scrollTop:window.pageYOffset-offset;
}

function setScrollPos() {
    window.scrollTo(0, scrollPosVert);
    setTimeout('window.scrollTo(0, scrollPosVert)',1);
}

function add(FieldName) {
    attachName = FieldName;
    var newFields = document.getElementById('attachment').cloneNode(true);
    newFields.id = '';
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    if (clicked >= ($fattachnum - 1)) {
        window.alert('$lang[attach_nomore]$forum[attachnum]$lang[attach_nomore2]');
        return;
    } else {
        clicked++;
        for (var i = 0; i < newField.length; i++) {
            if (newField[i].name == attachName) {
                newField[i].name = attachName + '_' + i;
                newField[i].id = attachName + '_' + i;
            }
        }
        var insertHere = document.getElementById('attachment_box');
        insertHere.parentNode.insertBefore(newFields,insertHere);
    }
}

function removeFile(container, item) {
    var tmp = item.getElementsByTagName('input')[0];
    var basefieldname = '';
    if (tmp.type=='text') basefieldname = nameFile;
    var iRemove=Number(tmp.id.substring(basefieldname.length, tmp.id.length));
    var x = document.getElementById('attachment_box').getElementsByTagName('input');
    for (i = 1; i < x.length; i++) {
        if (x[i].type=='text') basefieldname=nameFile;
        var iEdit = Number(x[i].id.substring(basefieldname.length, x[i].id.length));
        if (iEdit>iRemove) {
            x[i].name = basefieldname + '_' + (iEdit-1);
            x[i].id = basefieldname + '_' + (iEdit-1);
        }
    }
    saveScrollPos(0);
    container.removeChild(item);
    setScrollPos();
    clicked--;
}
</script>

============================================================================================================================
=======
Step 9:
=======
===============================
Go To Administration Panel --> Templates
===============================
==========================
Edit Template: post_attachmentbox
==========================
================
Replace Code With:
================

<tr class="tablerow">
<td bgcolor="$THEME[altbg1]">$lang[attachment]<br />(<a href="javascript:add('attach')">$lang[attach_add]</a>)</td>
<td bgcolor="$THEME[altbg2]"><input type="hidden" name="MAX_FILE_SIZE" value="$max_attach_size" /><div id="attachment" style="display:none"><input type="file" id="file" name="attach[]" size="20" /><a href="#" onclick="javascript:removeFile(this.parentNode.parentNode,this.parentNode);">$lang[attach_remove]</a></div><input type="file" id="file" name="attach[0]" size="20" /><div id="attachment_box"></div></td>
</tr>

============================================================================================================================
========
Step 10:
========
===============================
Go To Administration Panel --> Templates
===============================
================================
Edit Template: viewthread_post_attachment
================================
================
Replace Code With:
================

<br />
<br />
<table cellspacing="0" cellpadding="0" border="0" width="100%" align="center">
<tr>
<td bgcolor="$THEME[bordercolor]">
<table border="0" cellspacing="$THEME[borderwidth]" cellpadding="$THEME[tablespace]" width="100%">
<tr class="category">
<td colspan="2"><font color="$THEME[cattext]"><strong>$lang[attachment]</strong></font></td>
</tr>
<tr class="tablerow">
<td bgcolor="$THEME[altbg1]" width="15%">$lang[textfilename]</td>
<td bgcolor="$THEME[altbg2]"><a title="$lang[textfilename] $attach[filename] - $lang[textfilesize] $attachsize" href="viewthread.php?action=attachment&amp;tid=$tid&amp;pid=$post[pid]&amp;aid=$attach[aid]" target="_blank">$attach[filename]</a></td>
</tr>
<tr class="tablerow">
<td bgcolor="$THEME[altbg1]" width="15%">$lang[textfilesize]</td>
<td bgcolor="$THEME[altbg2]">$attachsize</td>
</tr>
<tr class="tablerow" bgcolor="$THEME[altbg2]">
<td colspan="2">$lang[textdownloadcount1] $downloadcount $lang[textdownloadcount2]</td>
</tr>
</table>
</td>
</tr>
</table>

============================================================================================================================
========
Step 11:
========
===============================
Go To Administration Panel --> Templates
===============================
====================================
Edit Template: viewthread_post_attachmentimage
====================================
================
Replace Code With:
================

<br />
<br />
<table cellspacing="0" cellpadding="0" border="0" width="100%" align="center">
<tr>
<td bgcolor="$THEME[bordercolor]">
<table border="0" cellspacing="$THEME[borderwidth]" cellpadding="$THEME[tablespace]" width="100%">
<tr class="category">
<td class="title" colspan="2">$lang[attachment]</td>
</tr>
<tr class="tablerow">
<td bgcolor="$THEME[altbg1]" width="15%" valign="top">$lang[attach_image]</td>
<td bgcolor="$THEME[altbg2]"><img src="viewthread.php?action=attachment&amp;tid=$tid&amp;pid=$post[pid]&amp;aid=$attach[aid]" border="0" title="$lang[thumbEnlarge]" alt="$lang[thumbEnlarge]" width="$n_width" height="$n_height" onclick="window.open('viewthread.php?action=attachment&amp;tid=$tid&amp;pid=$post[pid]&amp;aid=$attach[aid]','ne','width=$attach[filewidth],height=$attach[fileheight],resizable=yes,scrollbars=yes')" /></td>
</tr>
<tr class="tablerow">
<td bgcolor="$THEME[altbg1]" width="15%">$lang[attach_download]</td>
<td bgcolor="$THEME[altbg2]"><a title="$lang[textfilename] $attach[filename] - $lang[textfilesize] $attachsize" href="viewthread.php?action=attachment&amp;tid=$tid&amp;pid=$post[pid]&amp;aid=$attach[aid]" target="_blank">$attach[filename]</a></td>
</tr>
<tr class="tablerow">
<td bgcolor="$THEME[altbg1]" width="15%">$lang[textfilesize]</td>
<td bgcolor="$THEME[altbg2]">$attachsize</td>
</tr>
<tr class="tablerow">
<td bgcolor="$THEME[altbg2]" colspan="2">$lang[textdownloadcount1] $downloadcount $lang[textdownloadcount2]</td>
</tr>
</table>
</td>
</tr>
</table>

============================================================================================================================
========
Step 12:
========
===============================
Go To Administration Panel --> Templates
===============================
===============================
Create New Template: post_edit_attach_js
===============================
=======================
Add Code & Submit Changes:
=======================

<script language="JavaScript" type="text/javascript">
function attachChange(i) {
    var currentElement;
    var selectedOption;
    var specialTextElement;
    form = document.forms["input"];
    currentElement = document.getElementById("attach_edit[" + i + "]");
    for (j = 0; j < currentElement.options.length; j++) {
        if (currentElement.options[j].selected === true) {
            selectedOption = currentElement.options[j];
            break;
        } else {
            continue;
        }
    }

    fileElement = form["attach_edit_file[" + i + "]"];
    textElement = form["attach_edit_name[" + i + "]"];
    switch (selectedOption.value) {
        case 'none':
            fileElement.style.display = 'none';
            textElement.style.display = 'none';
            break;
        case 'replace':
            fileElement.style.display = 'inline';
            textElement.style.display = 'none';
            break;
        case 'rename':
            fileElement.style.display = 'none';
            textElement.style.display = 'inline';
            break;
        case 'delete':
            fileElement.style.display = 'none';
            textElement.style.display = 'none';
            break;
    }
}
</script>

============================================================================================================================
========
Step 13:
========
===============================
Go To Administration Panel --> Templates
===============================
===========================
Edit Template: post_edit_attachment
===========================
================
Replace Code With:
================

<tr class="tablerow">
<td bgcolor="$THEME[altbg1]">
$lang[textfilename] <em>$attach[filename]</em><br />
$lang[textfilesize] <em>$attach[filesize] $lang[byte]</em><br />
$lang[textdownloads] <em>$attach[downloads]</em><br />
<em><a href="viewthread.php?action=attachment&amp;tid=$tid&amp;pid=$pid&amp;aid=$attach[aid]" target="_blank">$lang[textdownload]</a></em>
</td>
<td bgcolor="$THEME[altbg2]">
<input type="hidden" name="attach_edit_aid[$i]" value="$attach[aid]" style="display:none;" />
<select name="attach_edit[$i]" id="attach_edit[$i]" onchange="javascript:attachChange($i);return false;">
<option value="none" selected>$lang[attach_leave]</option>
<option value="replace">$lang[attach_replace]</option>
<option value="rename">$lang[attach_rename]</option>
<option value="delete">$lang[attach_delete]</option>
</select>
<input type="hidden" name="MAX_FILE_SIZE" value="$max_attach_size" /><br />
<input type="file" name="attach_edit_file[$i]" id="attach_edit_file[$i]" style="display:none;" />
<input type="text" name="attach_edit_name[$i]" style="display:none;" id="attach_edit_name[$i]" value="" /><br />
</td>
</tr>

============================================================================================================================
========
Step 14:
========
===============================
Go To Administration Panel --> Templates
===============================
=================
Edit Template: header
=================
==========
Find Code:
==========

$bbcodescript

===============
Add Code Below:
===============

$attachscript

============================================================================================================================
========
Step 15:
========
===============================
Go To Administration Panel --> Templates
===============================
===================
Edit Template: post_edit
===================
==========
Find Code:
==========

<input type="hidden" name="pid" value="$pid" />

===============
Add Code Below:
===============

<input type="hidden" name="aid" value="$aid" />

============================================================================================================================
========
Step 16:
========

Now go to Administration Panel --> Forums --> More Options --> set the number of attachments to the desired amount per forum you wish.

============================================================================================================================
Enjoy!