<?php
define('IN_COPPERMINE', true);
define('UPLOAD_PHP', true);
define('DB_INPUT_PHP', true);
define('CONFIG_PHP', true);
define('AVATAR_PHP', true); //language file
require('include/init.inc.php');
require('include/picmgmt.inc.php');

if (!USER_ID) cpg_die(ERROR, $lang_errors['access_denied'], __FILE__, __LINE__);

$event = isset($_REQUEST['event']) ? $_REQUEST['event'] : null;
switch ($event) {

    case 'picture':

        if (!USER_CAN_UPLOAD_PICTURES) cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);
        // Test if the filename of the temporary uploaded picture is empty
        if ($_FILES['userpicture']['tmp_name'] == '') cpg_die(ERROR, $lang_db_input_php['no_pic_uploaded'], __FILE__, __LINE__);
        // Pictures are moved in a directory named 10000 + USER_ID


		$mime_content = cpg_get_type($_FILES['userpicture']['name']);
		if ($mime_content['content'] != 'image' ) cpg_die(ERROR, "Error, please upload an image, this is ". $mime_content['content'], __FILE__, __LINE__);

        if (USER_ID && !defined('SILLY_SAFE_MODE')) {
            $filepath = $CONFIG['userpics'] . (USER_ID + FIRST_USER_CAT);
            $dest_dir = $CONFIG['fullpath'] . $filepath;
            if (!is_dir($dest_dir)) {
                mkdir($dest_dir, octdec($CONFIG['default_dir_mode']));
                if (!is_dir($dest_dir)) cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['err_mkdir'], $dest_dir), __FILE__, __LINE__, true);
                chmod($dest_dir, octdec($CONFIG['default_dir_mode']));
                $fp = fopen($dest_dir . '/index.html', 'w');
                fwrite($fp, ' ');
                fclose($fp);
            }
            $dest_dir .= '/';
            $filepath .= '/';
        } else {
            $filepath = $CONFIG['userpics'];
            $dest_dir = $CONFIG['fullpath'] . $filepath;
        }
        // Check that target dir is writable
        if (!is_writable($dest_dir)) cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['dest_dir_ro'], $dest_dir), __FILE__, __LINE__, true);
        // Replace forbidden chars with underscores
        $matches = array();
        $forbidden_chars = strtr($CONFIG['forbiden_fname_char'], array('&amp;' => '&', '&quot;' => '"', '&lt;' => '<', '&gt;' => '>'));
        // Check that the file uploaded has a valid extension
        if (get_magic_quotes_gpc()) $_FILES['userpicture']['name'] = stripslashes($_FILES['userpicture']['name']);
        $picture_name = strtr($_FILES['userpicture']['name'], $forbidden_chars, str_repeat('_', strlen($CONFIG['forbiden_fname_char'])));
        if (!preg_match("/(.+)\.(.*?)\Z/", $picture_name, $matches)) {
            $matches[1] = 'invalid_fname';
            $matches[2] = 'xxx';
        }

        if ($matches[2] == '' || !is_known_filetype($matches)) {
            cpg_die(ERROR, sprintf($lang_db_input_php['err_invalid_fext'], $CONFIG['allowed_file_extensions']), __FILE__, __LINE__);
        }

        // Create a unique name for the uploaded file
        $nr = 0;
        $picture_name = $matches[1] . '.' . $matches[2];
		$avatar_name = 'user_'.(USER_ID + FIRST_USER_CAT).'_avatar.' . $matches[2];
        while (file_exists($dest_dir . $picture_name)) {
            $picture_name = $matches[1] . '~' . $nr++ . '.' . $matches[2];
        }
        $uploaded_pic = $dest_dir . $picture_name;
        // Move the picture into its final location
        if (!move_uploaded_file($_FILES['userpicture']['tmp_name'], $uploaded_pic))
            cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['err_move'], $picture_name, $dest_dir), __FILE__, __LINE__, true);
        // Change file permission
        chmod($uploaded_pic, octdec($CONFIG['default_file_mode']));
        // Get picture information


        // Check that picture file size is lower than the maximum allowed
        if (filesize($uploaded_pic) > ($CONFIG['max_upl_size'] << 10)) {
            @unlink($uploaded_pic);
            cpg_die(ERROR, sprintf($lang_db_input_php['err_imgsize_too_large'], $CONFIG['max_upl_size']), __FILE__, __LINE__);
        } elseif (is_image($picture_name)) {
            $imginfo = getimagesize($uploaded_pic);
            // getimagesize does not recognize the file as a picture
            if ($imginfo == null) {
                @unlink($uploaded_pic);
                cpg_die(ERROR, $lang_db_input_php['err_invalid_img'], __FILE__, __LINE__, true);
            // JPEG and PNG only are allowed with GD
            } elseif ($imginfo[2] != GIS_JPG && $imginfo[2] != GIS_PNG && $imginfo[2] != GIS_GIF && ($CONFIG['thumb_method'] == 'gd1' || $CONFIG['thumb_method'] == 'gd2')) {
                @unlink($uploaded_pic);
                cpg_die(ERROR, $lang_errors['gd_file_type_err'], __FILE__, __LINE__, true);
            } elseif (max($imginfo[0], $imginfo[1]) > $CONFIG['max_upl_width_height']) {
                @unlink($uploaded_pic);
                cpg_die(ERROR, sprintf($lang_db_input_php['err_fsize_too_large'], $CONFIG['max_upl_width_height'], $CONFIG['max_upl_width_height']), __FILE__, __LINE__);
            } // Image is ok
        }

    $work_image = $CONFIG['fullpath'] . $filepath . $picture_name;
	$avatar = $CONFIG['fullpath'] . $filepath . $avatar_name;
            if (!resize_image($work_image, $avatar, $CONFIG['mini_thumb_width'], $CONFIG['thumb_method'], "mini", "false", 1))
				{
		     	@unlink($uploaded_pic);
            	cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['err_insert_pic'], $uploaded_pic) . '<br /><br />' . $ERROR, __FILE__, __LINE__, true);
        
        } else {
			cpg_db_query("UPDATE {$CONFIG['TABLE_USERS']} SET avatar_url='".$avatar."' WHERE user_id='".(USER_ID)."'");
			//not used anymore due to bridge compatibility
			//cpg_db_query("UPDATE {$CONFIG['TABLE_COMMENTS']} SET avatar_url='".$avatar."' WHERE author_id='".(USER_ID)."'");

			@unlink($uploaded_pic);
            $header_location = (@preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE'))) ? 'Refresh: 0; URL=' : 'Location: ';
            $redirect = "avatar_manage.php";
            header($header_location . $redirect);
            pageheader($lang_info, "<META http-equiv=\"refresh\" content=\"1;url=$redirect\">");
            msg_box($lang_info, $lang_db_input_php['upl_success'], $lang_continue, $redirect);
            pagefooter();
            ob_end_flush();
            exit;
        }
		break;
}	



