<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
//
// Copyright (C) 2003 - 2007 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.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, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------



// MODULE HEADER INCLUSION -----------------------------------------------
// We include any header files for the modules
if (empty($suffix)) {
	$suffix = "core";
}

if (is_file("components/" . $suffix . "/inc/" . $suffix . "_participation.header.php")) {
	include_once("components/" . $suffix . "/inc/" . $suffix . "_participation.header.php");
}


//create URL
$url = "http://" . $_SERVER['HTTP_HOST'];
$url .= dirname ($_SERVER['PHP_SELF']);
//sometimes the server adds / as the last character - we need to check.
if (substr($url, -1, 1) != "/") {
	$url .= "/";
}

if (!empty($_POST['generate_invite'])) {
	$url .= "index.php?amn=core_register&mod=" . $module_id . "&invitee=" . $_SESSION['user_id'] . "&email=" . htmlspecialchars($_POST['to_email']) . "&language_id=" . $_SESSION['language_id'];
	
	$body->set("generated_invite", $url);
}
elseif (!empty($_POST['send_invite'])) {
	
	
	if (!empty($_POST['invited_identity_ids'])) {
		foreach($_POST['invited_identity_ids'] as $key => $i):
			// we insert into the participate table with a status of "invite"
			$output_identity = $user->selUserIdentity(null, $i);
			
			if (!empty($output_identity)) {
				$data['user_id'] = $output_identity['user_id'];
				$data['status_id'] = $core_config['participation']['status']['invite'];
				$data['identity_id'] = $i;
				$data['invitee_user_id'] = $_SESSION['user_id'];
				$data['participation_permission'] = $output_item['default_user_permission'];
				
				$participation->module_id = $module_id;
				$participation->item_id = $output_item['item_id'];
				$participation->insertParticipant($data);
				
				// append url to message (wiki formatted)
				$data['message_body'] = $_POST['message_body'] . "\n\n<a href=\"index.php?amn=core_participation&module_id=" . $module_id . "&item_id=" . $output_item['item_id'] . " \">" . $lang['txt_join'] . "</a>";
				
				// we send them a message	
				$data['from_identity_id'] = $output_participation['identity_id'];
				$data['to_identity_id'] = $output_identity['identity_id'];
				$data['message_subject'] = $lang['msg_subject'];
				
				$im->sendMessage($data);
			}
		endforeach;
				
		header("Location: " . $item_url . "&" . strip_tags(SID));
		exit;
	}


	if (isset($_POST['to_emails'])) {
		// get from email address
		$from_user = $user->selUser($_SESSION['user_id']);
		
		//setup email
		require_once('components/core/class/Mail/class.phpmailer.php');
		$mail = new PHPMailer($core_config['mail']);

		$mail->Subject = $lang['mail_subject'];

		if (!empty($from_user['user_email'])) {
			$mail->From = $from_user['user_email'];
			$mail->FromName = $from_user['user_firstname'];
		}
		else {
			$mail->AddReplyTo($core_config['mail']['no_reply_address'], $lang['subject_noreply']);
		}

		// we get the html template
		$html_tpl = & new Template($template_path_core); // inner template

		// get html language
		require_once($language_path_core . 'html_email.lang.php');
		$html_tpl->set('lang', $lang); // language

		
		foreach ($_POST['to_emails'] as $key => $i):
			
			if (!empty($i)) {
				// check email
				$to_email = trim($i);
				
				if(!preg_match('/^[-A-Za-z0-9_.]+[@][A-Za-z0-9_-]+([.][A-Za-z0-9_-]+)*[.][A-Za-z]{2,8}$/', $to_email)) {
					$GLOBALS['am_error_log'][] = array('error_email_invalid');
				}
				else {
					// we check if they are not in the database already
					$query = "
						SELECT DISTINCT user_id 
						FROM " . $db->prefix . "_user  
						WHERE 
						user_email=" . $db->qstr($to_email, get_magic_quotes_gpc())
					;
					
					$result = $db->Execute($query);
					
					if(isset($result->fields) && isset($result->fields['user_id'])) {
					
						// we check that they are not me
						if($result->fields['user_id'] == $_SESSION['user_id']) {
							$GLOBALS['am_error_log'][] = array('error_email_is_me'); //i've invited myself
						}
						
						if (empty($GLOBALS['am_error_log'])) {
							// we send them a message
							$user->identity_type = $core_config['user']['identity']['type']['registered'];
							$output_identity = $user->selUserIdentity($result->fields['user_id']);
							
							if (!empty($output_identity)) {
								$data['user_id'] = $output_identity['user_id'];
								$data['status_id'] = $core_config['participation']['status']['invite'];
								$data['identity_id'] = $output_identity['identity_id'];
								$data['invitee_user_id'] = $_SESSION['user_id'];
								$data['participation_permission'] = $output_item['default_user_permission'];
								
								$participation->module_id = $module_id;
								$participation->item_id = $output_item['item_id'];
								$participation->insertParticipant($data);
								
								// append url to message (html formatted)
								$data['message_body'] = $_POST['message_body'] . "<a href=\"index.php?amn=core_participation&module_id=" . $module_id . "&item_id=" . $output_item['item_id'] . " \">" .$lang['txt_join'] . "</a>";
								
								// we send them a message	
								$data['from_identity_id'] = $output_participation['identity_id'];
								$data['to_identity_id'] = $output_identity['identity_id'];
								$data['message_subject'] = $lang['msg_subject'];
								
								$im->sendMessage($data);
								
								header("Location: " . $item_url . "&" . strip_tags(SID));
								exit;
							}
						}
					}
					else { // we send the email
						// insert into invite table
						$rec = array();
						$rec['invited_email'] = $to_email;
						$rec['user_id'] = $_SESSION['user_id'];
						$rec['module_id'] = $module_id;
						$rec['item_id'] = $output_item['item_id'];
						$rec['invite_create_datetime'] = time();
						$rec['identity_id'] = $output_participation['identity_id'];
						$rec['invite_url'] = "core_participation&module_id=" . $module_id . "&item_id=" . $output_item['item_id'];
						$rec['default_status_id'] = $core_config['participation']['status']['invite'];
						$rec['default_participation_permission'] = $output_item['default_user_permission'];
						
						$table = $db->prefix . "_user_invite";
					
						$query = $db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
						$result = $db->Execute($query);
						
						
						$url .= "index.php?amn=core_register&mod=" . $module_id . "&invitee=" . $_SESSION['user_id'] . "&email=" . htmlspecialchars($to_email) . "&language_id=" . $_SESSION['language_id'];
						
						$url_html = "<a href=\"" . $url . "\">" .$lang['txt_join'] . "</a>";

						$_POST['message_body'] = stripslashes($_POST['message_body']);
						
						$message_body_email_html = $_POST['message_body'] . "\n\n" .$url_html;
						$message_body_email = $_POST['message_body'] . "\n\n" .$url;
						
						//send email to email address
						$mail->Subject = $lang['mail_subject'];
								
						// HTML-version of the mail
						$html_tpl->set('content', utf8_decode($message_body_email_html));
						$html_email = $html_tpl->fetch('html_email.tpl.php');
						
						$alt_body = strip_tags($message_body_email);
						$alt_body = utf8_decode($message_body_email);
						
						//send email
						$mail->Body = $html_email;
						$mail->AltBody = utf8_decode($alt_body);
						
						$mail->ClearAddresses();
						$mail->AddAddress($to_email, '');
						
						if(!$mail->Send()) {
							$GLOBALS['am_error_log'][] = array('mail_error', $mail->ErrorInfo);
						}
					}
				}
			}
		endforeach;
	}
}




