<?php
/************************************************************************/
/* Maximus CMS: Web Portal System                                       */
/* ==============================                                       */
/*                                                                      */
/* Copyright (c) 2002 - 2007                                            */
/* http://www.php-maximus.org                                           */
/* dev@php-maximus.org                                                  */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
/* Based on PHP-NUKE: Web Portal System                                 */
/************************************************************************/
/* Portage Coppermine Photo Gallery                                     */
/************************************************************************/
defined('MAXIMUS') or require_once("mainfile.php");

if ( !defined('USER_ALLOW') ) {
	redirect_url('modules.php?name=Coppermine');
}

$pagetitle = "- Coppermine";


switch($func) {
default:
incoh();
$aid = $album;
define('IN_COPPERMINE', true);
define('DB_INPUT_PHP', true);

require('modules/Coppermine/include/init.inc.php');
require('modules/Coppermine/include/picmgmt.inc.php');

function check_comment(&$str)
{
	global $CONFIG, $lang_bad_words;

	$ercp = array('/\S{'.($CONFIG['max_com_wlength']+1).',}/i');
	if ($CONFIG['filter_bad_words']) foreach($lang_bad_words as $word){
		$ercp[] = '/'.($word[0] == '*' ? '': '\b'). str_replace('*', '', $word). ($word[(strlen($word)-1)] == '*' ? '': '\b').'/i';
	}

	if (strlen($str)>$CONFIG['max_com_size']) $str = substr($str, 0, ($CONFIG['max_com_size'] -3)).'...';
	$str = preg_replace($ercp, '(...)', $str);
}


$event = isset($_POST['event']) ? $_POST['event'] : $HTTP_GET_VARS['event'];
switch ($event){
//
// Comment update
//
	case 'comment_update':
	new_cache();
	if (!(USER_CAN_POST_COMMENTS)) cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);

	check_comment($_POST['msg_body']);
	$msg_body = secure( $_POST['msg_body'], '', 1, 'sec' );
	$msg_id   = secure( $_POST['msg_id'], 'num', 1, 'sec' );

	if($msg_body == '') cpg_die(ERROR, $lang_db_input_php['err_comment_empty'], __FILE__, __LINE__);

	if (GALLERY_ADMIN_MODE) {
	    $update = $GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_COMMENTS."` SET `msg_body`='$msg_body' WHERE `msg_id`='$msg_id'");
	} elseif (USER_ID) {
	    $update = $GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_COMMENTS."` SET `msg_body`='$msg_body' WHERE `msg_id`='$msg_id' AND `author_id` ='".USER_ID."' LIMIT 1");
	} else {
	    $update = $GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_COMMENTS."` SET `msg_body`='$msg_body' WHERE `msg_id`='$msg_id' AND `author_md5_id` ='{$USER['ID']}' AND `author_id` = '0' LIMIT 1");
	}

	$header_location = ( @preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE')) ) ? 'Refresh: 0; URL=' : 'Location: ';

	$result = $GLOBALS['db']->sql_query("SELECT `pid` FROM `".TABLE_CPG_COMMENTS."` WHERE `msg_id`='$msg_id'");
	if (!$GLOBALS['db']->sql_numrows($result)) {
		$GLOBALS['db']->sql_free($result);
		$header_location = ( @preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE')) ) ? 'Refresh: 0; URL=' : 'Location: ';
		$redirect = "modules.php?name=Coppermine";
   		header($header_location.$redirect);
		pageheader($lang_info,"<meta http-equiv=\"refresh\" content=\"1;url=$redirect\">");
		msg_box($lang_info, $lang_db_input_php['redirect_msg'], $lang_db_input_php['continue'], $redirect);
		pagefooter();
		ob_end_flush();
		exit;
	} else {
		$comment_data = $GLOBALS['db']->sql_fetchrow($result);
		$GLOBALS['db']->sql_free($result);
		$redirect = "modules.php?name=Coppermine&op=displayimage&pos=".(-$comment_data['pid']);
   		header($header_location.$redirect);
		pageheader($lang_info,"<meta http-equiv=\"refresh\" content=\"1;url=$redirect\">");
		msg_box($lang_info, $lang_db_input_php['redirect_msg'], $lang_db_input_php['continue'], $redirect);
		pagefooter();
		ob_end_flush();
		exit;
	}
	break;
//
// Comment
//
	case 'comment':
	if (!(USER_CAN_POST_COMMENTS)) cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);
	new_cache();
	check_comment($_POST['msg_body']);
	$msg_author = secure( $_POST['msg_author'], '', 1, 'sec' );
	$msg_body   = secure( $_POST['msg_body'], '', 1, 'sec' );
	$pid        = secure( $_POST['pid'], 'num', 1, 'sec' );

	if($msg_author == '' || $msg_body == '') cpg_die(ERROR, $lang_db_input_php['empty_name_or_com'], __FILE__, __LINE__);

	$result = $GLOBALS['db']->sql_query("SELECT `comments` FROM `".TABLE_CPG_PICTURES."`, `".TABLE_CPG_ALBUMS."` WHERE ".TABLE_CPG_ALBUMS.".aid = ".TABLE_CPG_ALBUMS.".aid AND `pid`='$pid'");
	if (!$GLOBALS['db']->sql_numrows($result)) cpg_die(ERROR, $lang_errors['non_exist_ap'], __FILE__, __LINE__);
	$album_data = $GLOBALS['db']->sql_fetchrow($result);
	$GLOBALS['db']->sql_free($result);

	if ($album_data['comments'] != 'YES') cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);

	$result = $GLOBALS['db']->sql_query("SELECT `author_md5_id`, `author_id` FROM `".TABLE_CPG_COMMENTS."` WHERE `pid` = '$pid' ORDER BY `msg_id` DESC LIMIT 1");
	if ($GLOBALS['db']->sql_numrows($result)) {
	    $last_com_data = $GLOBALS['db']->sql_fetchrow($result);
		if ((USER_ID && $last_com_data['author_id'] == USER_ID) || (!USER_ID && $last_com_data['author_md5_id'] == $USER['ID'])) {
		    cpg_die(ERROR, $lang_db_input_php['no_flood'], __FILE__, __LINE__);
		}
	}

	if (!USER_ID) { // Anonymous users, we need to use META refresh to save the cookie
		$insert = $GLOBALS['db']->sql_query("INSERT INTO `".TABLE_CPG_COMMENTS."` (pid, msg_author, msg_body, msg_date, author_md5_id, author_id) VALUES ('$pid', '$msg_author', '$msg_body', NOW(), '{$USER['ID']}', '0')");

		$USER['name'] = secure( $_POST['msg_author'], '', 1, 'sec' );
		$redirect = "modules.php?name=Coppermine&op=displayimage&pos=".(-$pid);
		pageheader($lang_db_input_php['com_added'],"<META http-equiv=\"refresh\" content=\"1;url=$redirect\">");
		msg_box($lang_db_input_php['info'],$lang_db_input_php['com_added'], $lang_continue, $redirect);
		pagefooter();
		ob_end_flush();
		exit;
	} else { // Registered users, we can use Location to redirect
		$insert = $GLOBALS['db']->sql_query("INSERT INTO `".TABLE_CPG_COMMENTS."` (pid, msg_author, msg_body, msg_date, author_md5_id, author_id) VALUES ('$pid', '".username."', '$msg_body', NOW(), '', '".USER_ID."')");
		$header_location = ( @preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE')) ) ? 'Refresh: 0; URL=' : 'Location: ';
		$redirect = "modules.php?name=Coppermine&op=displayimage&pos=".(-$pid);
		header($header_location.$redirect);
		pageheader($lang_db_input_php['com_added'],"<meta http-equiv=\"refresh\" content=\"1;url=$redirect\">");
		msg_box($lang_db_input_php['info'],$lang_db_input_php['com_added'], $lang_continue, $redirect);
		pagefooter();
		ob_end_flush();
		exit;
	}
	break;
//
// Update album
//
	case 'album_update':
	if (!(USER_ADMIN_MODE || GALLERY_ADMIN_MODE)) cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);
	new_cache();
	$albumid     = secure( $_POST['albumid'], 'num', 1, 'sec' );
	$aid         = secure( $_POST['aid'], 'num', 1, 'sec' );
	$title       = secure( $_POST['title'], '', 1, 'sec' );
	$category    = secure( $_POST['category'], 'num', 1, 'sec' );
	$description = secure( $_POST['description'], '', 1, 'sec' );
	$thumb       = secure( $_POST['thumb'], 'num', 1, 'sec' );
	$visibility  = secure( $_POST['visibility'], 'num', 1, 'sec' );
	$uploads     = $_POST['uploads'] == 'YES' ? 'YES' : 'NO';
	$comments    = $_POST['comments'] == 'YES' ? 'YES' : 'NO';
	$votes       = $_POST['votes'] == 'YES' ? 'YES' : 'NO';

	if (!$title) cpg_die(ERROR, $lang_db_input_php['alb_need_title'], __FILE__, __LINE__);

	if (GALLERY_ADMIN_MODE) {
	    $query = "UPDATE `".TABLE_CPG_ALBUMS."` SET `title`='$title', `description`='$description', `category`='$category', `thumb`='$thumb', `uploads`='$uploads', `comments`='$comments', `votes`='$votes', `visibility`='$visibility' WHERE `aid`='$albumid' LIMIT 1";
	} else {
		$category = FIRST_USER_CAT + USER_ID;
		if ($visibility != $category && $visibility != $USER_DATA['group_id']) $visibility = 0;
	    $query = "UPDATE `".TABLE_CPG_ALBUMS."` SET `title`='$title', `description`='$description', `thumb`='$thumb',  `comments`='$comments', `votes`='$votes', `visibility`='$visibility' WHERE `aid`='$albumid' AND `category`='$category' LIMIT 1";
	}

	$update = $GLOBALS['db']->sql_query($query);
	if (!mysql_affected_rows()) cpg_die(INFORMATION, $lang_db_input_php['no_udp_needed'], __FILE__, __LINE__);

	pageheader($lang_db_input_php['alb_updated'],"<meta http-equiv=\"refresh\" content=\"1;url=modules.php?name=Coppermine&op=modifyalb&album=$aid\">");
	msg_box($lang_db_input_php['info'], $lang_db_input_php['alb_updated'], $lang_continue, "modules.php?name=Coppermine&op=modifyalb&album=$albumid");
	pagefooter();
	ob_end_flush();
	exit;
	break;