if(isset($_POST['dowhat']))
{

	switch ($_POST['dowhat']) {
	case "delete_avatar":
		if (isset($_POST['all_avatar'])) { //confirm checkbox clicked??
			//first let's check if an uploaded avatar is in his folder
				$result = cpg_db_query("SELECT avatar_url FROM {$CONFIG['TABLE_USERS']} WHERE user_id = '".(USER_ID)."'");
				$url_data = mysql_fetch_array($result);
				mysql_free_result($result);
				$avatar_url = $url_data['avatar_url'];
				@unlink($avatar_url);

			cpg_db_query("UPDATE {$CONFIG['TABLE_USERS']} SET avatar_url='' WHERE user_id='".(USER_ID)."'");
			//not used anymore due to bridge compatibility
			//cpg_db_query("UPDATE {$CONFIG['TABLE_COMMENTS']} SET avatar_url='' WHERE author_id='".(USER_ID)."'");
			header('Location: '.$PHP_SELF);
		}
	   	break;
	case "set_avatar":
		$mark_list=$_POST['list'];
		if ($marklist[0]) header('Location: http://localhost');
		while(list($key, $value) = each($mark_list)) 
			if ($key) 
			{
			
			echo $value. " <- value<br>";
	       	$matches = array();
	       	preg_match("/(.+)\.(.*?)\Z/", $key, $matches);

			$avatar_name = 'user_'.(USER_ID + FIRST_USER_CAT).'_avatar.' . $matches[2];
			if (!copy($CONFIG['fullpath'] . $value . $key, $CONFIG['fullpath'] . $value . $avatar_name))
                return false;			
			
			cpg_db_query("UPDATE {$CONFIG['TABLE_USERS']} SET avatar_url='".$CONFIG['fullpath']. $value . $avatar_name."' WHERE user_id='".(USER_ID)."'");
			//not used anymore due to bridge compatibility
			//cpg_db_query("UPDATE {$CONFIG['TABLE_COMMENTS']} SET avatar_url='".$CONFIG['fullpath'].$key."' WHERE author_id='".(USER_ID)."'");
			}
			header('Location: '.$PHP_SELF);
	   break;
	}

}