// select relations not in this item
$query = "
	SELECT r.*, p.participation_create_datetime, i.identity_nic 
	FROM " . $db->prefix . "_user_identity i, " . $db->prefix . "_relation r
	LEFT JOIN " . $db->prefix . "_participation p ON r.identity_id_relation=p.identity_id AND p.module_id=" . $module_id . " AND p.item_id=" . $output_item['item_id'] . " 
	WHERE 
	r.identity_id_relation=i.identity_id AND 
	r.user_id=" . $_SESSION['user_id'] . "
	ORDER BY i.identity_nic"
;

$result = $db->Execute($query);

if (isset($result->fields)) {

	$output_respected_network = array();

	while(!$result->EOF) {
		array_push($output_respected_network, $result->fields);
		
		$result->moveNext();
	}
	$result->Close();
	
	if (!empty($output_respected_network)) {
		$body->set("respected_network", $output_respected_network);
	}

	// apply identities to participation
	
	
}

// update texts files
//$lang['txt_invite'] = str_replace("SYS_KEYWORD_SET_TITLE", $output_item['set_title'], $lang['txt_invite']);
$lang['txt_invite_message'] = str_replace("SYS_KEYWORD_SET_SYNOPSIS", $output_item['item_synopsis'], $lang['txt_invite_message']);



// we include all module files which have a function to obtain a single item
// module_id 1 will include a function called -selItemModule1
if (!empty($core_config['module'])) {
	foreach($core_config['module'] as $key => $i):
		$suffix = $core_config['module'][$key]['prefix'];

		if(is_file("components/" . $suffix . "/inc/" . $suffix . "_item_select.function.php")) {
			include_once("components/" . $suffix . "/inc/" . $suffix . "_item_select.function.php");
		}
	endforeach;
}


// get pending email invites
$query = "
	SELECT invited_email, module_id, item_id 
	FROM " . $db->prefix . "_user_invite  
	WHERE 
	user_id=" . $_SESSION['user_id'];
;
		
$result = $db->Execute($query);

if (isset($result->fields)) {

	$output_invite_emails = array();
	
	while(!$result->EOF) {
		$temp = $result->fields;

		$suffix = $core_config['module'][$temp['module_id']]['prefix'];
		$function_name = "selItemModule_" . $suffix;
	
		if (function_exists($function_name)) {
			$temp['item'] = $function_name($temp['item_id']);
		}
		
		array_push($output_invite_emails, $temp);
	
		$result->moveNext();
	}
	
	if (!empty($output_invite_emails)) {
		$body->set("invite_emails", $output_invite_emails);
	}
}


// get invited participants
$query = "
	SELECT p.identity_id, p.module_id, p.item_id, i.identity_nic 
	FROM " . $db->prefix . "_user_identity i, " . $db->prefix . "_participation p 
	WHERE 
	p.identity_id=i.identity_id AND 
	p.invitee_user_id=" . $_SESSION['user_id'] . " AND 
	p.status_id=" . $core_config['participation']['status']['invite'];
;
		
$result = $db->Execute($query);

if (isset($result->fields)) {

	$output_invite_identities = array();
	
	while(!$result->EOF) {
		$temp = $result->fields;

		$suffix = $core_config['module'][$temp['module_id']]['prefix'];
		$function_name = "selItemModule_" . $suffix;
	
		if (function_exists($function_name)) {
			$temp['item'] = $function_name($temp['item_id']);
		}
		
		array_push($output_invite_identities, $temp);
		
		$result->moveNext();
	}
	
	if (!empty($output_invite_identities)) {
		$body->set("invite_identities", $output_invite_identities);
	}
}

?>