//
// Picture upload
//
	case 'picture':
	if (!USER_CAN_UPLOAD_PICTURES) cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);
	new_cache();
	$album    = secure( $_POST['album'], 'num', 1, 'sec' );
	$title    = secure( $_POST['title'], '', 1, 'sec' );
	$caption  = secure( $_POST['caption'], '', 1, 'sec' );
	$keywords = secure( $_POST['keywords'], '', 1, 'sec' );
	$user1    = secure( $_POST['user1'], '', 1, 'sec' );
	$user2    = secure( $_POST['user2'], '', 1, 'sec' );
	$user3    = secure( $_POST['user3'], '', 1, 'sec' );
	$user4    = secure( $_POST['user4'], '', 1, 'sec' );

	// Check if the album id provided is valid
	if (!GALLERY_ADMIN_MODE){
		$result = $GLOBALS['db']->sql_query("SELECT `category` FROM `".TABLE_CPG_ALBUMS."` WHERE `aid`='$album' and (`uploads` = 'YES' OR `category` = '".(USER_ID + FIRST_USER_CAT)."')");
		if ($GLOBALS['db']->sql_numrows($result) == 0 )cpg_die(ERROR, $lang_db_input_php['unknown_album'], __FILE__, __LINE__);
		$row = $GLOBALS['db']->sql_fetchrow($result);
		$GLOBALS['db']->sql_free($result);
		$category = secure( $row['category'], 'strip', 1 );
	} else {
		$result = $GLOBALS['db']->sql_query("SELECT `category` FROM `".TABLE_CPG_ALBUMS."` WHERE `aid`='$album'");
		if ($GLOBALS['db']->sql_numrows($result) == 0 )cpg_die(ERROR, $lang_db_input_php['unknown_album'], __FILE__, __LINE__);
		$row = $GLOBALS['db']->sql_fetchrow($result);
		$GLOBALS['db']->sql_free($result);
		$category = secure( $row['category'], 'strip', 1 );
	}

	// 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
	if (USER_ID && !defined('SILLY_SAFE_MODE')) {
		$filepath = $CONFIG['userpics'].(USER_ID+FIRST_USER_CAT);
	    // $dest_dir = $CONFIG['fullpath'].$filepath;
		$dest_dir = $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);
			$fp = @fopen($dest_dir.'/index.html', 'w');
 			fwrite($fp, ' ');
 			fclose($fp);

		}
		$dest_dir .= '/';
		$filepath .= '/';
	} else {
		$filepath = $CONFIG['userpics'];
	    $dest_dir = $filepath;
	}