$result = cpg_db_query("SELECT count(*) FROM  {$CONFIG['TABLE_PICTURES']} WHERE owner_id=".(USER_ID));
list($tot_pictures) = @mysql_fetch_array($result);

$result = cpg_db_query("SELECT avatar_url FROM {$CONFIG['TABLE_USERS']} WHERE user_id = '".(USER_ID)."'");
$url_data = mysql_fetch_array($result);
mysql_free_result($result);
$avatar_url = $url_data['avatar_url'];
if ($avatar_url !="") $avatar_url = "<img src='".$avatar_url."' class=\"image\">";
else $avatar_url="";



pageheader($lang_avatar['manage']);
echo <<<EOT



<form action="avatar_manage.php" method="post">


<table class="maintable" cellpadding="6" cellspacing="1" border="0" width="100%" align="center">
	<tr>
		<td class="tableh1" colspan="2" style="padding: 6px 0 6px 6px"><strong>$lang_avatar[stats]</strong></td>
	</tr>
	<tr>
		<td class="panelsurround" align="center">
		<span style="float: left">$lang_avatar[available_pics] $tot_pictures $lang_avatar[pictures]!</span><br /><br />
		<div class="panel">
			<div style="width:480px" align="left">
			
			<fieldset class="fieldset">
				<legend>$avatar_url</legend>
				<table cellpadding="0" cellspacing="3" border="0">
				<tr>
					<td>$lang_avatar[remove]</td>
				</tr>
				<tr>
					<td><label for="deleteavatar"><input type="checkbox" name="all_avatar" id="all_avatar" value="true" />$lang_avatar[remove_avatar]</label></td>
				</tr>
				</table>
			</fieldset>
			
			</div>
		</div>
		
		<div style="margin-top:6px">
			<input type="hidden" name="dowhat" value="delete_avatar" />
			<input type="submit" class="button" value="$lang_avatar[remove_avatar]" accesskey="s" />
		</div>
		</td>
	</tr>
</table>

</form>

<table class="maintable graybox" cellpadding="0" cellspacing="1" border="0" width="100%" align="center">
EOT;
create_avatar_upload ();
echo <<<EOT
</table>
EOT;

