Location: PHPKode > projects > ANJEL > com_anjel/admin.anjel.php
<?php
/* $Id: admin.anjel.php 44 2005-12-01 03:49:19Z schmalls $ */
/**
 * admin.anjel.php
 * 
 * <p>Main backend file for ANJEL. Includes options for Newsletter 
 * Management, Registered Subscribers, Unregsitered Subscribers, Mailing 
 * Management, Configuration, and Update.</p>
 * 
 * @package ANJEL
 * @subpackage backend
 * @copyright © 2004-2005 Schmalls / Joshua Thompson / All Rights Reserved
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * @author Schmalls / Joshua Thompson <hide@address.com>
 * @version 0.6.1
 * @since 0.4.3
 * @link http://www.schmalls.com
 */

 /**
  * Makes sure this is included by a parent file
  */
 defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');

 /**
  * Include required files
  */
 require_once ($mosConfig_absolute_path . '/administrator/components/com_anjel/admin.anjel.html.php' );
 require_once ($mosConfig_absolute_path . '/administrator/components/com_anjel/classes/class.mailing.php');
 require_once ($mosConfig_absolute_path . '/administrator/components/com_anjel/classes/class.subscribers.php');
 require_once ($mosConfig_absolute_path . '/administrator/components/com_anjel/configuration.php');
 require_once ($mosConfig_absolute_path . '/administrator/components/com_anjel/classes/class.phpmailer.php' );
 
 // compatibility functions
 /**
  * Replace file_get_contents()
  * 
  * @link        http://php.net/function.file_get_contents
  * @author      Aidan Lister <hide@address.com>
  * @version     $Revision: 1.25 $
  * @internal    resource_context is not supported
  * @since       PHP 5
  */
 if (!function_exists('file_get_contents')) {
	 function file_get_contents($filename, $incpath = false, $resource_context = null) {
		 if (false === $fh = fopen($filename, 'rb', $incpath)) {
			 user_error('file_get_contents() failed to open stream: No such file or directory', E_USER_WARNING);
			 return false;
		 } // end if
		 clearstatcache();
		 if ($fsize = @filesize($filename)) {
			 $data = fread($fh, $fsize);
		 } else {
			 $data = '';
			 while (!feof($fh)) {
				 $data .= fread($fh, 8192);
			 }
		 }
		 fclose($fh);
		 return $data;
	 }
 }
 if (!defined('FILE_USE_INCLUDE_PATH')) {
	 define('FILE_USE_INCLUDE_PATH', 1);
 }
 if (!defined('FILE_APPEND')) {
	 define('FILE_APPEND', 8);
 }
 /**
  * Replace file_put_contents()
  * 
  * @link        http://php.net/function.file_put_contents
  * @author      Aidan Lister <hide@address.com>
  * @version     $Revision: 1.25 $
  * @internal    resource_context is not supported
  * @since       PHP 5
  */
 if (!function_exists('file_put_contents')) {
	 function file_put_contents($filename, $content, $flags = null, $resource_context = null) {
		 // If $content is an array, convert it to a string
		 if (is_array($content)) {
			 $content = implode('', $content);
		 }
		 // If we don't have a string, throw an error
		 if (!is_scalar($content)) {
			 user_error('file_put_contents() The 2nd parameter should be either a string or an array', E_USER_WARNING);
			 return false;
		 }
		 // Get the length of data to write
		 $length = strlen($content);
		 // Check what mode we are using
		 $mode = ($flags & FILE_APPEND) ? 'a' : 'w';
		 // Check if we're using the include path
		 $use_inc_path = ($flags & FILE_USE_INCLUDE_PATH) ? true : false;
		 // Open the file for writing
		 if (($fh = @fopen($filename, $mode, $use_inc_path)) === false) {
			 user_error('file_put_contents() failed to open stream: Permission denied', E_USER_WARNING);
			 return false;
		 }
		 // Write to the file
		 $bytes = 0;
		 if (($bytes = @fwrite($fh, $content)) === false) {
			 $errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s', $length, $filename);
			 user_error($errormsg, E_USER_WARNING);
			 return false;
		 }
		 // Close the handle
		 @fclose($fh);
		 // Check all the data was written
		 if ($bytes != $length) {
			 $errormsg = sprintf('file_put_contents() Only %d of %d bytes written, possibly out of free disk space.', $bytes, $length);
			 user_error($errormsg, E_USER_WARNING);
			 return false;
		 }
		 // Return length
		 return $bytes;
	 }
 }
 
 // global classes
 $mailing = new mailing();
 $subscribers = new subscribers();
 
 // parameters
 $listid = mosGetParam($_REQUEST, 'listid', 0);
 $userid = mosGetParam($_REQUEST, 'userid', '');
 $action = mosGetParam($_REQUEST, 'act', '');
 $task = mosGetParam($_REQUEST, 'task', '');
 $letterid = mosGetParam($_REQUEST, 'letterid', '');
 $type = mosGetParam($_REQUEST, 'type', '');
 $test = mosGetParam($_REQUEST, 'test', '');
 $message = mosGetParam($_REQUEST, 'message', '');
 /**
  * Subscribers to modify
  * 
  * @global array $cid
  */
 $cid = mosGetParam($_REQUEST, 'cid', array());
 // make sure it is an array
 if (!is_array( $cid )) {
	 $cid = array(0);
 } // end if
 
 // include language file, or default to english
 if (file_exists ($mosConfig_absolute_path . '/components/com_anjel/languages/' . $mosConfig_lang . '.php')) {
	include_once ($mosConfig_absolute_path . '/components/com_anjel/languages/' . $mosConfig_lang . '.php');
 } else {
	include_once ($mosConfig_absolute_path . '/components/com_anjel/languages/english.php');
 } // end if
 
 // add any new registered users who are not in the anjel table
 $query = 'SELECT M.* FROM `#__users` AS M LEFT JOIN `#__anjel_subscribers` AS N ON M.id = N.subscriber_id WHERE N.subscriber_id IS NULL';
 $database->setQuery($query);
 $rows = $database->loadObjectList();
 $error = $database->getErrorMsg();
 // quit on error
 if (!empty($error)) {
	 echo '<p><b>Error (admin.anjel.php-> line ' . __LINE__ . '):</b> Error getting newly added Joomla users. Database error: <br />' . $error . '</p>';
 } else {
	 foreach ($rows as $row) {
		 $query = 'INSERT INTO `#__anjel_subscribers` (`subscriber_id`) VALUES (' . $row->id . ')';
		 $database->setQuery($query);
		 $database->query();
		 $error .= $database->getErrorMsg();
	 } // end foreach
	 // output error messages
	 if (!empty($error)) {
		 echo '<p><b>Error (admin.anjel.php-> line ' . __LINE__ . '):</b> Error adding new users to subscribers table. Database error: <br />' . $error . '</p>';
	 } // end if
 } // end if
 
 // delete any deleted registered users who are still in the anjel table
 $query = 'SELECT M.* FROM `#__anjel_subscribers` AS M LEFT JOIN `#__users` AS N ON N.id = M.subscriber_id WHERE N.id IS NULL';
 $database->setQuery($query);
 $rows = $database->loadObjectList();
 $error = $database->getErrorMsg();
 // quit on error
 if (!empty($error)) {
	 echo '<p><b>Error (admin.anjel.php-> line ' . __LINE__ . '):</b> Error getting newly added Joomla users. Database error: <br />' . $error . '</p>';
 } else {
	 foreach ($rows as $row) {
		 $query = 'DELETE FROM `#__anjel_subscribers` WHERE `subscriber_id` = ' . $row->subscriber_id;
		 $database->setQuery($query);
		 $database->query();
		 $error .= $database->getErrorMsg();
	 } // end foreach
	 // output error messages
	 if (!empty($error)) {
		 echo '<p><b>Error (admin.anjel.php-> line ' . __LINE__ . '):</b> Error adding new users to subscribers table. Database error: <br />' . $error . '</p>';
	 } // end if
 } // end if
 
 // show the logo
 echo '<table width="100%"><tr>';
 if ($action != '') {
	 echo '<td align="left"><img src="components/com_anjel/images/' . $action . '.png" alt="' . $action . '" border="0" align="left" /></td>';
 } // end if
 echo '<td align="right"><a href="http://anjel.schmalls.com" target="_blank"><img src="components/com_anjel/anjel.png" alt="ANJEL Logo" border="0" align="right" /></a></td></tr></table>';
 
 // switch by action
 switch ($action) {
	case ('registered') :
		subscribers('subscribers', 'subscriber');
		break;
	case ('unregistered') :
		subscribers('unregistered', 'unregistered');
		break;
	case ('configuration') :
		configuration();
		break;
	case ('newsletter') :
		newsletter();
		break;
	case ('mailing') :
		mailing();
		break;
	case ('statistics') :
		statistics();
		break;
	case ('update') :
		update();
		break;
	default :
		backend_html :: showMain();	
		break;
 } // end switch
 
 /**
  * Shows subscriber information and options
  * 
  * <p>For registered subscribers it allows you to view and update the 
  * subscriptions. For unregistered subscribers it allows you to view, add, 
  * delete, update, import, and export subscriptions.</p>
  * 
  * @version 0.6.1
  * @since 0.4.3
  * @param string $tablesuffix the suffix for the table
  * @param string $idprefix the prefix for the id
  * @global string the action to perform
  * @global string the task to perform
  * @global class access to the database
  * @global array which subscribers to work with
  * @global string the user's browser agent
  * @global string filesystem path to main site directory
  * @global int the list to work with
  * @global array ANJEL configuration options
  * @global class access to mailing functions
  * @global class access to subscriber functions
  * @uses backend_html::newSubscriber()
  * @uses mailing::send()
  * @uses backend_html::export()
  * @uses backend_html::import()
  * @uses getSubscribers()
  * @uses backend_html::showSubscribers()
  * @uses subscribers::validEmail()
  * @return boolean to tell whether it was successful
  */
 function subscribers($tablesuffix, $idprefix) {
	 global $action, $task, $database, $cid, $HTTP_USER_AGENT, $mosConfig_absolute_path, $listid, $newsletterConfig, $mailing, $subscribers;
	 
	 // switch by task
	 $doShowSubscribers = true;
	 switch ($task) {
		// show new subscriber options
		case ('new') :
			// make sure this is an unregistered user addition
			if ($action != 'unregistered') {
				echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Not able to add users of type other than unregistered.</p>';
			} else {
				// get newsletter ids
				$query = 'SELECT * FROM `#__anjel_letters`';
				$database->setQuery($query);
				$letters = $database->loadObjectList();
				$error = $database->getErrorMsg();
				// quit on error
				if (!empty($error)) {
					echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error getting newsletters from database. Database error: <br />' . $error . '</p>';
					return false;
				} else {
				 	$doShowSubscribers = false;
					backend_html :: newSubscriber($action, $letters);
				} // end if
			} // end if
			break;
		// add a new subscriber
		case ('doNew') :
			// make sure this is an unregistered subscriber addition
			if ($action != 'unregistered') {
				echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Not able to add users of type other than unregistered.</p>';
				return false;
			} else {
				// get email address
				$email = mosGetParam($_REQUEST, 'email', '');
				// make sure email address was received
				if ($email == '') {
					echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Email address not received.</p>';
					return false;
				} else {
					// check if email is valid
					if (!$subscribers->validEmail($email)) {
						echo '<p>' . _EMAILINVALID . '</p>';
						return false;
					} else {
						// check if email already in database
						$query = 'SELECT * FROM `#__anjel_unregistered` WHERE `email` = \'' . $email . '\'';
						$database->setQuery($query);
						$database->loadObject($check);
						// quit if address in database
						if ((!empty($check)) && ($check->blacklist == 0)) {
							echo '<p>' . _EMAIL_ALREADY_REGISTERED . '</p>';
							return false;	
						} else {
							// add user to database
							if (!empty($check)) {
								$query = 'UPDATE `#__anjel_unregistered` SET `blacklist` = 0 WHERE `email` = \'' . $email . '\'';
							} else {
								$query = 'INSERT INTO `#__anjel_unregistered` (`email`) VALUES (\'' . $email . '\')';
							} // end if
							$database->setQuery($query);
							$database->query();
							$error = $database->getErrorMsg();
							// quit on error
							if (!empty($error)) {
								echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Could not insert new user into database. Database error: <br />' . $error . '</p>';
								return false;
							} else {
								// get user's new id
								if (!empty($check)) {
									$userid = $check->unregistered_id;
								} else {
									$query = 'SELECT LAST_INSERT_ID()';
									$database->setQuery($query);
									$userid = $database->loadResult();
								} // end if
								// get letters
								$query = 'SELECT * FROM `#__anjel_letters`';
								$database->setQuery($query);
								$letters = $database->loadObjectList();
								$error = $database->getErrorMsg();
								// quit on error
								if (!empty($error)) {
									echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Could not get current subscriptions. Database error: <br />' . $error . '</p>';
									return false; 
								} else {
									// update subscriptions
									foreach ($letters as $letter) {
										$newValue = mosGetParam($_REQUEST, 'list_'.$letter->id, 0);
										$query = 'UPDATE `#__anjel_unregistered` SET `list_' . $letter->id . '` = ' . $newValue . ' WHERE `unregistered_id` = ' . $userid;
										$database->setQuery($query);
										$database->query();
										$error .= $database->getErrorMsg();
									} // end foreach
									// quit on error
									if (!empty($error)) {
										echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Could not update subscriptions. Database error: <br />' . $error . '</p>';
										return false;
									} else {
										// update name, email, subscribe_date, and receive html
										$newName = mosGetParam($_REQUEST, 'name', '');
										$newEmail = mosGetParam($_REQUEST, 'email', '');
										$newReceiveHtml = mosGetParam($_REQUEST, 'receivehtml', 0);
										$newConfirmed = mosGetParam($_REQUEST, 'confirmed', ($newsletterConfig['require_confirmation'] ? 0 : 1));
										$query = 'UPDATE `#__anjel_unregistered` SET `name` = \'' . $newName . '\', `email` = \'' . $newEmail . '\', `receive_html` = ' . $newReceiveHtml . ', `confirmed` = ' . $newConfirmed . ', `subscribe_date` = NOW() WHERE `unregistered_id` = ' . $userid;
										$database->setQuery($query);
										$database->query();
										$error = $database->getErrorMsg();
										// quit on error
										if (!empty($error)) {
											echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Could not update name, email, and/or receive html. Database error: <br />' . $error . '</p>';
											return false;				 
										} else {
											echo '<p>' . _UPDATED_SUCCESSFULLY . '</p>';
											if (($newConfirmed == 0) && ($newsletterConfig['require_confirmation'] != 0)) {
												// create content
												$content = $newsletterConfig['confirm_text'];
												if (!get_magic_quotes_gpc()) {
													$content = addslashes($content);
												} // end if
												// create receivers array
												$receivers = array('subscribe');
												$receivers[1]->id = $userid;
												$receivers[1]->email = $newEmail;
												$receivers[1]->name = $newName;
												$receivers[1]->receive_html = $newReceiveHtml;
												$receivers[1]->registered = 0;
												// send the confirm message
												$mailing->send(_WELCOME_SUBJECT, $content, $content, $receivers, $newsletterConfig['confirm_fromname'], $newsletterConfig['confirm_fromemail'], $newsletterConfig['confirm_return'], $newsletterConfig['confirm_html']);
											} // end if
										} // end if
									} // end if
								} // end if
							} // end if
						} // end if
					} // end if
				} // end if
			} // end if
			break;
		// delete subscriber(s)
		case ('delete') :
			// make sure this is an unregistered subscriber deletion
			if ($action != 'unregistered') {
				echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Not able to delete users of type other than unregistered.</p>';
				return false;
			} else {
				// make sure there are users to delete
				if (!is_array( $cid ) || count( $cid ) < 1) {
					echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
					return false;
				} else {
					// blacklist each subscriber
					$error = '';
					foreach ($cid as $id) {
						$query = 'UPDATE `#__anjel_unregistered` SET `blacklist` = 2 WHERE `unregistered_id` = \'' . $id . '\'';
						$database->setQuery($query);
						$database->query();
						$error .= $database->getErrorMsg();
					} // end foreach
					// quit on error
					if (!empty($error)) {
						echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error deleting from database. Database error: <br />' . $error . '</p>';
						return false;
					} else {
						echo _SUBSCRIBER_DELETED;
					} // end if
				} // end if
			} // end if
			break;
		// update subscriber(s) information
		case ('update') :
			// make sure there are users to update
			if (!is_array( $cid ) || count( $cid ) < 1) {
				echo "<script> alert('Select an item to update'); window.history.go(-1);</script>\n";
				return false;
			} else {
				// update each subscriber
				foreach ($cid as $id) {
					// get user changes
					$changes = mosGetParam($_REQUEST, 'subscriber_'.$id, array(0));
					// update receive html and confirmed
					if (!isset($changes['receive_html'])) {
						$changes['receive_html'] = 0;
					} // end if
					if (!isset($changes['confirmed'])) {
						$changes['confirmed'] = 0;
					} // end if
					$query = 'UPDATE 
								`#__anjel_' . $tablesuffix . '` 
								SET `receive_html` = ' . $changes['receive_html'] . ' , 
								`confirmed` = ' . $changes['confirmed'] . ' 
								WHERE `' . $idprefix . '_id` = ' . $id;
					$database->setQuery($query);
					$database->query();
					$error = $database->getErrorMsg();
					// quit on error
					if (!empty($error)) {
						echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error updating recevie html and confirmed. Database error: <br />' . $error . '</p>';
						return false;
					} else {
						// get newsletter ids
						$query = 'SELECT * FROM `#__anjel_letters`';
						$database->setQuery($query);
						$letters = $database->loadObjectList();
						$error = $database->getErrorMsg();
						// quit on error
						if (!empty($error)) {
							echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error getting newsletters from database. Database error: <br />' . $error . '</p>';
							return false;
						} else {
							// update each newsletter
							foreach ($letters as $letter) {
								if (!isset($changes[($letter->id)])) {
									$changes[($letter->id)] = 0;
								} // end if
								$query = 'UPDATE
											`#__anjel_' . $tablesuffix . '` 
											SET `list_' . $letter->id . '` = ' . $changes[($letter->id)] . ' 
											WHERE `' . $idprefix . '_id` = ' . $id;
								$database->setQuery($query);
								$database->query();
								$error .= $database->getErrorMsg();
							} // end foreach
							// quit on error
							if (!empty($error)) {
								echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error updating subscriber information in database. Database error: <br />' . $error . '</p>';
								return false;
							} // end if
						} // end if
					} // end if
				} // end foreach
			} // end if
			echo '<p>' . _UPDATED_SUCCESSFULLY . '</p>';
			break;
		// show export options
		case ('export') :
			$doShowSubscribers = false;
			backend_html :: export($action, $listid);
			break;
		// do the export
		case ('doExport') :
			if ($action != 'unregistered') {
				echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Can only export unregistered subscribers.</p>';
				return false;
			} else {
				$doShowSubscribers = false;
				// get browser type
				if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $HTTP_USER_AGENT)) {
					$UserBrowser = 'Opera';
				} elseif (ereg('MSIE ([0-9].[0-9]{1,2})', $HTTP_USER_AGENT)) {
					$UserBrowser = 'IE';
				} else {
					$UserBrowser = '';
				} // end if
				
				// set mime type and filename
				$mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
				$filename = "subscribers_" . date('d-m-Y');
		
				ob_end_clean();
				ob_start();
				
				// get unregistered subscribers from database
				$query = 'SELECT M.name AS name, M.email AS email, M.receive_html AS receive_html, M.confirmed AS confirmed FROM `#__anjel_unregistered` AS M';
				$database->setQuery($query);
				$subscribers = $database->loadObjectList();
				$error = $database->getErrorMsg();
				// quit on error
				if (!empty($error)) {
					echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error getting subscribers from database. Database error: <br />' . $error . '</p>';
					return false;
				} else {
					// add each subscriber line to the output string
					$export = '';
					foreach ($subscribers AS $subscriber) {
						// check for slashes
						if(get_magic_quotes_runtime()) {
							$subscriber->name = stripslashes($subscriber->name);
							$subscriber->email = stripslashes($subscriber->email);
						} // end if
						$export .= $subscriber->name . ',' . $subscriber->email . ',' . $subscriber->receive_html . ',' . $subscriber->confirmed . "\r\n";
					} // end foreach
					
					// set header options
					header('Content-Type: ' . $mime_type);
					header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
			
					if ($UserBrowser == 'IE') {
						header('Content-Disposition: inline; filename="' . $filename . '.csv"');
						header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
						header('Pragma: public');
					} else {
						header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
						header('Pragma: no-cache');
					}
					// print the output file
					print $export;
					exit();
				} // end if
			} // end if
			break;
		// show import options
		case ('import') :
			$doShowSubscribers = false;
			backend_html :: import($action, $listid);
			break;
		// do the import
		case ('doImport') :
			// make sure this is an unregistered subscriber import
			if ($action != 'unregistered') {
				echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Can only import unregistered subscribers.</p>';
				return false;
			} else {
				// get path and filename and move it to the newsletter directory
				$path = $mosConfig_absolute_path . '/images/stories/newsletter/';
				$filename = $_FILES['importfile']['name'];
				move_uploaded_file($_FILES['importfile']['tmp_name'], $path . $filename);
				// make sure the directory is writeable
				if (is_writable($path)) {
					// get the file contents
					$import = file_get_contents($path . $filename);
					// break into an array of the rows
					$array = explode("\n", $import);
					// make sure file wasn't empty
					if (sizeof($array) > 0) {
						// go through each row
						$error = '';
						foreach ($array AS $row) {
							// make sure row wasn't empty
							if ($row == '' || $row == ' ') {
								continue;
							} // end if
							// split the row by comma
							$values = explode(',', $row);
							// check if email is valid
							if (!$subscribers->validEmail($values[1])) {
								echo '<p>' . $values[1] . ': ' . _EMAILINVALID . '</p>';
							} else {
								// put it in the database
								$query = 'REPLACE INTO `#__anjel_unregistered` (`name`, `email`, `receive_html`, `confirmed`, `subscribe_date`) VALUES(\'' . addslashes($values[0]) . '\', \'' . addslashes($values[1]) . '\', \'' . intval($values[2]) . '\', \'' . intval($values[3]) . '\', NOW())';
								$database->setQuery($query);
								$database->query();
								$error .= $database->getErrorMsg();
							} // end if
						} // end foreach
						// quit on error
						if (!empty($error)) {
							echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error adding subscribers to database. Database error: <br />' . $error . '</p>';
							return false;
						} else {
							echo '<p>' . _IMPORTFINISHED . '.</p>';
						} // end if
					} // end if
					// make sure the file is deleted
					if (!unlink($path . $filename)) {
						echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b>' . _DELETIONOFFILE . ' ' . $path . $filename . ' ' . _MANUALLYDELETE . '.</p>';
					} // end if
				} else {
					echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> ' . _CANNOTWRITEDIR . ' ' . $path . '</p>';
					return false;
				} // end if
			} // end if
			break;
		// subscribe all
		case ('subscribeAll') :
			$query = 'UPDATE `#__anjel_' . $tablesuffix . '` SET `list_' . $listid . '` = 1 WHERE `list_' . $listid . '` != 2 AND `list_' . $listid . '` != 3';
			$database->setQuery($query);
			$database->query();
			$error = $database->getErrorMsg();
			// quit on error
			if (!empty($error)) {
				echo '<p><b>Error (admin.anjel.php->subscribers() line ' .__LINE__ . '):</b> Error subscribing all to the list. Database error: <br />' . $error . '</p>';
				return false;
			} else {
				$listid = 0;
			} // end if
			break;
		// unsubscribe all
		case ('unsubscribeAll') :
		 	$query = 'UPDATE `#__anjel_' . $tablesuffix . '` SET `list_' . $listid . '` = 0 WHERE `list_' . $listid . '` != 2 AND `list_' . $listid . '` != 3';
			$database->setQuery($query);
			$database->query();
			$error = $database->getErrorMsg();
			// quit on error
			if (!empty($error)) {
				echo '<p><b>Error (admin.anjel.php->subscribers() line ' .__LINE__ . '):</b> Error unsubscribing all from the list. Database error: <br />' . $error . '</p>';
				return false;
			} else {
				$listid = 0;
			} // end if
			break;
		case ('cancel') :
			// check for list id
			if ($listid != 0) {
				// change to 0
				$listid = 0;
			} else {
				// redirect to main page
				mosRedirect('index2.php?option=com_anjel');
			} // end if
			break;
	 } // end switch
	 
	 // check whether to show the subscribers
	 if ($doShowSubscribers) {
		 // get the start, limit, subscribers, and total
		 $start = mosGetParam($_REQUEST, 'start', 0);
		 $limit = mosGetParam($_REQUEST, 'limit', 10);
		 $emailsearch = mosGetParam($_REQUEST, 'emailsearch', '');
		 $subscribers = getSubscribers($start, $limit, $emailsearch, $total);
		 // quit on error
		 if ($subscribers == false) {
			 echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error getting subscribers.</p>';
			 return false;
		 } else {
			 // check if this is for a specific newsletter
			 if ($listid != 0) {
				$showAdmin = true;			 
			 } else {
				$showAdmin = false;
			 } // end if
			 // get letters from database
			 $query = 'SELECT `id` as id, `list_name` as list_name FROM `#__anjel_letters`';
			 $database->setQuery($query);
			 $letters = $database->loadObjectList();
			 $error = $database->getErrorMsg();
			 // quit on error
			 if (!empty($error)) {
				 echo '<p><b>Error (admin.anjel.php->subscribers() line ' . __LINE__ . '):</b> Error getting newsletters from database. Database error: <br />' . $error . '</p>';
				 return false;
			 } else {
				 // show subscribers
				 backend_html :: showSubscribers($subscribers, $letters, $action, $listid, $start, $limit, $total, $showAdmin, $listid, $emailsearch);
				 return true;
			 } // end if
		 } // end if
	 } else {
		 return true;
	 } // end if
 } // end function
 
 /**
  * Shows configuration options
  * 
  * <p>Displays a list of the configuration options, or saves the current configuration.</p>
  * 
  * @version 0.6.1
  * @since 0.4.3
  * @param array $config the configuration options
  * @global string the task to perform
  * @global array ANJEL configuration options
  * @global string the filesystem path to the main site directory
  * @uses backend_html::showConfigurationEdit()
  * @return boolean whether it was successful or not
  */
 function configuration($config = array(), $redirect = true) {
	 global $task, $newsletterConfig, $mosConfig_absolute_path;
	 
	 // switch by task
	 switch ($task) {
		 case ('save') :
			// check if log file should be erased
			$clear_log = mosGetParam($_REQUEST, 'clear_log', 0);
			if ($clear_log != 0) {
				unlink($newsletterConfig['save_log_file']);
			} // end if
		 	// get configuration file and put into a string
		 	$configurationFile = file_get_contents($mosConfig_absolute_path . '/administrator/components/com_anjel/configuration.php');
			// quit on error
			if ($configurationFile === false) {
				echo '<p><b>Error (admin.anjel.php->configuration() line ' . __LINE__ . '):</b> Error opening configuration file for reading.</p>';
				return false;
			} else {
				// go through each of the configuration options and update them
				if (empty($config)) {
					$config = $_REQUEST['config'];
				} // end if
				foreach ($config as $key => $value) {
					// check if magic quotes is enabled
					if (get_magic_quotes_gpc()) {
						$value = stripslashes($value);
					} // end if
					$value = str_replace('\'', '\\\'', $value);
					//$configurationFile = preg_replace('/\$newsletterConfig\[\'' . str_replace('\\\'', '', $key) . '\'] = \'[^\']*\';/','$newsletterConfig[\'' . str_replace('\\\'', '', $key) . '\'] = \'' . $value . '\';', $configurationFile);
					$configurationFile = preg_replace('/\$newsletterConfig\[' . $key . '] = \'[^\']*\';/', '$newsletterConfig[' . stripslashes($key) . '] = \'' . $value . '\';', $configurationFile);
				} // end foreach
				// write the file
				$check = file_put_contents($mosConfig_absolute_path . '/administrator/components/com_anjel/configuration.php', $configurationFile);
				// quit on error
				if ($check == 0) {
					echo '<p><b>Error (admin.anjel.php->configuration() line ' . __LINE__ . '):</b> Error opening configuration file for writing.</p>';
					return false;
				} else {
					if ($redirect) {
						mosRedirect('index2.php?option=com_anjel', _CONFIGUPDATED);
					} // end if
				} // end if
			} // end if
		 	break;
		 case ('cancel') :
			// redirect to main page
			mosRedirect('index2.php?option=com_anjel');
			break;		 
		 default :
		 	backend_html :: showConfigurationEdit($newsletterConfig);
		 	break;
	 } // end switch
	 return true;
 } // end function
 
 /**
  * Shows newsletter options
  * 
  * <p>Newsletter management area which allows you to create, edit, and 
  * delete newsletters.</p>
  * 
  * @version 0.5.1
  * @since 0.4.3
  * @global string the action to perform
  * @global string the task to perform
  * @global int the list to work with
  * @global class access to the database
  * @uses backend_html::showLetterEdit()
  * @uses updateLetter()
  * @uses backend_html::showLetters()
  * @return boolean whether it was successful or not
  */ 
 function newsletter() {
	global $action, $task, $listid, $database;
	
	// switch by task
	$showLetters = true;
	switch ($task) {
		// new newsletter
		case ('new') :
			$showLetters = false;
			$letter->id = 0;
			$letter->html = 1;
			$letter->new_letter = 1;
			$letter->list_name = '';
			$letter->list_desc = '';
			$letter->sendername = '';
			$letter->senderemail = '';
			$letter->bounceadres = '';
			$letter->layout = '[CONTENT]';
			$letter->subscribemessage = '';
			$letter->unsubscribemessage = '';
			$letter->hidden = 0;
			$letter->auto_add = 0;
			backend_html :: showLetterEdit($letter);
			break;
		// add newsletter
		case ('doNew') :
			// add to letters
			$listname = mosGetParam($_REQUEST, 'list_name', '');
			$query = 'INSERT INTO `#__anjel_letters` (`list_name`) VALUES (\'' . $listname . '\')';
			$database->setQuery($query);
			$database->query();
			$error = $database->getErrorMsg();
			// quit on error
			if (!empty($error)) {
				echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error adding newsletter to database. Database error: <br />' . $error . '</p>';
				return false;
			} else {
				// get listid
				$query = 'SELECT LAST_INSERT_ID()';
				$database->setQuery($query);
				$listid = $database->loadRow();
				$listid = $listid[0];
				$error = $database->getErrorMsg();
				// quit on error
				if (!empty($error)) {
					echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error getting new list id. Database error: <br />' . $error . '</p>';
					return false;
				} else {
					// add to registered and unregistered subscriber tables
					$auto_add = mosGetParam($_REQUEST, 'auto_add', 0);
					$query = 'ALTER TABLE `#__anjel_subscribers` ADD COLUMN (`list_' . $listid . '` tinyint(1) NOT NULL default \'' . $auto_add . '\')';
					$database->setQuery($query);
					$database->query();
					$error = $database->getErrorMsg();
					$query = 'ALTER TABLE `#__anjel_unregistered` ADD COLUMN (`list_' . $listid . '` tinyint(1) NOT NULL default \'' . $auto_add . '\')';
					$database->setQuery($query);
					$database->query();
					$error .= $database->getErrorMsg();
					// quit on error
					if (!empty($error)) {
						echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error adding newsletter to subscriber tables. Database error: <br />' . $error . '</p>';
						return false;
					} else {
						// quit on error
						if(!(updateLetter())) {
							echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error adding newsletter options.</p>';
							return false;
						} else {
							echo '<p>' . _NEWSLETTERADDED . '</p>';
						} // end if
					} // end if
				} // end if
			} // end if
			break;
		// edit newsletter
		case ('edit') :
			// make sure there is a newsletter to edit
			if ($listid == 0) {
				echo "<script> alert('Select a newsletter to edit.'); window.history.go(-1);</script>\n";
				return false;
			} else {
				$showLetters = false;
				// get the letter
				$query = 'SELECT M.* FROM `#__anjel_letters` as M WHERE `id` = ' . $listid;
				$database->setQuery($query);
				$database->loadObject($letter);
				$error = $database->getErrorMsg();
				$query = 'DESCRIBE `#__anjel_subscribers` `list_' . $listid . '`';
				$database->setQuery($query);
				$database->loadObject($letter_auto_add);
				$error .= $database->getErrorMsg();
				// quit on error
				if (!empty($error)) {
					echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error getting the newsletter. Database error: <br />' . $error . '</p>';
					return false;
				} else {
					$letter->auto_add = $letter_auto_add->Default;
					backend_html :: showLetterEdit($letter);
				} // end if
			} // end if
			break;
		// update the newsletter
		case ('update') :
			// quit on error
			if(!(updateLetter())) {
				echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error updating letter options.</p>';
				return false;
			} else {
				echo '<p>' . _NEWSLETTERUPDATED . '</p>';
			} // end if
			break;
		// delete the newsletter
		case ('delete') :
			// make sure there is a newsletter to delete
			if ($listid == 0) {
				echo "<script> alert('Select a newsletter to delete.'); window.history.go(-1);</script>\n";
				return false;
			} else {
				// delete from letters
				$query = 'DELETE FROM `#__anjel_letters` WHERE `id` = ' . $listid;
				$database->setQuery($query);
				$database->query();
				$error = $database->getErrorMsg();
				// quit on error
				if (!empty($error)) {
					echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error deleting newsletter. Database error: <br />' . $error . '</p>';
					return false;
				} else {
					// delete from subscriber tables
					$query = 'ALTER TABLE `#__anjel_subscribers` DROP COLUMN `list_' . $listid . '`';
					$database->setQuery($query);
					$database->query();
					$error = $database->getErrorMsg();
					$query = 'ALTER TABLE `#__anjel_unregistered` DROP COLUMN `list_' . $listid . '`';
					$database->setQuery($query);
					$database->query();
					$error .= $database->getErrorMsg();
					// quit on error
					if (!empty($error)) {
						echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error deleting columns from subscriber tables. Database error: <br />' . $error . '</p>';
						return false;
					} else {
						echo '<p>' . _NEWSLETTERDELETED . '</p>';
					} // end if
				} // end if
			} // end if
			break;
		case ('cancel') :
			// redirect to main page
			mosRedirect('index2.php?option=com_anjel');
			break;
	} // end switch
	
	// show newsletters if enabled
	if ($showLetters) {
		// get letters
		$query = 'SELECT * FROM `#__anjel_letters`';
		$database->setQuery($query);
		$letters = $database->loadObjectList();
		$error = $database->getErrorMsg();
		// quit on error
		if (!empty($error)) {
			echo '<p><b>Error (admin.anjel.php->newsletter() line ' . __LINE__ . '):</b> Error getting newsletters. Database error: <br />' . $error . '</p>';
			return false;
		} else {
			backend_html :: showLetters($letters, $action, 'edit');
			return true;
		} // end if
	} else {
		return true;
	} // end if
 } // end function
 
 /**
  * Shows mailing options
  * 
  * <p>Displays the mailing management area which allows you to edit, 
  * publish, save, and preview a mailing. You can also view and delete 
  * from the archive.</p>
  * 
  * @version 0.6.1
  * @since 0.4.3
  * @global string the action to perform
  * @global string the task to perform
  * @global int the list to work with
  * @global class access to the database
  * @global class access to mailing functions
  * @global string url to main site directory
  * @global object the mambots object
  * @uses backend_html::showMailingEdit()
  * @uses mailing::publish()
  * @uses backend_html::previewMailing()
  * @uses mailing::save()
  * @uses backend_html::viewArchive()
  * @uses backend_html::showMailings()
  * @uses backend_html::showLetters()
  * @return boolean whether it was successful or not
  */
 function mailing() {
	global $action, $task, $listid, $database, $mailing, $mosConfig_live_site, $_MAMBOTS;
	
	// get the senddate
	$senddate = mosGetParam($_REQUEST, 'senddate', 0);
	// switch by task
	$showLetters = true;
	switch ($task) {
		// edit the current mailing or create a new one
		case ('edit') :
			// don't show letters
			$showLetters = false;
			// get letter information
			$letter = $mailing->getLetterData($listid, $senddate, $new);
			// get layout information
			$layout = $mailing->getListData($listid);
			// check if mailing is new
			if($new == 1) {
				$letter->fromname = $layout->sendername;
				$letter->fromemail = $layout->senderemail;
				$letter->frombounce = $layout->bounceadres;
			} // end if
			backend_html :: showMailingEdit($letter, $layout, $new, $action, $listid);
			break;
		// create a new letter
		case ('new') :
			mosRedirect('index2.php?option=com_anjel&act=mailing&task=edit&listid=' . $listid);
		// publish a letter
		case ('publish') :
			$mailing->publish($listid);
			// don't show letters
			$showLetters = false;
			break;
		// preview a letter
		case ('preview') :
			// check if preview needs to be sent or if the preview options need to be displayed
			$emailaddress = mosGetParam($_REQUEST, 'emailaddress', '');
			if(!empty($emailaddress)){
				$check = $mailing->publish($listid, true);
				// see if mailing was sent successfully
				if ($check) {
					$returnMessage = _MESSAGESENTSUCCESSFULLY;
				} else {
					$returnMessage = _MESSAGENOT;
				} // end if
				// redirect
				mosRedirect( 'index2.php?option=com_anjel&act=mailing&task=show&listid=' . $listid . '&message=' . $returnMessage, $returnMessage);
				$showLetters = false;
			} else {
				$mailing->save($senddate);
				backend_html :: previewMailing($listid, $senddate);
				// don't show letters
				$showLetters = false;
			} // end if
			break;
		// save a letter
		case ('save') :
			if ($mailing->save($senddate)) {
				echo '<p>' . _MAILINGSAVED . '</p>';
			} // end if
			break;
		// view mailings
		case ('show') :
			$query = 'SELECT * FROM `#__anjel_mailing` WHERE `list_id` = \'' . $listid . '\'';
			$database->setQuery($query);
			$mailings = $database->loadObjectList();
			$error = $database->getErrorMsg();
			// quit on error
			if (!empty($error)) {
				echo '<p><b>Error (admin.anjel.php->mailing() line ' . __LINE__ . '):</b> Error getting mailings. Database error: <br />' . $error . '</p>';
				return false;
			} else {
				backend_html :: showMailings($mailings, $action, $listid);
				return true;
			}// end if
		// view archive
		case ('view') :
			// check if the senddate was provided
			$senddate = mosGetParam($_REQUEST, 'senddate', 0);
			if ($senddate != 0) {
				// if so, show the message
				$query = 'SELECT * FROM `#__anjel_mailing` WHERE `send_date` = \'' . $senddate . '\'';
				$database->setQuery($query);
				$database->loadObject($archivemailing);
				$error = $database->getErrorMsg();
				// quit on error
				if (!empty($error)) {
					echo '<p><b>Error (admin.anjel.php->mailing() line ' . __LINE__ . '):</b> Error getting mailing. Database error: <br />' . $error . '</p>';
					return false;
				} else {
					// check if textonly is empty
					if(!(strlen($archivemailing->list_textonly) > 0)) {
						$archivemailing->list_textonly = $mailing->htmlToText($archivemailing->list_content);
					} // end if
					// run "transform all" bots
					$_MAMBOTS->loadBotGroup('anjel');
					$bot_results = $_MAMBOTS->trigger('bot_anjel_transform_all', array(&$archivemailing->list_content, &$archivemailing->list_textonly));
					// change images to correct paths
					preg_match_all('/<img([^>]*)src="([^">]+)"([^>]*)>/i', $archivemailing->list_content, $images, PREG_SET_ORDER);
					foreach($images as $image) {
						// get rid of ../
						$image[2] = preg_replace('/(\.\.\/)+/', '/', $image[2]);
						// remove the site information if it is a local image
						$image[2] = str_replace($mosConfig_live_site, '', $image[2]);
						// remove a / at the beginning of the path (fixes some problems)
						$image[2] = preg_replace('/^\//', '', $image[2]);
						if (stristr($image[2], 'http://') === false) {
							// remove unneeded directory information
							if (stristr($image[2], 'images/stories/') !== false) {
								$image[2] = '/' . stristr($image[2], 'images/stories/');
							} // end if
							$replacement = '<img' . $image[1] . 'src="' . $mosConfig_live_site . $image[2] . '"' . $image[3] . '>';
						} else {
							$replacement = '<img' . $image[1] . 'src="' . $image[2] . '"' . $image[3] . '>';
						} // end if
						$archivemailing->list_content = str_replace($image[0], $replacement, $archivemailing->list_content);
					} // end foreach
					backend_html :: viewArchive($archivemailing);
					return true;
				}// end if
			} else {
				echo '<p><b>Error (admin.anjel.php->mailing() line ' . __LINE__ . '):</b> Senddate was not provided.</p>';
				return false;
			} // end if
			// don't show letters
			$showLetters = false;
			break;
		case ('delete') :
			// get the senddate
			$senddate = mosGetParam($_REQUEST, 'senddate', 0);
			// delete from database
			$query = 'DELETE FROM `#__anjel_mailing` WHERE `send_date` = \'' . $senddate . '\'';
			$database->setQuery($query);
			$database->query();
			$error = $database->getErrorMsg();
			$query = 'DELETE FROM `#__anjel_stats_overall` WHERE `listid` = \'' . $listid . '\' AND `send_date` = \'' . $senddate . '\'';
			$database->setQuery($query);
			$database->query();
			$error .= $database->getErrorMsg();
			$query = 'DELETE FROM `#__anjel_stats_detailed` WHERE `listid` = \'' . $listid . '\' AND `send_date` = \'' . $senddate . '\'';
			$database->setQuery($query);
			$database->query();
			$error .= $database->getErrorMsg();
			$query = 'DELETE FROM `#__anjel_stats_detailed_unregistered` WHERE `listid` = \'' . $listid . '\' AND `send_date` = \'' . $senddate . '\'';
			$database->setQuery($query);
			$database->query();
			$error .= $database->getErrorMsg();
			// quit on error
			if (!empty($error)) {
				echo '<p><b>Error (admin.anjel.php->mailing() line ' . __LINE__ . '):</b> Error deleting mailing. Database error: <br />' . $error . '</p>';
				return false;
			} else {
				// redirect to archive page
				mosRedirect('index2.php?option=com_anjel&act=mailing&task=show&listid=' . $listid);
			} // end if
			break;
		case ('cancel') :
			// redirect to main page
			mosRedirect('index2.php?option=com_anjel');
			break;
	} // end switch
	// get letters from the database if needed
	if ($showLetters == true) {
		$query = 'SELECT * FROM `#__anjel_letters`';
		$database->setQuery($query);
		$letters = $database->loadObjectList();
		$error = $database->getErrorMsg();
		// quit on error
		if (!empty($error)) {
			echo '<p><b>Error (admin.anjel.php->mailing() line ' . __LINE__ . '):</b> Error getting newsletters. Database error: <br />' . $error . '</p>';
			return false;
		} else {
			backend_html :: showLetters($letters, $action, 'show');
			return true;
		} // end if
	} // end if
 } // end function
 
 /**
  * Shows statistics
  * 
  * <p>Shows the newsletters from which to choose. Then shows the mailings 
  * that are available. Then gets the overall and detailed statistics from 
  * the database and displays them.</p>
  * 
  * @version 0.5.1
  * @since 0.4.3
  * @global int the list to work with
  * @global string the task to perform
  * @global string the action to perform
  * @global class access to the database
  * @uses backend_html::showStatistics()
  * @uses backend_html::showMailings()
  * @uses backend_html::showLetters()
  * @return boolean whether it was successful or not
  */
 function statistics() {
	 global $listid, $task, $action, $database;
	 
	 // get send date
	 $senddate = mosGetParam($_REQUEST, 'senddate', 0);
	 
	 // Check if the list's id was sent
	 if (!empty($listid)) {
		 // if so, switch by task
		 switch ($task) {
			 case ('show') :
				 // make sure send date was supplied
				 if ($senddate != 0) {
					 // if so, get statistics from database
					 $query = 'SELECT * FROM `#__anjel_stats_overall` WHERE `listid` = \'' . $listid . '\' AND `send_date` = \'' . $senddate . '\'';
					 $database->setQuery($query);
					 $database->loadObject($globalStats);
					 $error = $database->getErrorMsg();
					 $query = 'SELECT U.name, U.email, D.html, D.read FROM `#__anjel_stats_detailed` as D, `#__users` as U WHERE D.listid = \'' . $listid . '\' AND D.subscriber_id = U.id AND D.send_date = \'' . $senddate . '\'';
					 $database->setQuery($query);
					 $detailedStatsRegistered = $database->loadObjectList();
					 $error .= $database->getErrorMsg();
					 $query = 'SELECT U.name, U.email, D.html, D.read FROM `#__anjel_stats_detailed_unregistered` as D, `#__anjel_unregistered` as U WHERE D.listid = \'' . $listid . '\' AND D.subscriber_id = U.unregistered_id AND D.send_date = \'' . $senddate . '\'';
					 $database->setQuery($query);
					 $detailedStatsUnregistered = $database->loadObjectList();
					 $error .= $database->getErrorMsg();
					 // quit on error
					 if (!empty($error)) {
						 echo '<p><b>Error (admin.anjel.php->statistics() line ' . __LINE__ . '):</b> Error getting statistics. Database error: <br />' . $error . '</p>';
						 return false;
					 } else {
						 // join detailed stats
						 $detailedStats = array_merge($detailedStatsRegistered, $detailedStatsUnregistered);
						 // Get detailed stats
						 $html_read = array();
						 $html_unread = array();
						 $text = array();
						 foreach ($detailedStats AS $detailedStat) {
							 // check if this is an html user
							 if($detailedStat->html == 1) {
								 // if so, check if it was read
								 if($detailedStat->read == 1){
									 // if so, add to html read array
									 $html_read[] = $detailedStat;
								 } else{
									 // if not, add to html unread
									 $html_unread[] = $detailedStat;
								 } // end if
							 } else{
								 // if not, add to text
								 $text[] = $detailedStat;
							 } // end if
						 } // end foreach
						 // get letter details
						 $query = 'SELECT * FROM `#__anjel_letters` WHERE `id` = \'' . $listid . '\'';
						 $database->setQuery($query);
						 $database->loadObject($letter);
						 $error = $database->getErrorMsg();
						 // quit on error
						 if (!empty($error)) {
							 echo '<p><b>Error (admin.anjel.php->statistics() line ' . __LINE__ . '):</b> Error getting newsletter. Database error: <br />' . $error . '</p>';
							 return false;
						 } else {
							 // get mailing from database
							 $query = 'SELECT * FROM `#__anjel_mailing` WHERE `list_id` = \'' . $listid . '\' AND `send_date` = \'' . $senddate . '\'';
							 $database->setQuery($query);
							 $database->loadObject($mailing);
							 $error = $database->getErrorMsg();
							 // quit on error
							 if (!empty($error)) {
								 echo '<p><b>Error (admin.anjel.php->statistics() line ' . __LINE__ . '):</b> Error getting mailings. Database error: <br />' . $error . '</p>';
								 return false;
							 } else {
								 // finally send it to the html class
								 backend_html :: showStatistics($letter, $mailing, $globalStats, $html_read, $html_unread, $text, $listid);
								 return true;
							 } // end if
						 } // end if
					 } // end if
				 } else {
					 // if not, show error message
					 echo '<p><b>Error (admin.anjel.php->statistics() line ' . __LINE__ . '):</b> No send date provided.</p>';
					 return false;
				 } // end if
			     break;
			 case ('cancel') :
			 	 // check if send date was sent
			 	 if ($senddate != 0) {
					 // if so, redirect to mailings
					 mosRedirect('index2.php?option=com_anjel&act=statistics&listid=' . $listid);
			 	 } else {
					 // if not, redirect to letters
					 mosRedirect('index2.php?option=com_anjel&act=statistics');
			 	 } // end if 
			 default :
			 	 // get mailings from database
			 	 $query = 'SELECT * FROM `#__anjel_mailing` WHERE `list_id` = \'' . $listid . '\'';
				 $database->setQuery($query);
				 $mailings = $database->loadObjectList();
				 $error = $database->getErrorMsg();
				 // quit on error
				 if (!empty($error)) {
					 echo '<p><b>Error (admin.anjel.php->statistics() line ' . __LINE__ . '):</b> Error getting mailings. Database error: <br />' . $error . '</p>';
					 return false;
				 } else {
					 // send to html class
					 backend_html :: showMailings($mailings, $action, $listid);
					 return true;
				 } // end if 
		 } // end switch
	 } else {
		 // if not, switch by task
		 switch ($task) {
			 case ('cancel') :
			 	 mosRedirect('index2.php?option=com_anjel');
				 break;
			 default :
			 	 // get letters from database
				 $query = 'SELECT * FROM `#__anjel_letters`';
				 $database->setQuery($query);
				 $letters = $database->loadObjectList();
				 $error = $database->getErrorMsg();
				 // quit on error
				 if (!empty($error)) {
					 echo '<p><b>Error (admin.anjel.php->mailing() line ' . __LINE__ . '):</b> Error getting newsletters. Database error: <br />' . $error . '</p>';
					 return false;
				 } else {
					 backend_html :: showLetters($letters, $action, 'edit');
					 return true;
				 } // end if
				 break;
		 } // end switch
	 } // end if
 } // end function
 
 /**
  * Shows update options
  * 
  * <p>Gets the local and global anjel version arrays. Then displays the 
  * files that need to be updated, added, and/or removed. Then it will run 
  * the update script and update, add, and/or remove the selected files.</p>
  * 
  * @version 0.6.1
  * @since 0.4.3
  * @global string the task to perform
  * @global string the filesystem path to the main site directory
  * @global array ANJEL configuration options
  * @global string the message to display
  * @uses anjel_update::update()
  * @uses updateFile()
  * @uses checkVersion()
  * @uses backend_html::showUpdateOptions()
  */
 function update() {
	 global $task, $mosConfig_absolute_path, $newsletterConfig, $message;
	 
	 // Check for safe mode
	 if (ini_get('safe_mode')) {
	 	 // Do it the safe mode way
	 	 // no safe mode way yet
	 } else {
	 	 // set time limit to configured number of minutes
	 	 set_time_limit(60 * $newsletterConfig['script_timeout']);
	 }
	 // check if remote url files are allowed
	 if ((ini_get('allow_url_fopen') == false && !in_array('curl', get_loaded_extensions())) || ini_get('safe_mode') == true) {
		 echo 'Update will not work because of your server restrictions.';
		 return;
	 } // end if	 
	 // switch by task
	 switch ($task) {
		 case ('doUpdate') :
		 	 // run update file
			 $currentVersion = mosGetParam($_REQUEST, 'currentversion', 0);
			 if (ini_get('allow_url_fopen') == false) {
				 if (in_array('curl', get_loaded_extensions())) {
					 eval('?>' . getFileCurl('update.inc') . '<?php ');
				 } else {
					 echo '<p><b>Error (admin.anjel.php->update() line ' . __LINE__ . '):</b> No way to get remote file.</p>';
					 return false;
				 } // end if
			 } else {
				 require_once($newsletterConfig['update_url'] . 'update.inc');
			 } // end if
			 anjel_update :: update($currentVersion);
		 	 // get options
		 	 $needUpdated = mosGetParam($_REQUEST, 'needUpdated', 0);
			 $needAdded = mosGetParam($_REQUEST, 'needAdded', 0);
			 $needRemoved = mosGetParam($_REQUEST, 'needRemoved', 0);
			 // print form
			 echo <<<FORM
<form action="index2.php" method="post" name="adminForm">
	<input type="hidden" name="option" value="com_anjel" />
	<input type="hidden" name="act" value="update" />
	<input type="hidden" name="task" value="" />
</form>
FORM;
			 // check if files need updated
			 if ($needUpdated != 0) {
				 // if so, update them
				 echo '<p><strong>' . _UPDATING . '</strong><br />';
				 foreach ($needUpdated as $file) {
					 echo $file . '   ...   ';
					 // check if file updated correctly
					 if (updateFile($file)) {
						 // if so, print success
						 echo _UPDATE_UPDATED_SUCCESSFULLY . '<br />';
					 } else {
						 // if not, print failure
						 echo _UPDATE_FAILED . '<br />';
					 } // end if
				 } // end foreach
				 echo '</p>';
			 } // end if
			 // check if files need added
			 if ($needAdded != 0) {
				 // if so, update them
				 echo '<p><strong>' . _ADDING . '</strong><br />';
				 foreach ($needAdded as $file) {
					 echo $file . '   ...   ';
					 // check if file was added correctly
					 if (updateFile($file)) {
						 // if so, print success
						 echo _ADDED_SUCCESSFULLY . '<br />';
					 } else {
						 // if not, print failure
						 echo _ADDING_FAILED . '<br />';
					 } // end if
				 } // end foreach
				 echo '</p>';
			 } // end if
			 // check if files need removed
			 if ($needRemoved != 0) {
				 // if so, update them
				 echo '<p><strong>' . _REMOVING . '</strong><br />';
				 foreach ($needRemoved as $file) {
					 echo $file . '   ...   ';
					 // check if file was removed correctly
					 if (file_exists($mosConfig_absolute_path . '/' . $file) && unlink($mosConfig_absolute_path . '/' . $file)) {
						 // if so, print success
						 echo _REMOVED_SUCCESSFULLY . '<br />';
					 } else {
						 // if not, print failure
						 echo _REMOVING_FAILED . '<br />';
					 } // end if
				 } // end foreach
				 echo '</p>';
			 } // end if
			 // check if configuration file needs to be updated with the correct options
			 if (in_array('administrator/components/com_anjel/configuration.php', $needUpdated)) {
				 // update configuration
				 $task = 'save';
				 configuration($newsletterConfig, false);
			 } // end if
		 	 break;
		 case ('version') :
		 	 echo <<<FORM
<form action="index2.php" method="post" name="adminForm">
	<input type="hidden" name="option" value="com_anjel" />
	<input type="hidden" name="act" value="update" />
	<input type="hidden" name="task" value="" />
</form>
FORM;
			 // get version
			 $version = mosGetParam($_REQUEST, 'version', 0);
			 $newsletterConfig['update_url'] .= $version . '/';
			 // get version files
		 	 require_once ($mosConfig_absolute_path . '/administrator/components/com_anjel/anjel.version.php' );
			 if (ini_get('allow_url_fopen') == false) {
				 if (in_array('curl', get_loaded_extensions())) {
					 eval('?>' . getFileCurl('anjel.version.global.inc') . '<?php ');
					 // run undate file
					 eval('?>' . getFileCurl('undate.inc') . '<?php ');
					 anjel_undate :: undate($localAnjelVersion['anjel']);
				 } else {
					 echo '<p><b>Error (admin.anjel.php->update() line ' . __LINE__ . '):</b> No way to get remote file.</p>';
					 return false;
				 } // end if
			 } else {
				 require_once ($newsletterConfig['update_url'] . 'anjel.version.global.inc');
				 // run undate file
				 if ( include_once ($newsletterConfig['update_url'] . 'undate.inc')) {
					 anjel_undate :: undate($localAnjelVersion['anjel']);
				 } // end if
			 } // end if
			 // delete all current files
			 unset ($localAnjelVersion['anjel']);
			 echo '<p><strong>' . _REMOVING . '</strong><br />';
			 foreach ($localAnjelVersion as $file => $localVersion) {
				 echo $file . '   ...   ';
				 // check if file was removed correctly
				 if (file_exists($mosConfig_absolute_path . '/' . $file) && unlink($mosConfig_absolute_path . '/' . $file)) {
					 // if so, print success
					 echo _REMOVED_SUCCESSFULLY . '<br />';
				 } else {
					 // if not, print failure
					 echo _REMOVING_FAILED . '<br />';
				 } // end if
			 } // end foreach
			 // add new version files
			 echo '<p><strong>' . _ADDING . '</strong><br />';
			 unset ($globalAnjelVersion['anjel']);
			 foreach ($globalAnjelVersion as $file => $globalVersion) {
				 echo $file . '   ...   ';
				 if (updateFile($file, $globalVersion)) {
					 echo _ADDED_SUCCESSFULLY . '<br />';
				 } else {
					 echo _ADDING_FAILED . '<br />';
				 } // end if
			 } // end foreach
			 break;
		 case ('cancel') :
		 	 mosRedirect('index2.php?option=com_anjel');
			 break;
		 default :
		 	 // check for updates
		 	 // include required files
		 	 require_once ($mosConfig_absolute_path . '/administrator/components/com_anjel/anjel.version.php' );
			 if (ini_get('allow_url_fopen') == false) {
				 if (in_array('curl', get_loaded_extensions())) {
					 eval('?>' . getFileCurl('anjel.version.global.inc') . '<?php ');
					 eval('?>' . getFileCurl('anjel.versions.inc') . '<?php ');
				 } else {
					 echo '<p><b>Error (admin.anjel.php->update() line ' . __LINE__ . '):</b> No way to get remote file.</p>';
					 return false;
				 } // end if
			 } else {
				 require_once ($newsletterConfig['update_url'] . 'anjel.version.global.inc');
				 require_once ($newsletterConfig['update_url'] . 'anjel.versions.inc');
			 }// end if
			 // see which files need updated
			 $needUpdated = array();
			 foreach ($localAnjelVersion as $key => $value) {
				 // see if version is different
				 if ((checkVersion($value, $globalAnjelVersion[$key])) && ($key != 'anjel')) {
					 // if so, add to needs updating array
					 $needUpdated[] = $key;
				 } // end if
			 } // end foreach
			 // see which files need added
			 $needAdded = array();
			 foreach ($globalAnjelVersion as $key => $value) {
				 // see if key exists in local version
				 if (!array_key_exists($key, $localAnjelVersion)) {
					 // if not, add to needs added array
					 $needAdded[] = $key;
				 } // end if
			 } // end foreach
			 // see which files need removed
			 $needRemoved = array();
			 foreach ($localAnjelVersion as $key => $value) {
				 // see if key exists in local version
				 if (!array_key_exists($key, $globalAnjelVersion)) {
					 // if not, add to needs added array
					 $needRemoved[] = $key;
				 } // end if
			 } // end foreach
			 // show update options
			 backend_html :: showUpdateOptions($localAnjelVersion, $globalAnjelVersion, $needUpdated, $needAdded, $needRemoved, $anjelVersions, $message);
	 } // end switch
 } // end function
 
 /**
  * Gets the subscribers
  * 
  * <p>Gets the subscribers from the database and returns it as an array. 
  * It also checks if limits need to be added to the query and if it needs 
  * to search through the email and name fields. Also updates the variable 
  * $total to the total number of subscribers that were found.</p>
  * 
  * @version 0.6.1
  * @since 0.4.3
  * @param int $start the lower limit
  * @param int $limit the total to get
  * @param string $emailsearch the email search filter
  * @param object $total the total number of subscribers
  * @global class access to the database
  * @global string the action to perform
  * @global int the list to work with
  * @return boolean false on failure | array the subscribers
  */
 function getSubscribers($start, $limit, $emailsearch, &$total) {
	global $database, $action, $listid;
	
	// check whether this is a registered or unregistered action
	switch ($action) {
		case ('registered') :
			$query = 'SELECT M.subscriber_id as id, N.name, N.email, M.*, N.name, N.email FROM `#__anjel_subscribers` AS M, `#__users` AS N WHERE M.subscriber_id = N.id AND M.blacklist = 0';
			break;
		case ('unregistered') :
			$query = 'SELECT M.unregistered_id as id, M.*, M.name, M.email FROM `#__anjel_unregistered` AS M WHERE M.blacklist = 0';
			break;
		default :
			// error
			echo '<p><b>Error (admin.anjel.php->getSubscribers() line ' . __LINE__ . '):</b> Unknown subscriber type.</p>';
			return false;
	} // end switch
	
	// check if we need to add list limits
	if ($listid != 0) {
		if ($action == 'registered') {
			$query .= ' AND M.list_' . $listid . ' <> 0';
			// check if we need to search for an email address
			if ($emailsearch !== 0) {
				$query .= ' AND (N.email LIKE \'%' . $emailsearch . '%\' OR N.name LIKE \'%' . $emailsearch . '%\')';
			} // end if
		} else {
			$query .= ' AND M.list_' . $listid . ' <> 0';
			// check if we need to search for an email address
			if ($emailsearch !== 0) {
				$query .= ' AND (M.email LIKE \'%' . $emailsearch . '%\' OR M.name LIKE \'%' . $emailsearch . '%\')';
			} // end if
		} // end if	
	} else {
		if ($action == 'registered') {
			// check if we need to search for an email address
			if ($emailsearch !== 0) {
				$query .= ' AND (N.email LIKE \'%' . $emailsearch . '%\' OR N.name LIKE \'%' . $emailsearch . '%\')';
			} // end if
		} else {
			// check if we need to search for an email address
			if ($emailsearch !== 0) {
				$query .= ' AND (M.email LIKE \'%' . $emailsearch . '%\' OR M.name LIKE \'%' . $emailsearch . '%\')';
			} // end if
		} // end if
	} // end if
	
	// get total
	$database->setQuery($query);
	$totalcheck = $database->loadRowList();
	$error = $database->getErrorMsg();
	// quit on error
	if (!empty($error)) {
		echo '<p><b>Error (admin.anjel.php->getSubscribers() line ' . __LINE__ . '):</b> Error getting total from database. Database error: <br />' . $error . '</p>';
		return false;
	} else {
		$total = count($totalcheck);
	} // end if
	
	// check if we need to add limit
	if ($start != -1 && $limit != -1) {
		$query .= ' LIMIT ' . $start . ', ' . $limit;
	} // end if
	
	// do the query
	$database->setQuery($query);
	$subscribers = $database->loadAssocList();
	$error = $database->getErrorMsg();
	// quit on error
	if (!empty($error)) {
		echo '<p><b>Error (admin.anjel.php->getSubscribers() line ' . __LINE__ . '):</b> Error getting subscribers from database. Database error: <br />' . $error . '</p>';
		return false;
	} else {
		// make the array if it was false
		if ($subscribers == false) {
			$subscribers = array(0);
		} // end if
 		return $subscribers;
	} // end if
 } // end function
 
 /**
  * Updates the newsletter options
  * 
  * <p>Gets the new newsletter options and updates the database with 
  * them.</p>
  * 
  * @version 0.5.0
  * @since 0.4.3
  * @global int the list to work with
  * @global class access to the database
  * @return boolean whether it was successful or not
  */
 function updateLetter() {
	 global $listid, $database;
	 
	 // get parameters
	 $list_name = mosGetParam($_REQUEST, 'list_name', '');
	 $list_desc = mosGetParam($_REQUEST, 'list_desc', '', _MOS_ALLOWHTML);
	 $sendername = mosGetParam($_REQUEST, 'sendername', '');
	 $senderemail = mosGetParam($_REQUEST, 'senderemail', '');
	 $bounceadres = mosGetParam($_REQUEST, 'bounceadres', '');
	 $layout = mosGetParam($_REQUEST, 'layout', '', _MOS_ALLOWHTML);
	 $subscribemessage = mosGetParam($_REQUEST, 'subscribemessage', '', _MOS_ALLOWHTML);
	 $unsubscribemessage = mosGetParam($_REQUEST, 'unsubscribemessage', '', _MOS_ALLOWHTML);
	 $html = mosGetParam($_REQUEST, 'html', 0);
	 $hidden = mosGetParam($_REQUEST, 'hidden', 0);
	 $auto_add = mosGetParam($_REQUEST, 'auto_add', 0);
	 
	 // if quotes not already escaped, escape them
	 if (!get_magic_quotes_gpc()) {
		 $list_name = addslashes($list_name);
		 $list_desc = addslashes($list_desc);
		 $sendername = addslashes($sendername);
		 $layout = addslashes($layout);
		 $subscribemessage = addslashes($subscribemessage);
		 $unsubscribemessage = addslashes($unsubscribemessage);
	 } // end if
	 
	 // update database
	 $query = 'UPDATE `#__anjel_letters` SET 
	 			`list_name` = \'' . $list_name . '\', 
	 			`list_desc` = \'' . $list_desc . '\', 
	 			`sendername` = \'' . $sendername . '\',
	 			`senderemail` = \'' . $senderemail . '\', 
	 			`bounceadres` = \'' . $bounceadres . '\', 
	 			`layout` = \'' . $layout . '\', 
	 			`subscribemessage` = \'' . $subscribemessage . '\', 
	 			`unsubscribemessage` = \'' . $unsubscribemessage . '\', 
	 			`html` = \'' . $html . '\', 
	 			`hidden` = \'' . $hidden . '\' 
	 			WHERE `id` = \'' . $listid . '\';';
 	 $database->setQuery($query);
	 $database->query();
	 $error = $database->getErrorMsg();
	 $query = 'ALTER TABLE `#__anjel_subscribers` ALTER COLUMN `list_' . $listid . '` SET DEFAULT \'' . $auto_add . '\';';
	 $database->setQuery($query);
	 $database->query();
	 $error .= $database->getErrorMsg();
	 $query = 'ALTER TABLE `#__anjel_unregistered` ALTER COLUMN `list_' . $listid . '` SET DEFAULT \'' . $auto_add . '\';';
	 $database->setQuery($query);
	 $database->query();
	 $error .= $database->getErrorMsg();
	 // quit on error
	 if (!empty($error)) {
		 echo '<p><b>Error (admin.anjel.php->updateLetter() line ' . __LINE__ . '):</b> Error updating letter options. Database error: <br />' . $error . '</p>';
		 return false;
	 } else {
		 return true;
	 } // end if
 } // end function
 
 /**
  * Checks if the second arguments version is higher
  * 
  * <p>If it is higher it returns true. It returns false otherwise.</p>
  * 
  * @version 0.5.0
  * @since 0.4.3
  * @param string $localVersion the local version to compare
  * @param string $globalVersion the global version to check against
  * @return boolean true if global version is higher, false otherwise
  */
 function checkVersion($localVersion, $globalVersion) {
	 
	 // split up major, minor, and micro version
	 $localSplit = explode ('.', $localVersion . '...');
	 $globalSplit = explode ('.', $globalVersion . '...');
	 // check if major version is higher
	 if ($globalSplit[0] > $localSplit[0]) {
		 // if so, return true
		 return true;
	 } else if ($globalSplit[0] < $localSplit[0]) {
		 return false;
	 } else {
		 // if not, check minor version
		 if ($globalSplit[1] > $localSplit[1]) {
			 // if higher, return true
			 return true;
		 } else if ($globalSplit[1] < $localSplit[1]) {
			 return false;
		 } else {
			 // if lower, check micro version
			 if ($globalSplit[2] > $localSplit[2]) {
				 // if higher, return true
				 return true;
			 } else if ($globalSplit[2] < $localSplit[2]) {
				 return false;
			 } else {
				 if ($globalSplit[3] > $localSplit[3]) {
					 // if higher, return true
					 return true;
				 } else {
					 // if lower or equal, return false
					 return false;
				 } // end if
			 } // end if
		 } // end if
	 } // end if
 } // end function
 
 /**
  * Updates (or adds) a file
  * 
  * <p>Gets the global file and (over)writes it to the local file.</p>
  * 
  * @version 0.6.1
  * @since 0.4.3
  * @param string $file the file to be updated
  * @param string $version the file version
  * @global array ANJEL configuration options
  * @global array filesystem path to main site directory
  * @return boolean whether it was successful or not
  */
 function updateFile($file, $version = '') {
	 global $newsletterConfig, $mosConfig_absolute_path;

	 // get global file
	 if (ini_get('allow_url_fopen') == false) {
		 if (in_array('curl', get_loaded_extensions())) {
			 $globalFile = getFileCurl($file, $version);
		 } else {
			 echo '<p><b>Error (admin.anjel.php->updateFile() line ' . __LINE__ . '):</b> No way to get remote file.</p>';
			 return false;
		 } // end if 
	 } else { 
		 $globalFile = file_get_contents($newsletterConfig['update_url'] . preg_replace('/\.php$/', '.inc', $file));
	 } // end if
	 // quit on error
	 if ($globalFile === false) {
		 echo '<p><b>Error (admin.anjel.php->updateFile() line ' . __LINE__ . '):</b> Error fetching file.</p>';
		 return false;
	 } else {
	 	 // write local file
	 	 return file_put_contents($mosConfig_absolute_path . '/' . $file, $globalFile);
	 } // end if
 } // end function
 
 /**
  * Gets a remote file from the update site with curl
  * 
  * <p>Gets the global file and returns it.</p>
  * 
  * @version 0.6.1
  * @since 0.6.1
  * @param string $file the file to be updated
  * @param string $version the file version
  * @global array ANJEL configuration options
  * @return string the file
  */
 function getFileCurl($file, $version = '') {
	 global $newsletterConfig;
	 
	 $curl_handle = curl_init();
	 // set file location
	 curl_setopt ($curl_handle, CURLOPT_URL, $newsletterConfig['update_url'] . preg_replace('/\.php$/', '.inc', $file));
	 // set to save as string
	 curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
	 // prevent hanging
	 curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, 1);
	 // get file
	 $file = curl_exec($curl_handle);
	 // get error
	 $file = (curl_errno($curl_handle) == 0) ? $file : false;
	 // close connection
	 curl_close($curl_handle);
	 // write file
	 return $file;
 }
 
 /**
  * Uses the sefRelToAbs function and prepends the site url if needed
  * 
  * @version 0.6.1
  * @since 0.6.1
  * @param string $url the url to be sef'd
  * @global string url of the main site
  * @return string the updated url
  */
 function anjel_sef_rel_to_abs($url) {
	 global $mosConfig_live_site;
	 
	 $result = sefRelToAbs($url);
	 $result = str_replace($mosConfig_live_site . '/' . $mosConfig_live_site, $mosConfig_live_site, $mosConfig_live_site . '/' . $result);
	 return $result;
 } // end function
 
 echo '<p align="center" style="clear:both;"><a href="http://anjel.schmalls.com">ANJEL 0.6.1-final</a> component by <a href="mailto:schmalls+hide@address.com">Schmalls</a></p>'; 
?>
Return current item: ANJEL