$imageurl_name = secure( $_FILES['userpicture']['name'], '', 1, 'sec' );
$imageurl_temp = secure( $_FILES['userpicture']['tmp_name'], '', 1, 'sec' );
$imageurl_type = secure( $_FILES['userpicture']['type'], '', 1, 'sec' );

$ext           = substr($imageurl_name, strrpos($imageurl_name,'.'));
$ext           = strtolower($ext);

$imageurl_name = strtr($imageurl_name,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$imageurl_temp = strtr($imageurl_temp,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');

$imageurl_name = preg_replace('/([^a-z0-9]+)/i', '_', $imageurl_name);
$imageurl_temp = preg_replace('/([^a-z0-9]+)/i', '_', $imageurl_temp);

$limitedtype = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/tiff', 'image/tif');
if (!in_array($imageurl_type, $limitedtype)) {
	echo "<center>"._TYPE_NONALLOW."</center>";
	br('2');
	echo "<center>"._GOBACK."</center>";
	br('2');
	unset($imageurl_name);
	unset($_FILES['userpicture']['name']);
	unset($imageurl_temp);
	unset($_FILES['userpicture']['tmp_name']);
	incof();
	die();
}

$limitedext = array('.png', '.gif', '.jpg', '.jpeg', '.tiff', '.tif');
if (!in_array($ext,$limitedext)) {
	echo ""._EXT_NONALLOW."";
	incof();
	die();
}

$limitedext = array('.php', '.php3', '.php4', '.htm', '.html', '.js', '.exe', '.asp');
if (in_array($ext,$limitedext)) {
	echo ""._EXT_NONALLOW."";
	incof();
	die();
}

$renommage = @microtime();
$renommage = @md5($renommage);

$imageurl_name = $renommage."".$ext ;

	// 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 (get_magic_quotes_gpc()) $imageurl_name = stripslashes($imageurl_name);
	$picture_name = strtr($imageurl_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]=='' || !stristr($CONFIG['allowed_file_extensions'], $matches[2])) {
	    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];
	$picture_name = $imageurl_name ;
	while(@file_exists($dest_dir . $picture_name)){
		$picture_name = $matches[1] . '~'. $nr++ .'.' . $matches[2];
	}
	$uploaded_pic = $dest_dir.$picture_name;
if ( defined('USER_ALLOW') ) {
	// Move the picture into its final location
	//if(!move_uploaded_file($_FILES['userpicture']['tmp_name'], $uploaded_pic ))
	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
	$imginfo = @getimagesize($uploaded_pic);

	// Check that picture size (in pixels) is lower than the maximum allowed
	if (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__);

	// Check that picture file size is lower than the maximum allowed
	} elseif (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__);

	// getimagesize does not recognize the file as a picture
	} elseif ($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 && ($CONFIG['thumb_method'] == 'gd1' || $CONFIG['thumb_method'] == 'gd2')){
        } elseif ($imginfo[2] != GIS_JPG && $imginfo[2] != GIS_PNG && $CONFIG['GIF_support'] == 0) {
		@unlink($uploaded_pic);
		cpg_die(ERROR, $lang_errors['gd_file_type_err'], __FILE__, __LINE__, true);

	// Check image type is among those allowed for ImageMagick
	} elseif (!stristr($CONFIG['allowed_img_types'], $IMG_TYPES[$imginfo[2]]) && $CONFIG['thumb_method'] == 'im'){
		@unlink($uploaded_pic);
		cpg_die(ERROR, sprintf($lang_db_input_php['allowed_img_types'], $CONFIG['allowed_img_types']), __FILE__, __LINE__);
	} else {

// secure upload
if ( @ ! file_exists ( $filepath.'/.htaccess') ) {
	@ copy ( 'modules/Coppermine/securefiles/.htaccess', $filepath.'/.htaccess' );
}

if ( @ ! file_exists ( $filepath.'/index.html') ) {
	@ copy ( 'modules/Coppermine/securefiles/index.html', $filepath.'/index.html' );
}
// albums
if ( @ ! file_exists ( 'modules/Coppermine/albums/.htaccess') ) {
	@ copy ( 'modules/Coppermine/securefiles/.htaccess', 'modules/Coppermine/albums/.htaccess' );
}

if ( @ ! file_exists ( 'modules/Coppermine/albums/index.html') ) {
	@ copy ( 'modules/Coppermine/securefiles/index.html', 'modules/Coppermine/albums/index.html' );
}
// albums
if ( @ ! file_exists ( 'modules/Coppermine/albums/userpics/.htaccess') ) {
	@ copy ( 'modules/Coppermine/securefiles/.htaccess', 'modules/Coppermine/albums/userpics/.htaccess' );
}

if ( @ ! file_exists ( 'modules/Coppermine/albums/userpics/index.html') ) {
	@ copy ( 'modules/Coppermine/securefiles/index.html', 'modules/Coppermine/albums/userpics/index.html' );
}

		// Create thumbnail and internediate image and add the image into the DB
		$result = add_picture($album, $filepath, $picture_name, $title, $caption, $keywords, $user1, $user2, $user3, $user4, $category);
		if(!$result){
			@unlink($uploaded_pic);
			cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['err_insert_pic'], $uploaded_pic).'<br /><br />'.$ERROR, __FILE__, __LINE__, true);
		} elseif ($PIC_NEED_APPROVAL) {
			pageheader($lang_info);
			msg_box($lang_info, $lang_db_input_php['upload_success'], $lang_continue, 'modules.php?name=Coppermine');
			pagefooter();
			ob_end_flush();
		} else {
			$header_location = ( @preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE')) ) ? 'Refresh: 0; URL=' : 'Location: ';
			$redirect = "modules.php?name=Coppermine&op=displayimage&pos=".(-mysql_insert_id());
	   		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;

//
// Unknow event
//
	default:
	cpg_die(CRITICAL_ERROR, $lang_errors['param_missing'], __FILE__, __LINE__);
}
incof();
break;
}