if ($tot_pictures > 0 && $CONFIG['enable_mini_thumbs']){

echo <<<EOT
<form action="avatar_manage.php" method="post" name="form">
<table class="maintable" cellpadding="0" cellspacing="1" border="0" width="100%" align="center">
<thead>
	<tr>
		<td class="tableh1 graybox" colspan="4" style="padding: 6px 0 6px 6px">
				<strong>$lang_avatar[manage]</strong><span>:</span> $lang_avatar[select]			
		</td>
	</tr>
</thead>
<tr><td>
<table class="tborder" cellpadding="6" cellspacing="1" border="0" width="100%" align="center">
EOT;



    $sort_codes = array(
        'title_a' => 'title ASC',
        'title_d' => 'title DESC',
		'image_name_a' => 'filename ASC',
	    'image_name_d' => 'filename DESC',
		'date_a' => 'ctime ASC',
        'date_d' => 'ctime DESC',
        );

    $sort = (!isset($_GET['sort']) || !isset($sort_codes[$_GET['sort']])) ? 'title_a' : $_GET['sort'];

    $tab_tmpl = array('left_text' => '<td width="100%%" align="left" valign="middle" class="tableh1_compact" style="white-space: nowrap"><b>' . $lang_avatar['u_pics_on_p_pages'] . '</b></td>' . "\n",
        'tab_header' => '',
        'tab_trailer' => '',
        'active_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="tableb_compact"><b>%d</b></td>',
        'inactive_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="navmenu"><a href="' . $PHP_SELF . '?page=%d&sort=' . $sort . '"<b>%d</b></a></td>' . "\n",
		'active_next_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="tableb_compact"><b>%s</b></td>',
		'inactive_next_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="navmenu"><a href="' . $PHP_SELF . '?page=%s&sort=' . $sort . '"<b>Next</b></a></td>',
		'active_prev_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="tableb_compact"><b>%s</b></td>',
		'inactive_prev_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="navmenu"><a href="' . $PHP_SELF . '?page=%s&sort=' . $sort . '"<b>Prev</b></a></td>'
		);

    $subscr_per_page = 25;
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $lower_limit = ($page-1) * $subscr_per_page;
    $total_pages = ceil($tot_pictures / $subscr_per_page);


//end tabs setup

$sql = 	"SELECT p.pid, p.title, p.caption, p.ctime, p.filepath, p.filename ".
		" FROM {$CONFIG['TABLE_PICTURES']} AS p WHERE  p.owner_id=".(USER_ID).
		" ORDER BY " . $sort_codes[$sort] . " ".
        "LIMIT $lower_limit, $subscr_per_page;";


$tabs = create_tabs($tot_pictures, $page, $total_pages, $tab_tmpl);

		
$result = cpg_db_query($sql);
$total= @mysql_num_rows($result);
while($i=mysql_fetch_array($result))
{

$pid=$i['pid'];
$filepath=$i['filepath'];
$filename=$CONFIG['mini_pfx'].urlencode($i['filename']);

$lb = "<select name=\"album_listbox\" class=\"listbox\" onChange=\"if(this.options[this.selectedIndex].value) window.location.href='$PHP_SELF?page=$page&sort='+this.options[this.selectedIndex].value;\">\n";
	foreach($sort_codes as $key => $value) {
		  $selected = ($key == $sort) ? "SELECTED" : "";
		  $lb .= "        <option value=\"" . $key . "\" $selected>" . $lang_avatar[$key] . "</option>\n";
	}
$lb .= "</select>\n";
$this_date=localised_date($i['ctime'], $comment_date_fmt);	

$mime_content = cpg_get_type($i['filename']);
if ($mime_content['content'] == 'image' ) {

if ($CONFIG['enable_mini_thumbs']){
$preview = <<<EOT
<a href="displayimage.php?pos=-$i[pid]"><img src="{$CONFIG['fullpath']}$i[filepath]{$CONFIG['mini_pfx']}$i[filename]" width="{$CONFIG['mini_thumb_width']}" height="{$CONFIG['mini_thumb_height']}" alt=""  class="image" /></a>
EOT;
}
else $preview = "&nbsp;&nbsp;&nbsp;";
echo <<<EOT

	<tr>
	<td class="alt1"><img src="{$THEME_DIR}images/pm_replied.gif" alt="" border="0" /></td>
	<td class="alt2">$preview</td>
	<td class="alt1Active" id="pmid" width="100%">

		<div>
			<span style="float:right" class="smallfont">$this_date</span>
			$lang_avatar[title] <a href="displayimage.php?pos=-$i[pid]">$i[title]</a>
		</div>
		<div class="smallfont">
			<span style="float:right" class="time">$i[filename]</span>
		</div>
	
	</td>
	<td class="alt2" align="center" style="padding:0px"><input type="checkbox" id="checkall" name="list[$filename]" value="$filepath" /></td>
</tr>

EOT;

}
}
echo <<<EOT
</tbody></table>
<table class="tableb" cellpadding="0" cellspacing="0" border="0" width="100%" align="center">
<tr><td><br /></td></tr>
</table>

<table class="tablef graybox" cellpadding="0" cellspacing="0" border="0" width="100%" align="center">
<thead>
	<tr>
		<td class="tablef" align="left" colspan="2">			
			<div class="smallfont">
				$lang_avatar[selected]
				<select name="dowhat">
					<option value="do_nothing">$lang_avatar[do_nothing]</option>
					<option value="set_avatar">$lang_avatar[set_avatar]</option>
				</select>
				<input type="submit" class="button" value="$lang_avatar[go]" />
			</div>		
		</td></form>
		<form method="post" action="$PHP_SELF?op=new_user">
		<td class="tablef" align="right" colspan="2">
			<div class="smallfont">
				$lang_avatar[sort_by] $lb
			</div>		
		</td></form>
	</tr>
</thead>
      <tr>
              <td colspan="4" style="padding: 0px;">
                      <table width="100%" cellspacing="0" cellpadding="0">
                              <tr>
                                      $tabs
                              </tr>
                      </table>
              </td>
      </tr>
</table>




EOT;
endtable();
}

pagefooter();
ob_end_flush();




/* ################################################################################################ */
function clean_table() {
    global $CONFIG;
    $comparative_timestamp = time() - 3600;
    $result = mysql_query("DELETE FROM {$CONFIG['TABLE_TEMPDATA']} WHERE timestamp < $comparative_timestamp");
    if ($result) {
        return TRUE;
    } else {
        return FALSE;
    }
}


function hidden_input($name, $value) {
        echo "        <input type=\"hidden\" name=\"$name\" value=\"$value\">\n";
}


function file_input($text, $name, $iterations) {

    $ordinal = '';

    // Begin loop
    for ($counter=0; $counter<$iterations; $counter++) {

    // Create a numbering system when necessary.
    if ($text == '') {
        $cardinal = $counter + 1;
        $ordinal = "".$cardinal.". ";
    }

    // Create the file input box.
    echo <<<EOT
        <tr>
            <td class="tableb">
                        $text  $ordinal
        </td>
        <td class="tableb" valign="top">
                        <input type="file" name="$name" size="40" class="listbox">
                </td>
        </tr>

EOT;
    }
}

function create_form(&$data) {
    global $CONFIG;
    foreach($data as $element) {
        if ((is_array($element))) {
            switch ($element[2]) {
                case 0 :
                    text_box_input($element[0], $element[1], $element[3], $element[4]);
                    break;
                case 1 :
                    file_input($element[0], $element[1], $element[3]);
                    break;
                case 2 :
                    form_alb_list_box($element[0], $element[1]);
                    break;
                case 3 :
                    text_area_input($element[0], $element[1], $element[3]);
                    break;
                case 4 :
                    hidden_input($element[0], $element[1]);
                    break;
                default:
                    cpg_die(ERROR, $lang_upload_php['reg_instr_1'], __FILE__, __LINE__);
            } // switch
        } else {
            form_label($element);
        }
    }
}

function form_label($text) {
    echo <<<EOT
        <tr>
                <td class="tableh2" colspan="2">
                        <b>$text</b>
                </td>
        </tr>

EOT;
}

function open_form($path) {

    echo <<<EOT
    <script language="JavaScript">
    function textCounter(field, maxlimit) {
            if (field.value.length > maxlimit) // if too long...trim it!
            field.value = field.value.substring(0, maxlimit);
    }
    </script>
    <form method="post" action="$path" ENCTYPE="multipart/form-data">
    </td>
EOT;
}


function close_form($button_value) {
global $lang_upload_php;
echo <<<EOT
        <tr>
                <td colspan="2" align="center" class="tablef">
                        <input type="submit" value="{$button_value}" class="button">
                </td>
                </form>
        </tr>

EOT;
}


function form_instructions() {

    global $CONFIG, $lang_upload_php, $user_form, $max_file_size;

    echo "<tr><td colspan=2><br />";

    printf ($lang_upload_php['avatar_instr_1'], $CONFIG['max_upl_size']);

    echo "</td></tr>";

}	




function create_avatar_upload ()
{
	global $lang_upload_php, $CONFIG, $max_file_size;
    // Do some cleanup in the edit directory.
    spring_cleaning('./albums/edit',3600);

    // Do some cleaning in the temp data table.
    clean_table();

    // Create upload form headers.
    //pageheader($lang_upload_php['title']);

    // Open the form table.
    //starttable("100%", $lang_upload_php['title'], 2);
 
 
        // The user has the single upload only form. Send the request to db_input.php.
        open_form($_SERVER['PHP_SELF']);
        //open_form('upload_avatar.php');
        form_instructions();
 
 
 
 
         // The user should have the 'single upload only' form.

        // Declare an array containing the various upload form box definitions.
        $captionLabel = $lang_upload_php['description'];
        $form_array = array(
        sprintf($lang_upload_php['max_fsize'], $CONFIG['max_upl_size']),
        array('MAX_FILE_SIZE', $max_file_size, 4),
        array($lang_upload_php['picture'], 'userpicture', 1, 1),
        array('event', 'picture', 4)
        );


 
 
 
 
     create_form($form_array);
 
 
        // The user has the single upload only form. Select proper language for button.
        close_form($lang_upload_php['title']);
		
		    //endtable();
    //pagefooter();
    //ob_end_flush();

    // Exit the script.

    //exit;
}


?>