Example #1
0
 /**
  * printPage
  *
  * @return Void Doesn't return anything.
  */
 public function printPage()
 {
     $user = GetUser();
     $split_api = $this->GetApi('Splittest');
     // for permission checks
     $subaction = $this->_getGetRequest('subaction', 'print');
     $perpage = $this->_getGetRequest('PerPageDisplay', null);
     $jobids = $this->_getGETRequest('jobids', null);
     $listids = $this->_getGETRequest('split_statids', null);
     $jobids = explode(",", $jobids);
     $listids = explode(",", $listids);
     SendStudio_Functions::LoadLanguageFile('Stats');
     if (!SplitTest_API::OwnsJobs($user->Get('userid'), $jobids) && !$user->Admin()) {
         FlashMessage(GetLang('NoAccess'), SS_FLASH_MSG_ERROR, $this->base_url);
         return;
     }
     // Get some setup parameters for the API
     $sortdetails = array('sort' => 'splitname', 'direction' => 'asc');
     $page_number = 0;
     $perpage = 20;
     $displayAll = false;
     // just show a single splitest campaign send. If you want every campaign send for a split test set to true
     $dateFromat = self::getDateFormat();
     $statitics = array();
     $jobid = 0;
     for ($i = 0; $i < count($jobids); $i++) {
         $stats = array();
         $stats_api = new Splittest_Stats_API();
         $jobid = $jobids[$i];
         $splitid = $listids[$i];
         // get the array of stats data
         $stats = $stats_api->GetStats(array($splitid), $sortdetails, false, $page_number, $perpage, $displayAll, $jobid);
         foreach ($stats as $stats_id => $stats_details) {
             $stats[$stats_id]['splitname'] = htmlspecialchars($stats_details['splitname'], ENT_QUOTES, SENDSTUDIO_CHARSET);
             $stats[$stats_id]['campaign_names'] = htmlspecialchars($stats_details['campaign_names'], ENT_QUOTES, SENDSTUDIO_CHARSET);
             $stats[$stats_id]['list_names'] = htmlspecialchars($stats_details['list_names'], ENT_QUOTES, SENDSTUDIO_CHARSET);
         }
         // A Splittest can be sent multiple times hence we might have multiple campaign record sets here
         while (list($id, $data) = each($stats)) {
             $charts = $this->generateCharts($data['splitname'], $data['campaigns'], $subaction);
             foreach ($charts as $type => $data) {
                 $stats[$id][$type] = $data;
             }
         }
         $statistics[] = $stats;
     }
     $template = GetTemplateSystem(dirname(__FILE__) . '/templates');
     $template->Assign('DateFormat', $dateFromat);
     $template->Assign('statsData', $statistics);
     $template->Assign('subaction', $subaction);
     $options = $this->_getGETRequest('options', null);
     for ($i = 0; $i < count($options); $i++) {
         $template->Assign($options[$i], $options[$i]);
     }
     $template->ParseTemplate('Stats_Summary_Splittest');
 }
	/**
	 * Get HTML options to be displayed
	 *
	 * @return String Returns the parsed template with language variables replaced etc.
	 *
	 * @todo Allow to save user's preference (ie. when user has clicked enable "google", it should be pre-clicked the next time user see it
	 */
	function GetDisplayOption()
	{
		$HTML = array();

		$tpl = GetTemplateSystem();
		$HTML['Required'] = $tpl->ParseTemplate('Required', true);
		unset($tpl);

		$tpl = GetTemplateSystem(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'templates');
		$tpl->Assign('HTML', $HTML);
		return $tpl->ParseTemplate('Options', true);
	}
Example #3
0
	/**
	 * PrintAddonsList
	 * Prints a list of all addons that the system can use.
	 * It works out what step an addon is up to (whether it is configured, enabled, installed or not) and prints an appropriate action
	 *
	 * @uses Interspire_Addons
	 * @uses Interspire_Addons::GetAllAddons
	 * @uses Interspire_Addons::GetAvailableAddons
	 * @uses FlashMessage
	 * @uses GetFlashMessages
	 *
	 * @return String Returns a formatted (table design) list of addons and what they are up to (whether they need to be configured, installed, enabled etc).
	 */
	function PrintAddonsList()
	{
		require_once(SENDSTUDIO_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR . 'interspire_addons.php');
		$addon_system = new Interspire_Addons();
		$addons = $addon_system->GetAllAddons();
		if (empty($addons)) {
			FlashMessage(GetLang('Addon_NoAddonsAvailable'), SS_FLASH_MSG_ERROR);
			$GLOBALS['Message'] .= GetFlashMessages();
			return $this->ParseTemplate('Settings_Addons_Empty', true, false);
		} else {
			$GLOBALS['Message'] .= GetFlashMessages();
		}

		$addons_status = $addon_system->GetAvailableAddons();

		$addons_list = '';

		$page = array(
			'message' => $GLOBALS['Message']
		);

		foreach ($addons as $addon_name => $details) {
			$addons[$addon_name]['name'] = htmlspecialchars($details['name'], ENT_QUOTES, SENDSTUDIO_CHARSET);
			$addons[$addon_name]['short_name'] = htmlspecialchars($this->TruncateName($details['name']), ENT_QUOTES, SENDSTUDIO_CHARSET);
			$addons[$addon_name]['description'] = htmlspecialchars($details['description'], ENT_QUOTES, SENDSTUDIO_CHARSET);
			$addons[$addon_name]['short_description'] = htmlspecialchars($this->TruncateName($details['description']), ENT_QUOTES, SENDSTUDIO_CHARSET);

			if (isset($addons_status[$addon_name])) {
				$addons[$addon_name]['install_details'] = $addons_status[$addon_name];
				$addons[$addon_name]['need_upgrade'] = (version_compare($details['addon_version'], $addons_status[$addon_name]['addon_version']) == 1);
			} else {
				$addons[$addon_name]['install_details'] = false;
			}
		}

		$tpl = GetTemplateSystem();
		$tpl->Assign('PAGE', $page);
		$tpl->Assign('records', $addons);
		return $tpl->ParseTemplate('Settings_Addons_Display', true);
	}
Example #4
0
	/**
	* ShowCaptcha
	*
	* Returns the html img tags for the captcha image(s)
	*
	* @return string
	*/
	function ShowCaptcha()
	{
		$tpl = GetTemplateSystem();
		$tpl->Assign('captcha_baseurl', SENDSTUDIO_RESOURCES_URL . '/form_designs/captcha/index.php');
		$tpl->Assign('captcha_length', $this->length);
		$tpl->Assign('captcha_dynamic', ($this->type == 'dynamic'));
		$tpl->Assign('captcha_session', (!$this->inside_sendstudio && !$this->modify_details));

		return $tpl->ParseTemplate('captcha_code', true);
	}
Example #5
0
	$statid = $foundparts['n'];
}

if ($statstype) {
	$validLists = $subscriberapi->GetSubscribersListByStatOwner($statid, $subscriber_id, $statstype);
} else {
	// default
	$validLists[] = array('listid' => $primary_listid, 'subscriberid' => $subscriber_id);
}

$displayList = array();
foreach ($validLists as $eachList) {
	$listapi->Load($eachList['listid']);
	$subscriberlistinfo = $subscriberapi->LoadSubscriberList($eachList['subscriberid'], $eachList['listid']);
	$displayList[] = array('listid' => $eachList['listid'], 'name' => $listapi->Get('name'), 'cc' => $subscriberlistinfo['confirmcode'], 'subscriberid' => $eachList['subscriberid']);
}

if (!sizeof($displayList)) {
	$GLOBALS['DisplayMessage'] = GetLang('DefaultUnsubscribeMessage');
	$sendstudio_functions->ParseTemplate('Default_Form_Message');
	exit();
}

$GLOBALS['Message'] = '<div style="padding:10px;">'.GetLang('Unsubscribe_Form_Note').'</div>';

$tpl = GetTemplateSystem();
$tpl->Assign('page', $_GET);
$tpl->Assign('list', $displayList);
$tpl->Assign('primary_listid', $primary_listid);
echo $tpl->ParseTemplate('unsubscribe_form', true);
Example #6
0
/**
* GetFlashMessages
* Gets the messages from the session and works out which template etc to display them in based on the message type.
* If there are multiple messages, they are all returned (based on which type/template etc) in one long string.
*
* It will not combine all 'success' messages into one box and all 'error' messages into another box.
* Each message is displayed in it's own box and they are returned in the order they were created.
*
* If you create a 'success' message then an 'info' message then an 'error' message, that is the order they are returned in.
*
* @see FlashMessage
* @uses SS_FLASH_MSG_SUCCESS
* @uses SS_FLASH_MSG_ERROR
* @uses SS_FLASH_MSG_WARNING
* @uses SS_FLASH_MSG_INFO
*
* @return String Returns the message ready for displaying.
*/
function GetFlashMessages()
{
	$flash_messages = IEM::sessionGet('FlashMessages', false);

	if (!$flash_messages) {
		return '';
	}

	$template_system = GetTemplateSystem();

	$print_msg = '';
	foreach ($flash_messages as $msg) {
		switch ($msg['type']) {
			case SS_FLASH_MSG_SUCCESS:
				$GLOBALS['Success'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('successmsg', true);
			break;

			case SS_FLASH_MSG_ERROR:
				$GLOBALS['Error'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('errormsg', true);
			break;

			case SS_FLASH_MSG_INFO:
				$GLOBALS['Message'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('infomsg', true);
			break;

			case SS_FLASH_MSG_WARNING:
				$GLOBALS['Warning'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('warningmsg', true);
			break;
		}
	}
	IEM::sessionRemove('FlashMessages');

	return $print_msg;
}
Example #7
0
		/**
		 * TriggerEmailsStats_View
		 * Handle listing of the trigger emails statistics
		 *
		 * @return Void Prints output directly to stdout without returning anything.
		 *
		 * @uses Stats_API::GetTriggerEmailsStats()
		 */
		function TriggerEmailsStats_View()
		{
			// ----- Sanitize and declare variables that is going to be used in this function
				$user = IEM::userGetCurrent();

				$id					= intval($this->_getGETRequest('id', ''));

				$record				= array();
				$triggerrecord		= array();

				$api				= $this->GetApi();
				$triggerapi			= $this->GetApi('TriggerEmails');

				$page = array(
					'messages'		=> GetFlashMessages(),
					'whichtab'		=> intval($this->_getGETRequest('tab', 1)),
					'unique_open'	=> ($this->_getGETRequest('Unique', false) ? true : false),
					'session_token'	=> md5(uniqid(rand()))
				);

				$tabs				= array(
					'snapshot'		=> array(),
					'open'			=> array(),
					'links'			=> array(),
					'bounces'		=> array(),
					'unsubscribe'	=> array(),
					'forward'		=> array(),
					'recipients'	=> array()
				);

			// ----

			if ($id == 0) {
				return $this->TriggerEmailsStats_List();
			}

			// Make sure that user can access this particular trigger email statistics
			if (!$this->_TriggerEmailsStats_Access($id)) {
				return $this->TriggerEmailsStats_List();
			}

			// ----- Load trigger emails statistics record
				$record = $api->GetTriggerEmailsStatsRecord($id);
				$triggerrecord = $triggerapi->GetRecordByID($id, true, true);

				if (!isset($triggerrecord['triggeractions']) || !is_array($triggerrecord['triggeractions'])) {
					$triggerrecord['triggeractions'] = array();
				}

				if (!isset($triggerrecord['triggeractions']['send']) || !is_array($triggerrecord['triggeractions']['send'])) {
					$triggerrecord['triggeractions']['send'] = array();
				}

				$temp = array('trackopens', 'tracklinks');
				foreach ($temp as $each) {
					if (!isset($triggerrecord['triggeractions']['send'][$each])) {
						$triggerrecord['triggeractions']['send'][$each] = 0;
					}
				}

				if (empty($record)) {
					return $this->TriggerEmailsStats_List();
				}
			// -----


			// Log this to "User Activity Log"
			IEM::logUserActivity($_SERVER['REQUEST_URI'], 'images/chart_bar.gif', $record['triggeremailsname']);

			// ----- Calculate some common variables for the record
				$record['processed_totalsent'] = intval($record['htmlrecipients']) + intval($record['textrecipients']) + intval($record['multipartrecipients']);
				$record['processed_unopened'] = abs($record['processed_totalsent'] - $record['emailopens_unique']);
				$record['processed_totalbounced'] = intval($record['bouncecount_soft']) + intval($record['bouncecount_hard']) + intval($record['bouncecount_unknown']);

				if ($record['processed_totalsent'] != 0) {
					if ($triggerrecord['triggeractions']['send']['trackopens'] != 0) {
						$record['processed_timeframe_emailopens_total'] = intval($api->GetOpens($record['statid'], 1, 'all', $page['unique_open'], $this->CalendarRestrictions['opens'], true));
						$record['processed_timeframe_emailopens_unique'] = intval($api->GetOpens($record['statid'], 1, 'all', $page['unique_open'], $this->CalendarRestrictions['opens'], true));
					}

					if ($triggerrecord['triggeractions']['send']['tracklinks'] != 0) {
						$record['processed_timeframe_linkclicks_total'] = intval($api->GetClicks($record['statid'], 1, 'all', 'a', $this->CalendarRestrictions['clicks'], true));
						$record['processed_timeframe_linkclicks_unique'] = intval($api->GetUniqueClicks($record['statid'], 'a', $this->CalendarRestrictions['clicks']));
						$record['processed_timeframe_linkclicks_individuals'] = intval($api->GetUniqueClickRecipients($record['statid'], $this->CalendarRestrictions['clicks'], 'a'));
					}

					$record['processed_timeframe_bounces'] = intval($api->GetBounces($record['statid'], 1, 'all', 'any', $this->CalendarRestrictions['bounces'], true));

					$record['processed_timeframe_unsubscribes'] = intval($api->GetUnsubscribes($record['statid'], 1, 'all', $this->CalendarRestrictions['unsubscribes'], true));

					if (array_key_exists('forwards', $this->CalendarRestrictions) && !empty($this->CalendarRestrictions['forwards'])) {
						$record['processed_timeframe_forwards'] = intval($api->GetForwards($record['statid'], 1, 'all', $this->CalendarRestrictions['forwards'], true));
					} else {
						$record['processed_timeframe_forwards']	= intval($record['emailforwards']);
					}

					$record['processed_timeframe_totalsent'] = 0;

					// Set up session information that correspond to the current stats (this information in the session will not be cleaned up, need to refactor)
					// The session infromation is used to print out a table that list email addressess for "open" and "link" tabs
					IEM::sessionSet($page['session_token'], array(
						'statid'				=> $record['statid'],
						'calendar_restrictions'	=> $this->CalendarRestrictions,
						'unique_open_only'		=> $page['unique_open'],
						'summary'				=> $record
					));
				}
			// -----





			// Load additional language variable for displaying trigger email statistics
			$this->LoadLanguageFile('TriggerEmails');

			// Include the charting tool
			include_once (SENDSTUDIO_FUNCTION_DIRECTORY . '/amcharts/amcharts.php');


			// ----- Tab 1: Snapshot
				$tabs['snapshot']['intro'] = sprintf(GetLang('TriggerEmails_Stats_Snapshots_Intro'), $record['triggeremailsname']);
				$tabs['snapshot']['newsletter_uniqueopen'] = sprintf(GetLang('EmailOpens_Unique'), $this->FormatNumber($record['emailopens_unique']));
				$tabs['snapshot']['newsletter_totalopen'] = sprintf(GetLang('EmailOpens_Total'), $this->FormatNumber($record['emailopens']));
				$tabs['snapshot']['newsletter_bounce'] = $this->FormatNumber($record['processed_totalbounced']);
				$tabs['snapshot']['url_open_url'] = 'index.php?Page=Stats&Action=TriggerEmails&SubAction=view&tab=2&id=' . $id;
				$tabs['snapshot']['url_openunique_url'] = $tabs['snapshot']['url_open_url'] . '&Unique=1';

				$tabs['snapshot']['summary_chart'] = InsertChart(
					'pie',
					'stats_chart.php?Opens=' . $record['emailopens_unique'] . '&Unopened=' . $record['processed_unopened'] . '&Bounced=' . $record['processed_totalbounced'] . '&Area=TriggerEmails&'. IEM::SESSION_NAME . '=' . IEM::sessionID(),
					array('graph_title' => sprintf(GetLang('TriggerEmails_Stats_Snapshots_ChartTitle'), $record['triggeremailsname'])));
			// -----

			// ----- Tab 2: Open rates
				$tabs['open']['intro'] = sprintf(GetLang('TriggerEmails_Stats_Open_Intro'), $record['triggeremailsname']);

				// setup calendar
				$GLOBALS['TabID'] = '1';
				$this->SetupCalendar('Action=ProcessCalendar&SubAction=TriggerEmails&NextAction=View&tab=2&id=' . $id);
				$tabs['open']['calendar'] = $GLOBALS['Calendar'];
				unset($GLOBALS['TabID']);
				unset($GLOBALS['Calendar']);


				// Set up error message if no "opens" count is not available
				if (!array_key_exists('processed_timeframe_emailopens_total', $record) || !$record['processed_timeframe_emailopens_total']) {
					$tempMessage = 'TriggerEmails_Stats_Open_Error_HasNotBeenOpened';
					$tempRestriction = $this->CalendarRestrictions;

					if ($triggerrecord['triggeractions']['send']['trackopens'] == 0) {
						$tempMessage = 'TriggerEmails_Stats_Open_Error_NotOpenTracked';
					} elseif (array_key_exists('opens', $tempRestriction) && !empty($tempRestriction['opens'])) {
						$tempMessage = 'TriggerEmails_Stats_Open_Error_HasNotBeenOpened_CalendarProblem';
					}

					$GLOBALS['Error'] = GetLang($tempMessage);
					$tabs['open']['message'] = $this->ParseTemplate('ErrorMsg', true, false);
					unset($GLOBALS['Error']);


				// Set up open information otherwise
				} else {
					$tabs['open']['email_opens_total'] = $this->FormatNumber($record['processed_timeframe_emailopens_total']);
					$tabs['open']['email_opens_unique'] = $this->FormatNumber($record['processed_timeframe_emailopens_unique']);

					// ----- Most opens
						$tempMostOpens = $api->GetMostOpens($record['statid'], $this->CalendarRestrictions['opens']);
						$tempNow = getdate();

						if (isset($tempMostOpens['mth'])) {
							$tabs['open']['most_open_date'] = $this->Months[$tempMostOpens['mth']] . ' ' . $tempMostOpens['yr'];

						} elseif (isset($tempMostOpens['hr'])) {
							$tabs['open']['most_open_date'] = date(GetLang('Daily_Time_Display'),mktime($tempMostOpens['hr'], 1, 1, 1, 1, $tempNow['year']));

						} elseif (isset($tempMostOpens['dow'])) {
							$pos = array_search($tempMostOpens['dow'], array_keys($this->days_of_week));
							$tabs['open']['most_open_date'] = date(GetLang('Date_Display_Display'), strtotime("last " . $this->days_of_week[$pos]));

						} elseif (isset($tempMostOpens['dom'])) {
							$month = $tempNow['mon'];
							// if the day-of-month is after "today", it's going to be for "last month" so adjust the month accordingly.
							if ($tempMostOpens['dom'] > $tempNow['mday']) {
								$month = $tempNow['mon'] - 1;
							}

							$tabs['open']['most_open_date'] = date(GetLang('Date_Display_Display'),mktime(0, 0, 1, $month, $tempMostOpens['dom'], $tempNow['year']));
						}

						unset($tempNow);
						unset($tempMostOpens);
					// -----

					// ----- Average opens
						$tabs['open']['average_opens'] = 0;
						if ($record['processed_totalsent'] > 0) {
							$tempAverage = $record['processed_timeframe_emailopens_total'] / $record['processed_totalsent'];
							$tabs['open']['average_opens'] = $this->FormatNumber($tempAverage, 3);
							unset($tempAverage);
						}
					// -----

					// ----- Open rate
						$tabs['open']['open_rate'] = '0%';
						if ($record['processed_totalsent'] > 0) {
							$tempOpenRate = $record['processed_timeframe_emailopens_unique'] / $record['processed_totalsent'] * 100;
							$tabs['open']['open_rate'] = $this->FormatNumber($tempOpenRate, 2) . '%' ;
							unset($tempOpenRate);
						}
					// -----

					// Setup chart
					$this->DisplayChart('OpenChart', 'triggeremails', $record['statid'], 'column', array('graph_title' => GetLang('OpensChart')));
					$tabs['open']['open_chart'] = $GLOBALS['OpenChart'];
					unset($GLOBALS['OpenChart']);
				}
			// -----

			// ----- Tab 3: Links (TODO: when user chooses a specific link. Currently this is being ignored)
				$tabs['links']['intro'] = sprintf(GetLang('TriggerEmails_Stats_Links_Intro'), $record['triggeremailsname']);

				// setup calendar
				$GLOBALS['TabID'] = '2';
				$this->SetupCalendar('Action=ProcessCalendar&SubAction=TriggerEmails&NextAction=View&tab=3&id=' . $id);
				$tabs['links']['calendar'] = $GLOBALS['Calendar'];
				unset($GLOBALS['TabID']);
				unset($GLOBALS['Calendar']);

				// Set up error message if no "links" count is not available
				if (!array_key_exists('processed_timeframe_linkclicks_total', $record) || !$record['processed_timeframe_linkclicks_total']) {
					$tempMessage = 'TriggerEmails_Stats_Links_Error_NoLinksFound';
					$tempRestriction = $this->CalendarRestrictions;

					if ($triggerrecord['triggeractions']['send']['tracklinks'] == 0) {
						$tempMessage = 'TriggerEmails_Stats_Links_Error_NotLinkTracked';
					} elseif (array_key_exists('clicks', $tempRestriction) && !empty($tempRestriction['clicks'])) {
						$tempMessage = 'TriggerEmails_Stats_Links_Error_NoLinksFound_CalendarProblem';
					}

					$GLOBALS['Error'] = GetLang($tempMessage);
					$tabs['links']['message'] = $this->ParseTemplate('ErrorMsg', true, false);
					unset($GLOBALS['Error']);


				// Set up open information otherwise
				} else {
					$tabs['links']['linkclicks_total'] = $this->FormatNumber($record['processed_timeframe_linkclicks_total']);
					$tabs['links']['linkclicks_unique'] = $this->FormatNumber($record['processed_timeframe_linkclicks_unique']);
					$tabs['links']['linkclicks_individuals'] = $this->FormatNumber($record['processed_timeframe_linkclicks_individuals']);

					// ----- Most popular
						$most_popular_link = $api->GetMostPopularLink($record['statid'], 'a', $this->CalendarRestrictions['clicks']);
						$most_popular_link = htmlspecialchars($most_popular_link, ENT_QUOTES, SENDSTUDIO_CHARSET);

						$tabs['links']['most_popular_link'] = $most_popular_link;
						$tabs['links']['most_popular_link_short'] = $this->TruncateName($most_popular_link, 20);

						unset($most_popular_link);
					// -----

					// ----- Average clicks per-email-opens
						$tabs['links']['average_clicks'] = '0';
						if ($record['emailopens'] > 0) {
							$tabs['links']['average_clicks'] = $this->FormatNumber(($record['linkclicks'] / $record['emailopens']), 3);
						}
					// -----

					// ----- Clickthrough rate
						$tabs['links']['click_through'] = '0%';
						if ($record['processed_totalsent'] > 0) {
							$tempClickThroughRate = $record['processed_timeframe_linkclicks_unique'] / $record['processed_totalsent'] * 100;
							$tabs['links']['click_through'] = $this->FormatNumber($tempClickThroughRate, 2) . '%';
							unset($tempClickThroughRate);
						}
					// -----

					// Setup chart
					$this->DisplayChart('LinksChart', 'triggeremails', $record['statid'], 'column', array('graph_title' => GetLang('LinksClickedChart')));
					$tabs['links']['link_chart'] = $GLOBALS['LinksChart'];
					unset($GLOBALS['LinksChart']);
				}
			// -----

			// ----- Tab 4: Bounces (TODO: Cannot filter the bounce under soft/hard)
				$tabs['bounces']['intro'] = sprintf(GetLang('TriggerEmails_Stats_Bounces_Intro'), $record['triggeremailsname']);

				// setup calendar
				$GLOBALS['TabID'] = '3';
				$this->SetupCalendar('Action=ProcessCalendar&SubAction=TriggerEmails&NextAction=View&tab=4&id=' . $id);
				$tabs['bounces']['calendar'] = $GLOBALS['Calendar'];
				unset($GLOBALS['TabID']);
				unset($GLOBALS['Calendar']);

				// Set up error message if no "bounces" count is not available
				if (!array_key_exists('processed_timeframe_bounces', $record) || !$record['processed_timeframe_bounces']) {
					$tempMessage = 'TriggerEmails_Stats_Bounces_Error_NoBouncesFound';
					$tempRestriction = $this->CalendarRestrictions;

					if (array_key_exists('clicks', $tempRestriction) && !empty($tempRestriction['clicks'])) {
						$tempMessage = 'TriggerEmails_Stats_Links_Error_NoLinksFound_CalendarProblem';
					}

					$GLOBALS['Error'] = GetLang($tempMessage);
					$tabs['bounces']['message'] = $this->ParseTemplate('ErrorMsg', true, false);
					unset($GLOBALS['Error']);


				// Set up open information otherwise
				} else {
					$tabs['bounces']['bounces_total'] = $this->FormatNumber($record['processed_totalbounced']);
					$tabs['bounces']['bounces_soft'] = $this->FormatNumber(intval($record['bouncecount_soft']));
					$tabs['bounces']['bounces_hard'] = $this->FormatNumber(intval($record['bouncecount_hard']));
					$tabs['bounces']['bounces_unknown'] = $this->FormatNumber(intval($record['bouncecount_unknown']));

					// Setup chart
					$this->DisplayChart('BounceChart', 'triggeremails', $record['statid'], 'column', array('graph_title' => GetLang('BounceChart')));
					$tabs['bounces']['bounce_chart'] = $GLOBALS['BounceChart'];
					unset($GLOBALS['BounceChart']);
				}
			// -----

			// ----- Tab 5: Unsubscribe
				$tabs['unsubscribes']['intro'] = sprintf(GetLang('TriggerEmails_Stats_Unsubscribes_Intro'), $record['triggeremailsname']);

				// setup calendar
				$GLOBALS['TabID'] = '4';
				$this->SetupCalendar('Action=ProcessCalendar&SubAction=TriggerEmails&NextAction=View&tab=5&id=' . $id);
				$tabs['unsubscribes']['calendar'] = $GLOBALS['Calendar'];
				unset($GLOBALS['TabID']);
				unset($GLOBALS['Calendar']);

				// Set up error message if no "unsubscribes" count is not available
				if (!array_key_exists('processed_timeframe_unsubscribes', $record) || !$record['processed_timeframe_unsubscribes']) {
					$tempMessage = 'TriggerEmails_Stats_Unsubscribes_Error_NoUnsubscribesFound';
					$tempRestriction = $this->CalendarRestrictions;

					if (array_key_exists('bounces', $tempRestriction) && !empty($tempRestriction['bounces'])) {
						$tempMessage = 'TriggerEmails_Stats_Unsubscribes_Error_NoUnsubscribesFound_CalendarProblem';
					}

					$GLOBALS['Error'] = GetLang($tempMessage);
					$tabs['unsubscribes']['message'] = $this->ParseTemplate('ErrorMsg', true, false);
					unset($GLOBALS['Error']);


				// Set up open information otherwise
				} else {
					$tabs['unsubscribes']['unsubscribes_total'] = $this->FormatNumber($record['processed_timeframe_unsubscribes']);

					// ----- Most unsubscribe
						$tempMostUnsubscribes = $api->GetMostUnsubscribes($record['statid'], $this->CalendarRestrictions['unsubscribes']);
						$tempNow = getdate();

						if (isset($tempMostUnsubscribes['mth'])) {
							$tabs['unsubscribes']['unsubscribes_most'] = $this->Months[$tempMostUnsubscribes['mth']] . ' ' . $tempMostUnsubscribes['yr'];

						} elseif (isset($tempMostUnsubscribes['hr'])) {
							$tabs['unsubscribes']['unsubscribes_most'] = $this->PrintDate(mktime($tempMostUnsubscribes['hr'], 1, 1, 1, 1, $tempNow['year']), GetLang('Daily_Time_Display'));

						} elseif (isset($tempMostUnsubscribes['dow'])) {
							$pos = array_search($tempMostUnsubscribes['dow'], array_keys($this->days_of_week));
							// we need to add 1 hour here otherwise we get the wrong day from strtotime.
							$tabs['unsubscribes']['unsubscribes_most'] = $this->PrintDate(strtotime("last " . $this->days_of_week[$pos] . " +1 hour"), GetLang('Date_Display_Display'));

						} elseif (isset($tempMostUnsubscribes['dom'])) {
							$month = $tempNow['mon'];
							// if the day-of-month is after "today", it's going to be for "last month" so adjust the month accordingly.
							if ($tempMostUnsubscribes['dom'] > $tempNow['mday']) {
								$month = $tempNow['mon'] - 1;
							}

							$tabs['unsubscribes']['unsubscribes_most'] = $this->PrintDate(mktime(0, 0, 1, $month, $tempMostUnsubscribes['dom'], $tempNow['year']), GetLang('Date_Display_Display'));
						}

						unset($tempNow);
						unset($tempMostUnsubscribes);
					// -----

					// Setup chart
					$this->DisplayChart('UnsubscribeChart', 'triggeremails', $record['statid'], 'column', array('graph_title' => GetLang('UnsubscribesChart')));
					$tabs['unsubscribes']['unsubscribe_chart'] = $GLOBALS['UnsubscribeChart'];
					unset($GLOBALS['UnsubscribeChart']);
				}
			// -----

			// ----- Tab 6: Forwards
				$tabs['forwards']['intro'] = sprintf(GetLang('TriggerEmails_Stats_Forwards_Intro'), $record['triggeremailsname']);

				// setup calendar
				$GLOBALS['TabID'] = '5';
				$this->SetupCalendar('Action=ProcessCalendar&SubAction=TriggerEmails&NextAction=View&tab=6&id=' . $id);
				$tabs['forwards']['calendar'] = $GLOBALS['Calendar'];
				unset($GLOBALS['TabID']);
				unset($GLOBALS['Calendar']);

				// Set up error message if no "forwards" count is not available
				if (!array_key_exists('processed_timeframe_forwards', $record) || !$record['processed_timeframe_forwards']) {
					$tempMessage = 'TriggerEmails_Stats_Forwards_Error_NoForwardFound';
					$tempRestriction = $this->CalendarRestrictions;

					if (array_key_exists('forwards', $tempRestriction) && !empty($tempRestriction['forwards'])) {
						$tempMessage = 'TriggerEmails_Stats_Forwards_Error_NoForwardFound_CalendarProblem';
					}

					$GLOBALS['Error'] = GetLang($tempMessage);
					$tabs['forwards']['message'] = $this->ParseTemplate('ErrorMsg', true, false);
					unset($GLOBALS['Error']);


				// Set up open information otherwise
				} else {
					$tabs['forwards']['forward_total'] = $this->FormatNumber($record['processed_timeframe_forwards']);

					// ----- Total new Signups
						$temp = intval($api->GetForwards($record['statid'], 1, 'all', $this->CalendarRestrictions['forwards'], true, true));
						$tabs['forwards']['forward_signups'] = $this->FormatNumber($temp);
						unset($temp);
					// -----

					// Setup chart
					$this->DisplayChart('ForwardsChart', 'triggeremails', $record['statid'], 'column', array('graph_title' => GetLang('ForwardsChart')));
					$tabs['forwards']['forwards_chart'] = $GLOBALS['ForwardsChart'];
					unset($GLOBALS['ForwardsChart']);
				}
			// -----

			// ----- Tab 7: Contact info
				$tabs['recipients'] = $this->_TriggerEmailsStats_View_Tab7($record);
			// -----

			// ----- Tab 8: Failed sending info
				$tabs['failed'] = $this->_TriggerEmailsStats_View_Tab8($record);
			// -----



			// ----- Print HTML
				$tpl = GetTemplateSystem();
				$tpl->Assign('PAGE', $page);
				$tpl->Assign('record', $record);
				$tpl->Assign('tabs', $tabs);

				return $tpl->ParseTemplate('Stats_Triggeremails_Summary', true);
			// -----
		}
Example #8
0
	/**
	 * DbVersionCheck
	 * Checks if the database version is sufficient to upgrade and will not allow upgrades to continue if not.
	 *
	 * @return Void Does not return anything.
	 */
	function DbVersionCheck()
	{
		$db = IEM::getDatabase();
		$version = $db->Version();
		list($error, $msg) = IEM_Installer::DbVersionCheck(SENDSTUDIO_DATABASE_TYPE, $version);
		if (!$error) {
			return;
		}
		// See also admin/index.php for a similar message
		$tpl = GetTemplateSystem();
		$tpl->Assign('title', 'This Upgrade Cannot Proceed');
		$tpl->Assign('msg', '<p>Interspire Email Marketer requires ' . $msg['product'] . ' <em>' . $msg['req_version'] . '</em> or above to work properly. Your server is running <em>' . $msg['version'] . '</em>. To complete the installation, your web host must upgrade ' . $msg['product'] . ' to this version. Please note that this is not a software problem and it is something only your web host can change.</p>');
		$this->PrintHeader();
		$tpl->ParseTemplate('Upgrade_Body');
		$this->PrintFooter();
		exit();
	}
Example #9
0
	/**
	* PrintEditForm
	* Prints a form to edit a user. If you pass in a userid, it will load up that user and print their information. If you pass in the details array, it will prefill the form with that information (eg if you tried to create a user with a duplicate username). Also checks whether you are allowed to edit this user. If you are not an admin, you are only allowed to edit your own account.
	*
	* @param Int $userid Userid to load up.
	* @param Array $details Details to prefill the form with (in case there was a problem creating the user).
	*
	* @see User_API::Admin
	* @see User_API::Status
	* @see User_API::ListAdmin
	* @see User_API::EditOwnSettings
	* @see GetUser
	*
	* @return Void Returns nothing. If you don't have access to edit a particular user, it prints an error message and exits. Otherwise it prints the correct form (either edit-own or edit) and then exits.
	*/
	function PrintEditForm($userid = 0, $details = array())
	{
		$thisuser = IEM::getCurrentUser();
		if (!$thisuser->UserAdmin()) {
			if ($userid != $thisuser->userid) {
				$this->DenyAccess();
			}

			if (!$thisuser->EditOwnSettings()) {
				$this->DenyAccess();
			}
		}

		$user = $this->GetApi('User');

		$listapi = $this->GetApi('Lists');
		$all_lists = $listapi->GetLists(0, array('SortBy' => 'name', 'Direction' => 'asc'), false, 0, 0);

		$segmentapi = $this->GetApi('Segment');
		$all_segments = $segmentapi->GetSegments(array('SortBy' => 'segmentname', 'Direction' => 'asc'), false, 0, 'all');

		$templateapi = $this->GetApi('Templates');
		$all_templates = $templateapi->GetTemplates(0, array('SortBy' => 'name', 'Direction' => 'asc'), false, 0, 0);

		$all_groups = API_USERGROUPS::getRecords(false, false, 0, 0, 'groupname');

		$GLOBALS['CustomSmtpServer_Display'] = '0';

		$GLOBALS['XmlPath'] = SENDSTUDIO_APPLICATION_URL . '/xml.php';

		if ($userid > 0) {
			$user = GetUser($userid);
			if ($user->Get('userid') <= 0) {
				$GLOBALS['ErrorMessage'] = GetLang('UserDoesntExist');
				$this->DenyAccess();
				return;
			}
			$GLOBALS['UserID'] = $user->Get('userid');
			$GLOBALS['UserName'] = htmlspecialchars($user->Get('username'), ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['FullName'] = htmlspecialchars($user->Get('fullname'), ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['EmailAddress'] = htmlspecialchars($user->Get('emailaddress'), ENT_QUOTES, SENDSTUDIO_CHARSET);

			$activity = $user->GetEventActivityType();
			if (!is_array($activity)) {
				$activity = array();
			}
			$GLOBALS['EventActivityType'] = implode("\n", $activity);

			$GLOBALS['MaxLists'] = $user->group->limit_list;
			$GLOBALS['MaxEmails'] = $user->group->limit_totalemailslimit;
			$GLOBALS['PerMonth'] = $user->group->limit_emailspermonth;
			$GLOBALS['PerHour'] = $user->group->limit_hourlyemailsrate;


			$GLOBALS['DisplayMaxLists'] = '';
			if ($user->Get('maxlists') == 0) {
				$GLOBALS['LimitListsChecked'] = ' CHECKED';
				$GLOBALS['DisplayMaxLists'] = 'none';
			}

			$GLOBALS['DisplayEmailsPerHour'] = '';
			if ($user->Get('perhour') == 0) {
				$GLOBALS['LimitPerHourChecked'] = ' CHECKED';
				$GLOBALS['DisplayEmailsPerHour'] = 'none';
			}

			$GLOBALS['DisplayEmailsPerMonth'] = '';
			if ($user->Get('permonth') == 0) {
				$GLOBALS['LimitPerMonthChecked'] = ' CHECKED';
				$GLOBALS['DisplayEmailsPerMonth'] = 'none';
			}

			$GLOBALS['LimitMaximumEmailsChecked'] = ' CHECKED';
			$GLOBALS['DisplayEmailsMaxEmails'] = 'none';

			if (!$user->hasUnlimitedCredit()) {
				$GLOBALS['LimitMaximumEmailsChecked'] = '';
				$GLOBALS['DisplayEmailsMaxEmails'] = '';
			}

			if ($user->Get('usewysiwyg')) {
				$GLOBALS['UseWysiwyg'] = ' CHECKED';
				$GLOBALS['UseXHTMLDisplay'] = ' style="display:block;"';
			} else {
				$GLOBALS['UseXHTMLDisplay'] = ' style="display:none;"';
			}

			if ($user->Get('enableactivitylog')) {
				$GLOBALS['EnableActivityLog'] = ' CHECKED';
			} else {
				$GLOBALS['EnableActivityLog'] = '';
			}

			$GLOBALS['UseXHTMLCheckbox'] = $user->Get('usexhtml')? ' CHECKED' : '';

			$GLOBALS['Xmlapi'] = $user->Get('xmlapi')? ' CHECKED' : '';
			$GLOBALS['XMLTokenDisplay'] = ' style="display:none;"';

			if ($user->Get('xmlapi')) {
				$GLOBALS['XMLTokenDisplay'] = ' style="display:block;"';
			}
			$GLOBALS['XmlToken'] = htmlspecialchars($user->Get('xmltoken'), ENT_QUOTES, SENDSTUDIO_CHARSET);

			$GLOBALS['TextFooter'] = $user->Get('textfooter');
			$GLOBALS['HTMLFooter'] = $user->Get('htmlfooter');

			$GLOBALS['SmtpServer'] = $user->Get('smtpserver');
			$GLOBALS['SmtpUsername'] = $user->Get('smtpusername');
			$GLOBALS['SmtpPassword'] = $user->Get('smtppassword');
			$GLOBALS['SmtpPort'] = $user->Get('smtpport');

			if ($GLOBALS['SmtpServer']) {
				$GLOBALS['CustomSmtpServer_Display'] = '1';
			}

			$GLOBALS['googlecalendarusername'] = htmlspecialchars($user->Get('googlecalendarusername'), ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['googlecalendarpassword'] = htmlspecialchars($user->Get('googlecalendarpassword'), ENT_QUOTES, SENDSTUDIO_CHARSET);

			$GLOBALS['FormAction'] = 'Action=Save&UserID=' . $user->userid;

			if (!$thisuser->UserAdmin()) {

				$smtp_access = $thisuser->HasAccess('User', 'SMTP');

				$GLOBALS['ShowSMTPInfo'] = 'none';
				$GLOBALS['DisplaySMTP'] = '0';

				if ($smtp_access) {
					$GLOBALS['ShowSMTPInfo'] = '';
				}

				if ($GLOBALS['SmtpServer']) {
					$GLOBALS['CustomSmtpServer_Display'] = '1';
					if ($smtp_access) {
						$GLOBALS['DisplaySMTP'] = '1';
					}
				}

				$this->ParseTemplate('User_Edit_Own');
				return;
			}

			$GLOBALS['StatusChecked'] = ($user->Status()) ? ' CHECKED' : '';

			$GLOBALS['ForceDoubleOptInChecked'] = ($user->Get('forcedoubleoptin')) ? ' CHECKED' : '';
			$GLOBALS['ForceSpamCheckChecked'] = ($user->Get('forcespamcheck')) ? ' CHECKED' : '';
			$GLOBALS['InfoTipsChecked'] = ($user->InfoTips()) ? ' CHECKED' : '';

			$editown = '';
			if ($user->UserAdmin()) {
				$editown = ' CHECKED';
			} else {
				if ($user->EditOwnSettings()) {
					$editown = ' CHECKED';
				}
			}
			$GLOBALS['EditOwnSettingsChecked'] = $editown;

			$timezone = $user->usertimezone;

			$GLOBALS['TimeZoneList'] = $this->TimeZoneList($timezone);

			$admintype = $user->AdminType();
			$listadmintype = $user->ListAdminType();
			$segmentadmintype = $user->SegmentAdminType();
			$templateadmintype = $user->TemplateAdminType();

			$admin = $user->Admin();
			$listadmin = $user->ListAdmin();
			$segmentadmin = $user->SegmentAdmin();
			$templateadmin = $user->TemplateAdmin();

			$permissions = $user->Get('permissions');
			$area_access = $user->Get('access');

			$GLOBALS['Heading'] = GetLang('EditUser');
			$GLOBALS['Help_Heading'] = GetLang('Help_EditUser');

			$GLOBALS['AdminNotifyEmailAddress'] = $user->Get('adminnotify_email');
			if (empty($GLOBALS['AdminNotifyEmailAddress'])) {
				$GLOBALS['AdminNotifyEmailAddress'] = constant('SENDSTUDIO_EMAIL_ADDRESS');
			}

			$GLOBALS['AdminNotifications_Send_Email'] = $user->Get('adminnotify_send_emailtext');
			if (empty($GLOBALS['AdminNotifications_Send_Email'])) {
				$GLOBALS['AdminNotifications_Send_Email'] = GetLang('AdminNotifications_Send_Email');
			}

			$GLOBALS['AdminNotifications_Import_Email'] = $user->Get('adminnotify_import_emailtext');
			if (empty($GLOBALS['AdminNotifications_Import_Email'])) {
				$GLOBALS['AdminNotifications_Import_Email'] = GetLang('AdminNotifications_Import_Email');
			}

			$GLOBALS['SendLimit'] = $user->Get('adminnotify_send_threshold');
			$GLOBALS['ImportLimit'] = $user->Get('adminnotify_import_threshold');

			if (empty($GLOBALS['SendLimit'])) {
				$GLOBALS['SendLimit'] = 1000;
			}
			if (empty($GLOBALS['ImportLimit'])) {
				$GLOBALS['ImportLimit'] = 1000;
			}

			$admin_flag = $user->Get('adminnotify_send_flag');
			if ($user->Get('adminnotify_send_flag') == 1) {
				$GLOBALS['AdminNotificationsSend'] = 'CHECKED';
				$GLOBALS['UseNotifySend'] = '';
			} else {
				$GLOBALS['UseNotifySend'] = "style=display:none;";
			}
			if ($user->Get('adminnotify_import_flag') == 1) {
				$GLOBALS['AdminNotificationsImport'] = 'CHECKED';
				$GLOBALS['UseNotifyImport'] = '';
			} else {
				$GLOBALS['UseNotifyImport'] = "style=display:none;";
			}

			$GLOBALS['SmtpPort'] = $user->Get('smtpport');


			// Log this to "User Activity Log"
			IEM::logUserActivity(IEM::urlFor('users', array('Action' => 'Edit', 'UserID' => $userid)), 'images/user.gif', $user->username);

		} else {
			$timezone = (isset($details['timezone'])) ? $details['timezone'] : SENDSTUDIO_SERVERTIMEZONE;
			$GLOBALS['TimeZoneList'] = $this->TimeZoneList($timezone);

			$activity = $thisuser->defaultEventActivityType;
			if (!is_array($activity)) {
				$activity = array();
			}
			$GLOBALS['EventActivityType'] = implode("\n", $activity);

			$GLOBALS['FormAction'] = 'Action=Create';

			if (!empty($details)) {
				foreach ($details as $area => $val) {
					$GLOBALS[$area] = $val;
				}
			}
			$GLOBALS['Heading'] = GetLang('CreateUser');
			$GLOBALS['Help_Heading'] = GetLang('Help_CreateUser');

			$listadmintype = 'c';
			$segmentadmintype = 'c';
			$admintype = 'c';
			$templateadmintype = 'c';

			$GLOBALS['DisplayMaxLists'] = 'none';
			$GLOBALS['DisplayEmailsPerHour'] = 'none';
			$GLOBALS['DisplayEmailsPerMonth'] = 'none';
			$GLOBALS['DisplayEmailsMaxEmails'] = 'none';

			$GLOBALS['MaxLists'] = '0';
			$GLOBALS['PerHour'] = '0';
			$GLOBALS['PerMonth'] = '0';
			$GLOBALS['MaxEmails'] = '0';

			$GLOBALS['StatusChecked'] = ' CHECKED';
			$GLOBALS['ForceDoubleOptInChecked'] = '';
			$GLOBALS['ForceSpamCheckChecked'] = '';
			$GLOBALS['InfoTipsChecked'] = ' CHECKED';
			$GLOBALS['EditOwnSettingsChecked'] = ' CHECKED';

			$GLOBALS['LimitListsChecked'] = ' CHECKED';
			$GLOBALS['LimitPerHourChecked'] = ' CHECKED';
			$GLOBALS['LimitPerMonthChecked'] = ' CHECKED';
			$GLOBALS['LimitMaximumEmailsChecked'] = ' CHECKED';

			$GLOBALS['UseWysiwyg'] = ' CHECKED';
			$GLOBALS['EnableLastViewed'] = '';
			$GLOBALS['UseXHTMLCheckbox'] = ' CHECKED';

			$GLOBALS['HTMLFooter'] = GetLang('Default_Global_HTML_Footer');
			$GLOBALS['TextFooter'] = GetLang('Default_Global_Text_Footer');

			$GLOBALS['EnableActivityLog'] = ' CHECKED';

			$GLOBALS['Xmlapi'] = '';
			$GLOBALS['XMLTokenDisplay'] = ' style="display:none;"';

			$admin = $listadmin = $segmentadmin = $templateadmin = false;
			$permissions = array();
			$area_access = array('lists' => array(), 'templates' => array(), 'segments' => array());

			$GLOBALS['AdminNotifyEmailAddress'] = constant('SENDSTUDIO_EMAIL_ADDRESS');
			$GLOBALS['UseNotifySend'] = "style=display:none;";
			$GLOBALS['UseNotifyImport'] = "style=display:none;";

			$GLOBALS['SendLimit'] = 1000;
			$GLOBALS['ImportLimit'] = 1000;
			$GLOBALS['AdminNotifications_Send_Email'] = GetLang('AdminNotifications_Send_Email');
			$GLOBALS['AdminNotifications_Import_Email'] = GetLang('AdminNotifications_Import_Email');

		}

		$agencyid = defined('IEM_SYSTEM_LICENSE_AGENCY') ? IEM_SYSTEM_LICENSE_AGENCY : '';
		$available_users = $user->AvailableUsers();

		$template = GetTemplateSystem();
        
		$template->Assign('UserID', $user->userid);
		$template->Assign('groupid', $user->groupid);
		$template->Assign('canChangeUserGroup', !$user->isLastAdmin());
		$template->Assign('AgencyEdition', get_agency_license_variables());
		$template->Assign('EditOwn', ($user->userid != 0 && $user->userid == $thisuser->userid));
		$template->Assign('TrialUser', $user->trialuser);
		$template->Assign('EditMode', !empty($user->userid));
		$template->Assign('AvailableNormalUsers', isset($available_users['normal']) ? $available_users['normal'] : 0);
		$template->Assign('AvailableTrialUsers', isset($available_users['trial']) ? $available_users['trial'] : 0);
		$template->Assign('AvailableGroups', $all_groups);
		$template->Assign('record_groupid', $user->groupid);
		$template->Assign('DefaultIdTab', IEM::requestGetPOST('id_tab_num', 1, 'intval'));
		$template->Assign('showSmtpInfo', (bool) $user->smtpserver);

		$template->ParseTemplate('User_Form');
	}
Example #10
0
	/**
	* Process
	* This processes the ajax requests.
	* There are only two types of request - importfile and importurl.
	*
	* If it's importfile, it will display the 'fileupload' iframe again, and also process the file if there was one uploaded. It base 64 encodes the data to pass to javascript, this saves having to worry about newlines, quotes and so on. The javascript decodes it itself, then calls the DoImport function in the includes/js/javascript.js file.
	*
	* If it's importurl, it simply calls GetPageContents and returns that.
	*
	* @see GetPageContents
	*
	* @return Void Doesn't return anything, simply prints out the results.
	*/
	function Process()
	{
		// make sure they are logged in appropriately.
		if (!IEM::getCurrentUser()) {
			return;
		}

		$GLOBALS['ImportType'] = 'HTML';
		if (isset($_GET['ImportType']) && strtolower($_GET['ImportType']) == 'text') {
			$GLOBALS['ImportType'] = 'Text';
		}

		if (isset($_GET['DisplayFileUpload'])) {
			$this->ParseTemplate('Editor_FileUpload');
			return;
		}

		$user = GetUser();

		if (isset($_POST['what'])) {
			$what = $_POST['what'];

			switch (strtolower($what)) {
				case 'check_existing':
					// this is used when editing an autoresponder and you check the "send to existing" box.
					// it will alert you if you have sent this autoresponder to any recipients before
					// so you're aware that they will receive it again.

					$autoresponder_id = (isset($_POST['auto'])) ? (int)$_POST['auto'] : 0;
					if ($autoresponder_id <= 0) {
						exit;
					}

					$this->LoadLanguageFile('autoresponders');

					require_once(SENDSTUDIO_API_DIRECTORY . '/autoresponders.php');
					$auto_api = new Autoresponders_API();

					$userid = $user->userid;

					// If user is an admin, omit the userid so that it won't get checked
					if ($user->Admin()) {
						$userid = 0;
					}

					$already_sent_to = $auto_api->GetRecipientCount($autoresponder_id, $userid);
					if (!$already_sent_to) {
						exit;
					}

					if ($already_sent_to > 0) {
						$msg = sprintf(GetLang('AutoresponderAlreadySentTo'), $this->FormatNumber($already_sent_to));
						echo $msg;
					}
					exit;
				break;

				case 'importlinks':
					$listid = false;
					$processing_list = IEM::sessionGet('LinksForList');
					if ($processing_list) {
						$listid = (int)$processing_list;
					}

					$links = $user->GetAvailableLinks($listid);

					$link_list = 'mylinks[-1]=\'' . GetLang('FilterAnyLink') . '\';' . "\n";
					foreach ($links as $linkid => $url) {
						$link_list .= 'mylinks[' . $linkid . ']=\'' . addslashes($url) . '\';' . "\n";
					}
					echo $link_list;
				break;

				case 'importnewsletters':
					$listid = false;

					$processing_list = IEM::sessionGet('NewsForList');
					if ($processing_list) {
						$listid = (int)$processing_list;
					}

					$news = $user->GetAvailableNewsletters($listid);

					$news_list = 'mynews[-1]=\'' . GetLang('FilterAnyNewsletter') . '\';' . "\n";
					foreach ($news as $newsid => $name) {
						$news_list .= 'mynews[' . $newsid . ']=\'' . addslashes($name) . '\';' . "\n";
					}
					echo $news_list;
				break;

				case 'importfile':
					if (!empty($_FILES['newsletterfile'])) {
						if (is_uploaded_file($_FILES['newsletterfile']['tmp_name'])) {
							$page = file_get_contents($_FILES['newsletterfile']['tmp_name']);

							$page = self::ScrubPage($page);

							header('Content-type: text/html;');

							?>
							<script>
								parent.ajaxData = '<?php echo addcslashes($page,"'\\\n\r"); ?>';
								parent.DoImport('file', '<?php echo $GLOBALS['ImportType']; ?>');
							</script>
							<?php
						}
					}
					$this->ParseTemplate('Editor_FileUpload');
				break;

				case 'importurl':
					$url = false;
					if (isset($_POST['url'])) {
						$url = $_POST['url'];
					}
					list($page, $statusmsg) = $this->GetPageContents($url);
					if ($page) {
						// if there is a base href, don't worry about converting the links and images.
						// the email class does this when it sends the content.
						if (preg_match('%base href=%is', $page)) {
							echo $page;
							break;
						}

						$page = self::ScrubPage($page);

						/**
						* $url starts off as something like http://www.domain.com/path/index.html
						*
						* Grab the scheme & hostname from the url.
						*/
						$urlparts = parse_url($url);
						$baseurl = $urlparts['scheme'] . '://';
						$baseurl .= $urlparts['host'];

						/**
						* If there is a path (eg '/path/index.html'), break it up into sections.
						*
						* Then if there is an extension to the path, we assume it's a file (the extension in this case is 'html').
						*
						* So we need to take the basename of the file (/path) and add that to our url.
						*
						* If the url starts off as http://www.domain.com/path/
						* there will be no extension for '/path' so we assume it's a directory
						* So that means we have to add the 'basename' of the url ('/path') to the base url.
						*
						* If the url starts off as http://www.domain.com then there will be no path to worry about at all,
						* so we can skip that whole section
						*
						*/
						if (isset($urlparts['path'])) {
							$path_parts = pathinfo($urlparts['path']);
							$baseurl .= $path_parts['dirname'];

							if (!isset($path_parts['extension'])) {
                                $baseurl .= '/'.$path_parts['basename'];
							}
						}

						// Remove trailing '\' from base URL
						$baseurl = preg_replace('/(%5c|\\\\)$/i', '', $baseurl);

						// make sure the baseurl always has a '/' on the end - ie we need to point to a directory not a file.
						if (substr($baseurl, -1) != '/') {
							$baseurl .= '/';
						}

						// Modified to parse HTML and find src and href, and convert it into an absolute resource link
						$pattern = '~(?<=src=["\']|href=["\']|link=["\']|background=["\']|url\()(?![a-z0-9]*?\://|\%\%|mailto\:|#|javascript\:|news\:)(.*?)(?=["\'])~i';
						$page = preg_replace($pattern, "{$baseurl}\$1", $page);

						/**
						* Clean up links that started out looking like
						* http://host/path/to/file.ext
						* and ended up looking like
						* http://host/path/to//path/to/file.ext
						*/
						if (isset($path_parts['dirname'])) {
							$path = $path_parts['dirname'];
							if (strlen($path) > 1) {
								$page = str_replace($path . '/' . $path, $path, $page);
							}
						}

						/**
						* Clean up the urls so they don't have double slashes or '/./' in them.
						*/
						$page = str_replace(array('/./', '//'), '/', $page);

						/**
						* However that breaks our scheme (http or https) so we need to re-fix those again.
						*/
						$page = str_replace(array('http:/', 'https:/'), array('http://', 'https://'), $page);

						echo $page;
					}
				break;

				case 'save_version':
					// Only admin user can save "version"
					if (!$user->Admin()) {
						exit();
					}

					$lines = array();

					if (isset($_POST['latest'])) {
						$lines[] = 'latest=' . $_POST['latest'];
					}

					if (isset($_POST['feature'])) {
						$lines[] = 'feature=' . $_POST['feature'];
					}

					if (isset($_POST['latest_critical'])) {
						$lines[] = 'latest_critical=' . (int)$_POST['latest_critical'];
					}

					if (isset($_POST['feature_critical'])) {
						$lines[] = 'feature_critical=' . (int)$_POST['feature_critical'];
					}

					$fp = fopen(IEM_STORAGE_PATH . '/.version', 'w');
					if ($fp) {
						foreach ($lines as $line) {
							$line .= "\r\n";
							fputs($fp, $line);
						}
						fclose($fp);
					}
				break;

				case 'googlecalendar':
					$this->LoadLanguageFile('Subscribers');
					if (strlen($user->googlecalendarusername) && strlen($user->googlecalendarpassword)) {
						if (isset($_POST['google']) && is_array($_POST['google'])) {
							$google = $_POST['google'];
							$google['username'] = $user->googlecalendarusername;
							$google['password'] = $user->googlecalendarpassword;
							if (isset($google['allday']) && $google['allday']) {
								IEM::sessionSet('gcal_allday',true);
							} else {
								IEM::sessionSet('gcal_allday',false);
							}

							try {
								$this->GoogleCalendarAdd($google);
								echo 'top.tb_remove();';
							} catch (GoogleCalendarException $e) {
								switch ($e->getCode()) {
									case GoogleCalendarException::BADAUTH;
										echo 'alert("' . GetLang('GoogleCalendarAuth') . '");';
									break;
									default:
										echo 'alert("' . GetLang('GoogleCalendarException') . '");';
										echo "//" . $e->getMessage();
								}

							}
						}
					}
				break;
				case 'imagemanagerrename':
					$api = $this->GetApi('ImageManager');

					// lets get the extension from the old filename
					$ext = substr(strrchr($_POST['fromName'], "."), 0);
					$_POST['toName'] = $_POST['toName'] . $ext;

					$return = array();
					if(strpos($_POST['toName'], '/') !== false || strpos($_POST['toName'], '\\') !== false ){
						$return['success'] = false;
						$return['message'] = GetLang('ImageManagerRenameInvalidFileName');
						die(json_encode($return));
					}

					if(!$this->IsImageFile($_POST['toName'])){
						$return['success'] = false;
						$return['message'] = GetLang('ImageManagerRenameInvalidFileName');
						die(json_encode($return));
					}
					if(!file_exists($api->GetImagePath() . '/' . $_POST['fromName'])){
						$return['success'] = false;
						$return['message'] = GetLang('ImageManagerFileDoesntExistRename');
						die(json_encode($return));
					}

					if(file_exists($api->GetImagePath() . '/' . $_POST['toName'])){
						$return['success'] = false;
						$return['message'] = GetLang('ImageManagerRenameFileAlreadyExists');
						die(json_encode($return));
					}

					if(!@rename($api->GetImagePath() . '/' . $_POST['fromName'], $api->GetImagePath() . '/' . $_POST['toName'])){
						if(isset($php_errormsg)){
							$msgBits = explode(':', $php_errormsg);
							if(isset($msgBits[1])){
								$message =  $msgBits[1] . '.';
							}else{
								$message =  $php_errormsg  . '.';
							}
						}else{
							$message = 'Unknown error.';
						}
						$return['success'] = false;
						$return['message'] = $message;
						die(json_encode($return));
					}

					$return['success'] = true;
					$newName = $_POST['toName'];
					$newName = substr($newName, 0, strrpos($newName, "."));
					$return['newname'] = strtolower(htmlspecialchars($newName));
					$return['newrealname'] = strtolower(htmlspecialchars($_POST['toName']));
					$return['newurl'] = $api->GetImageDir() . urlencode(strtolower($_POST['toName']));
					echo json_encode($return);
					die();
				break;
				case 'imagemanagerdelete':

					$api = $this->GetApi('ImageManager');
					$successImages = $errorFiles = $return = array();

					if(!is_array($_POST['deleteimages']) || empty($_POST['deleteimages'])) {
						$return['success'] = false;
						$return['message'] = GetLang('ImageManagerNoImagesSelectedDelete');
						die(json_encode($return));
					}

					foreach($_POST['deleteimages'] as $k=>$image) {
						if(file_exists($api->GetImagePath() . '/' . $image)){
							if(!@unlink($api->GetImagePath() . '/' . $image)) {
								if(isset($php_errormsg)){
									$msgBits = explode(':', $php_errormsg);
									if(isset($msgBits[1])){
										$errorFiles =  $msgBits[1] .'.';
									}else{
										$errorFiles =  $php_errormsg  .'.';
									}
								}else{
									$errorFiles[] = GetLang('ImageManagerUnableDeleteError') . ' ' . $image;
								}
								unset($php_errormsg);
							}else{
								$ext = strrchr($image, '.');
								if($ext !== false) {
									$image = substr($image, 0, -strlen($ext));
								}
								$successImages[] = $image;
							}
						}
					}
					if(!empty($errorFiles)){
						$return['success'] = false;
						$return['message'] = GetLang('ImageManagerDeleteErrors') . $this->ArrayToList($errorFiles);
						die(json_encode($return));
					}

					$return['success'] = true;
					$return['successimages'] = $successImages;
					if(count($successImages) == 1){
						$return['message'] = GetLang('ImageManagerDeleteSuccessSingle');
					}elseif(count($successImages) > 1){
						$return['message'] = sprintf(GetLang('ImageManagerDeleteSuccessMulti'), count($successImages));
					}
					echo json_encode($return);
					die();
				break;
				case 'imagemanagerimagenumshown':
					$api = $this->GetApi('ImageManager');
					$api->Init();
					$return['text'] = $api->GetImageNumberShownText();
					echo json_encode($return);
				break;
				case 'imagemanagermanage':
					$api = $this->GetApi('ImageManager');
					$settingApi = $this->GetApi('settings');
					$GLOBALS['imgLocation'] = $api->GetImageDir();

					// Sorting of the images
					$validSort = array("name.asc", "name.desc", "modified.desc", "modified.asc", "size.asc", "size.desc");
					$sortby = '';
					if(isset($_GET['SortBy'])){
						$sortby = $_GET['SortBy'];
						$sortBits = explode('.', $sortby);
						$_GET['SortBy'] = $sortBits[0];
						$_GET['Direction'] = $sortBits[1];
					}

					$perpage = $this->GetPerPage();
					$DisplayPage = $this->GetCurrentPage();
					$start = 0;
					$sortinfo = $this->GetSortDetails();


					// if sorting field and direction is defined
					if (isset($sortinfo['Direction']) && isset($sortinfo['SortBy'])) {
						$sortby = $sortinfo['SortBy'].'.'.$sortinfo['Direction'];
					}

					// Default sorting field and direction
					if(empty($sortby) || !in_array($sortby, $validSort, true)){
						$sortby = 'name.asc';
						list($sortinfo['SortBy'], $sortinfo['Direction']) = explode('.', $sortby);
					}

					// Init the images sorting field and direction
					$api->Init($sortinfo['Direction'], $sortinfo['SortBy']);

					// Pagination setup
					$GLOBALS['SortList'] = '';
					foreach ($validSort as $eachSort) {
						$eachSortBits = explode('.', $eachSort);
						$displayText = GetLang('Sort'.ucwords($eachSortBits[0]).ucwords($eachSortBits[1]));
						$sel = '';
						if ($eachSort == $sortby) {
							$sel = ' SELECTED ';
						}
						$GLOBALS['SortList'] .= '<option value="'.$eachSort.'" '.$sel.'>' . $displayText . '</option> ';
					}
					if (strtolower($perpage) != 'all') {
						$api->start = ($perpage * $DisplayPage) - $perpage;
						$api->finish = ($perpage * $DisplayPage);
					}

					$NumberOfImages = ($api->CountDirItems())?$api->CountDirItems():1;

					$this->SetupPaging($NumberOfImages, $DisplayPage, $perpage);
					$GLOBALS['FormAction'] = 'Action=ProcessPaging';
					$paging = $this->ParseTemplate('Paging', true);
					$GLOBALS['dirImages'] = '';
					$dirImages = $api->GetImageDirFiles();

					$GLOBALS['Intro_Help'] = GetLang('Help_ImageManagerManage');
					$GLOBALS['Intro'] = GetLang('ImageManagerManage');
					$GLOBALS['NumImageShown'] = $api->GetImageNumberShownText();

					$GLOBALS['ImageManager_AddButton'] = '<input id="btnUpload" type="button" value="'.GetLang('ImageManagerUploadImages').'" class="SmallButton" />';
					$showDeleteBtn = "display:none";
					if ($api->CountDirItems()) {
						$showDeleteBtn = "";
						foreach ($dirImages as $dirImage) {
                            $GLOBALS['dirImages'] .= "AdminImageManager.AddImage( '".addslashes($dirImage['name'])."', '".addslashes($dirImage['url'])."', '".$dirImage['size']." Bytes', '".$dirImage['width']."', '".$dirImage['height']."', '".$dirImage['origwidth']." X ".$dirImage['origheight']."', '".$dirImage['id']."'); ";							$GLOBALS['DisplayImagePanel'] = 'block';
						}
					} else {
						$GLOBALS['DisplayImagePanel'] = 'none';
						$GLOBALS['Message'] = $GLOBALS['Message'] = $this->PrintSuccess('NoImage');
					}
					$GLOBALS['ImageManager_DeleteButton'] = '<input id="deleteButton" type="button" value="'.GetLang('DeleteSelected').'"  class="SmallButton" style="'.$showDeleteBtn.';" />';

					$tpl = GetTemplateSystem();
					$tpl->Assign('SessionName', IEM::SESSION_NAME);
					$tpl->Assign('Pagination', $paging);
					$tpl->Assign('SessionID', IEM::sessionID());
					echo $tpl->ParseTemplate('Image_Manager_Sub');
				break;
			}
		}
	}
Example #11
0
	/**
	 * ChekContentForSpam
	 * Function to check for spam keywords within an email.
	 * This function is called by an Ajax request.
	 *
	 * @param string $text The text content of the email.
	 * @param string $html The HTML content of the email.
	 *
	 * @see self::CheckContentForSpamDisplay
	 * @see Application.Modules.SpamCheck
	 *
	 * @return Void Returns nothing, it displays the contents of the spam check frame.
	 */
	function CheckContentForSpam($text, $html)
	{
		$tpl = GetTemplateSystem();
		$spam_api = $this->GetApi('Spam_Check');
		$result = $spam_api->Process($text, $html);

		$types = array();
                if ($html) {
                    array_push($types, 'html');
                }
                if ($text) {
                   array_push($types, 'text');
                }

		foreach ($types as $type) {

                    $rating = $result[$type]['rating'];
                    $score = $result[$type]['score'];
                    $broken_rules = $result[$type]['broken_rules'];

                    if (empty($broken_rules)) {
                            if (${$type} !== false) {
                                    $tpl->Assign('spam_heading', GetLang('Spam_Heading_intro_notspam_' . $type));
                                    $tpl->ParseTemplate('Spam_Check_Row_Not_Broken');
                            }
                            continue;
                    }
                    $tpl->Assign('spam_heading', GetLang('Spam_Heading_intro_' . $type));
                    $tpl->ParseTemplate('Spam_Check_SubHeader');

                    foreach ($broken_rules as $details) {
                            $tpl->Assign('rule_broken', $details[0]);
                            $tpl->Assign('rule_score', $this->FormatNumber($details[1], 1));
                            $tpl->ParseTemplate('Spam_Check_Row');
                    }

                    $is_spam = 0;
                    switch ($rating) {
                            case Spam_Check_API::RATING_SPAM:
                                    $display_style = 'spam';
                                    $is_spam = 1;
                                    break;
                            case Spam_Check_API::RATING_ALERT:
                                    $display_style = 'alert';
                                    break;
                            case Spam_Check_API::RATING_NOT_SPAM:
                                    $display_style = 'notspam';
                                    break;
                            default:
                                    $display_style = '';
                    }

                    $score_percent = number_format((($score / Spam_Check_API::RATING_SPAM) * 100), 0);
                    if ($score_percent > 100) {
                            $score_percent = 100;
                    }

                    $tpl->Assign('spam_percentage', $score_percent);
                    $tpl->Assign('spam_display_style', $display_style);
                    $tpl->Assign('spam_rating_message', sprintf(GetLang('Spam_Rating_Message'), $score, Spam_Check_API::RATING_SPAM, GetLang('Spam_Rating_' . $display_style)));
                    $tpl->Assign('is_spam', $is_spam);
                    $tpl->Assign('type', $type);

                    $tpl->ParseTemplate('Spam_Check_SubFooter');
                    if ($type == 'html') {
                            $tpl->ParseTemplate('Spam_Check_Row_Empty');
                    }

		}
	}
Example #12
0
	/**
	 * _getEditor
	 * This will return an HTML of the editor page
	 *
	 * @param Array $parameters Any parameters that need to be parsed to this function
	 * @param Array $record Record that should be displayed as the default value for the form (for editing purpose)
	 * @return String Returns HTML string of the page
	 *
	 * @uses SendStudio_Functions::GetApi()
	 * @uses User_API::AdminType()
	 * @uses User_API::GetLists()
	 * @uses User_API::GetLiveNewsletters()
	 * @uses User_API::GetAvailableLinks()
	 * @uses GetLang()
	 * @uses GetFlashMessages()
	 * @uses TriggerEmails::_getDateCustomFieldUsedByList()
	 * @uses GetTemplateSystem()
	 * @uses InterspireTemplate::Assign()
	 * @uses InterspireTemplate::ParseTemplate()
	 */
	private function _getEditor($parameters, $record = array())
	{
		$newslettrAPI = $this->GetApi('Newsletters');
		$customfieldAPI = $this->GetApi('CustomFields');

		$newsletterowner = ($parameters['user']->Admin() || $parameters['user']->AdminType() == 'n') ? 0 : $parameters['user']->userid;
		$availableLists = $parameters['user']->GetLists();
		$availableNewsletters = $newslettrAPI->GetLiveNewsletters($newsletterowner);
		$availableLinks = array();
		$availableCustomFields = array();
		$availableNameCustomFields = array();
		$allowEmbedImages = SENDSTUDIO_ALLOW_EMBEDIMAGES;
		$allowSetBounceDetails =  $parameters['user']->HasAccess('Lists', 'BounceSettings');
		$options = array();
		$page = array(
			'heading'	=> GetLang('TriggerEmails_Create'),
			'messages'	=> $parameters['message']
		);

		if (!empty($record)) {
			$page['heading'] = GetLang('TriggerEmails_Edit');

			if ($record['triggertype'] == 'l' && isset($record['data']['linkid_newsletterid'])) {
				$temp = $this->_getLinksFormNewsletter($record['data']['linkid_newsletterid']);
				if (is_array($availableLinks)) {
					$availableLinks[$record['data']['linkid_newsletterid']] =  $temp;
				}
			}
		} else {
			// Default values
			$record['active'] = 1;
			$record['triggeractions']['send']['enabled'] = 0;
			$record['triggeractions']['send']['sendfromname'] = $parameters['user']->fullname;
			$record['triggeractions']['send']['sendfromemail'] = $parameters['user']->emailaddress;
			$record['triggeractions']['send']['replyemail'] = $parameters['user']->emailaddress;
			$record['triggeractions']['send']['bounceemail'] = SENDSTUDIO_BOUNCE_ADDRESS;
			$record['triggeractions']['send']['multipart'] = 1;
			$record['triggeractions']['send']['trackopens'] = 1;
			$record['triggeractions']['send']['tracklinks'] = 1;
			$record['triggeractions']['send']['embedimages'] = SENDSTUDIO_DEFAULT_EMBEDIMAGES;
		}

		// ----- Get available "date" and "text" custom fields, and set up the currently available custom fields in the options (if it is in edit mode)
			$tempCustomFields = $customfieldAPI->GetCustomFieldsForLists(array_keys($availableLists), null, array('date', 'text'));
			foreach ($tempCustomFields as $each) {
				if (!array_key_exists($each['listid'], $availableCustomFields)) {
					$availableCustomFields[$each['listid']] = array(
						'date' => array(),
						'text' => array()
					);
				}

				$availableCustomFields[$each['listid']][$each['fieldtype']][$each['fieldid']] = $each;
			}

			if (!empty($availableCustomFields) && isset($record['data']['listid'])  && array_key_exists($record['data']['listid'], $availableCustomFields)) {
				$availableNameCustomFields = $availableCustomFields[$record['data']['listid']]['text'];
			}
			unset($tempCustomFields);
		// -----

		/**
		 * Return HTML
		 */
			$tpl = GetTemplateSystem();
			$tpl->Assign('PAGE', $page);
			$tpl->Assign('record', $record);
			$tpl->Assign('options', $options);
			$tpl->Assign('availableLists', $availableLists);
			$tpl->Assign('availableNewsletters', $availableNewsletters);
			$tpl->Assign('availableLinks', $availableLinks);
			$tpl->Assign('availableCustomFields', $availableCustomFields);
			$tpl->Assign('availableNameCustomFields', $availableNameCustomFields);
			$tpl->Assign('allowEmbedImages', $allowEmbedImages);
			$tpl->Assign('allowSetBounceDetails', $allowSetBounceDetails);

			return $tpl->ParseTemplate('TriggerEmails_Form', true);
		/**
		 * -----
		 */
	}
Example #13
0
	function PrintRecentLists($countOnly = false) {

		$user = GetUser();
		$perpage = 5;
		$start = 0;
		$DisplayPage = 1;
		$sortinfo['SortBy'] = 'date';
		$sortinfo['Direction'] = 'DESC';

		$all_lists = $user->GetLists();
		$check_lists = array_keys($all_lists);

		$listapi = $this->GetApi('Lists');

		$NumberOfLists = count($check_lists);

		if ($countOnly) {
			return $NumberOfLists;
		}

		// If we're a list admin, no point checking the lists - we have access to everything.
		if ($user->ListAdmin()) {
			$check_lists = null;
		}

		$mylists = $listapi->GetLists($check_lists, $sortinfo, false, $start, $perpage);

		if ($NumberOfLists == 0) {
			$tpl = GetTemplateSystem();
			$page['message']=GetLang('GettingStarted_NoContactList');
			$tpl->Assign('page', $page);
			echo $tpl->ParseTemplate('index_campaign_noitem', true);
			exit;
		}

		$this->SetupPaging($NumberOfLists, $DisplayPage, $perpage);
		$GLOBALS['FormAction'] = 'Action=ProcessPaging';
		$paging = $this->ParseTemplate('Paging', true, false);

		foreach ($mylists as $pos => $listinfo) {
			$list['Name'] = htmlspecialchars($listinfo['name'], ENT_QUOTES, SENDSTUDIO_CHARSET);
			$list['Created'] = $this->PrintDate($listinfo['createdate']);

			$list['SubscriberCount'] = $this->FormatNumber($listinfo['subscribecount']);

			$list['ListID'] = $listinfo['listid'];
			$list['NameShort'] = $this->TruncateName($list['Name'], 30);
			if ($user->HasAccess('Lists', 'Edit', $listinfo['listid'])) {
				$editList = 'index.php?Page=Lists&Action=Edit&id='.$list['ListID'];
				$manageContacts = $list['SubscriberCount'].' '.GetLang('GettingStarted_Contacts');
				if ($list['SubscriberCount'] > 0) {
					$manageContacts = '<a href="index.php?Page=Subscribers&Action=Manage&Lists[]='.$list['ListID'].'">'.$list['SubscriberCount'].' '.GetLang('GettingStarted_Contacts').'</a>';
				}
				echo '<li><a class="ListLink" href="' . $editList . '" title="' . GetLang('Edit'). ' - ' . $list['Name'] . '">' . $list['NameShort'] . '</a> - ('.$manageContacts.')</li>';
			} else {
				echo '<li>' . $list['NameShort'] . ' - ('.$list['SubscriberCount'].' '.GetLang('GettingStarted_Contacts').')</li>';
			}
		}
	}
Example #14
0
	/**
	 * showHelp
	 * Displays a help message, to be placed within a thickbox window.
	 *
	 * @param string $topic The topics to display.
	 *
	 * @return boolean Returns false on error, otherwise true.
	 */
	private static function showHelp($topic)
	{
		$questions = array(
			'list_group' => 'WhyListsGrouped',
			'auto_explain' => 'Bounce_Auto_Process_Why',
			'manual_explain' => 'Bounce_Manual_Process_Why',
		);
		$answers = array(
			'list_group' => 'Bounce_Why_Group_Lists',
			'auto_explain' => 'Bounce_Why_Use_Auto',
			'manual_explain' => 'Bounce_Why_Not_Manual',
		);
		if (!array_key_exists($topic, $questions)) {
			return false;
		}
		$tpl = GetTemplateSystem();
		$tpl->Assign('heading', GetLang($questions[$topic], true));
		$tpl->Assign('message', GetLang($answers[$topic], true));
		$tpl->ParseTemplate('Help_PopUp');
		return true;
	}
Example #15
0
 /**
  * GetTemplateSystem
  *
  * Sets the local template_system variable for child addons to use and process templates.
  *
  * @uses template_system
  * @uses GetTemplateSystem
  *
  * @return Void Doesn't return anything, just sets the local template_system variable.
  */
 protected function GetTemplateSystem()
 {
     $template_dir = null;
     if ($this->addon_id !== null && $this->addon_id !== 'Interspire_Addons') {
         $template_dir = $this->addon_template_directory;
     }
     if (!empty($template_dir)) {
         $this->template_system = GetTemplateSystem($template_dir);
     }
 }
Example #16
0
	/**
	* NoFlashUpload
	* A function to display the upload form for non flash upload
	*
	* @return Void Doesn't return anything. Display the template.
	*/
	function NoFlashUpload()
	{
		$tpl = GetTemplateSystem();
		echo $tpl->ParseTemplate('image_manager_multiupload', true);
		die();
	}
	/**
	* Process
	* Executes functions for the page that was requested
	*
	* @return Void Returns nothing
	*/
	function Process()
	{
		$user = GetUser();

		$action = $this->_getGETRequest('Action', '');
		$statstype = $this->_getGETRequest('statstype', null);
		$subaction = $this->_getGETRequest('subaction', '');


		if (isset($_GET['PerPageDisplay'])) {
			$perpage = $this->SetPerPage($_GET['PerPageDisplay']);
		} else {
			$perpage = $this->GetPerPage();
		}

		$statsapi = $this->GetApi('Stats');

		switch ($action) {
			case 'get_linkstats':
				$linksjson = array();

				$token_id = IEM::requestGetGET('token', false);
				$request_link = IEM::requestGetGET('link', false);

				if (!$token_id || !$request_link) {
					die();
				}

				$token_data = IEM::sessionGet($token_id);
				$statid = $token_data['statid'];
				$calendar_restrictions = $token_data['calendar_restrictions'];
				$chosen_link = (is_numeric($request_link) ? $request_link : 'a');

				// Total Clicks
				$linkclicks = $statsapi->GetClicks($statid, 0, 0, $chosen_link, $calendar_restrictions, true);
				$linkclicks = intval($linkclicks);

				$linksjson['linkclicks'] = $linkclicks;

				// Average Clicks
				$averageclicks = 0;

				$open_count = $statsapi->GetOpens($statid, 0, 0, true, $calendar_restrictions, true);
				$open_count = intval($open_count);

				if ($open_count != 0) {
					$averageclicks = $linkclicks / $open_count;
				}

				$linksjson['averageclicks'] = $this->FormatNumber($averageclicks, 3);

				// Click-through rate
				if (isset($token_data['summary']['emails_sent'])) {
					$sent_to = $token_data['summary']['emails_sent'];
				} else {
					$summary = $statsapi->GetNewsletterSummary($statid, true, 0);
					if (!isset($summary['htmlrecipients'])) {
                        $sent_to = $request_link == 'a' ?
                            $statsapi->GetRecipients($statid, 'autoresponder', 0, 1, $calendar_restrictions, true) :
                            0;
					} else {
						$sent_to = $summary['htmlrecipients'] + $summary['textrecipients'] + $summary['multipartrecipients'];
					}
				}

				$clicks = $statsapi->GetUniqueClickRecipients($statid,$calendar_restrictions,$chosen_link);

				if ($sent_to == 0) {
					$linksjson['clickthrough'] = '0%';
				} else {
					$linksjson['clickthrough'] = $this->FormatNumber($clicks / $sent_to * 100,2) . '%';
				}

				// Unique Clicks
				$uniqueclicks = $clicks;
				$linksjson['uniqueclicks'] = $uniqueclicks;

				echo "var linksjson = " . GetJSON($linksjson) . ";";
			break;

			case 'print':
				if ($statstype != 'a' && $statstype != 'n' && $statstype != 'l' && $statstype != 't') {
					exit;
				}

				switch ($statstype) {
					case 'a':
						$this->area = 'autoresponder';
					break;
					case 'n':
						$this->area = 'newsletter';
					break;
					case 'l':
						$this->area = 'list';
					break;
					case 't':
						$this->area = 'triggeremails';
					break;
				}

				switch ($subaction) {
					case 'step2':
						require_once(dirname(__FILE__) . "/amcharts/amcharts.php");

						$options_details = array();
						if (isset($_GET['options_details']) && is_array($_GET['options_details'])) {
							$options_details = $_GET['options_details'];
						}

						if (isset($_GET['autoresponderid'])) {
							$autoresponderid = (int)$_GET['autoresponderid'];
						}

						if (!isset($_GET['Preview'])) {
							$GLOBALS['Body_Onload'] = 'window.focus();window.print();';
						}  else {
							$GLOBALS['Body_Onload'] = '';
						}

						header("Content-type: text/html; charset=" . SENDSTUDIO_DEFAULTCHARSET);

						$this->ParseTemplate('Stats_Print_Header');

						$calendar_restrictions = '';
						$statids = $statsapi->CheckIntVars($_GET['stats']);

						foreach ($statids as $index=>$statid) {

							if ($statstype == 'a') {
								// For autoresponders, $_GET['stats'] contains the autoresponderid
								$autoresponderid = $statid;
								$summary = $statsapi->GetAutoresponderSummary($autoresponderid, true, 0);
								$statid = $summary['statid'];
							}

							if ($statstype == 'n') {
								$summary = $statsapi->GetNewsletterSummary($statid, true, 0);
							}

							if ($statstype == 'l') {
								$summary = $statsapi->GetListSummary($statid);
								$listid = $statid;
								$statid = $summary['statids'];
								IEM::sessionSet('ListStatistics', $statid);
							}

							if ($statstype == 't') {
								$triggeremailsid = $this->_getGETRequest('triggermailsid', 0);

								if (isset($triggeremailsid[$index])) {
									$summary = $statsapi->GetTriggerEmailsStatsRecord($triggeremailsid[$index]);
								} else {
									$summary = array();
								}
							}

							$access = true;

							if (in_array($statstype, array('a', 'n'))) {
								$access = $this->CanAccessStats($statid, $statstype);
							} elseif ($statstype == 't') {
								// Admin access?
								$access = $user->Admin();

								// If this is NOT an admin, check whether or not he owns the trigger
								if (!$access && $this->IsOwner($summary['owneruserid'])) {
									$access = true;
								}
							} else {
								$access = $this->CanAccessList($listid);
							}

							if (!$access) {
								$this->DenyAccess();
								return;
							}


							foreach ($_GET['options'] as $option) {

								switch ($option) {
									case 'snapshot':
										switch ($statstype) {
											case 'l':
												$data = $statsapi->GetSubscriberGraphData($statsapi->stats_type, array('unconfirms' => array(),'confirms' => array(),'subscribes' => array(),'unsubscribes' => array(),'bounces' => array(),'forwards' => array()), $listid);
												IEM::sessionSet('SubscriberGraphData', $data);
												$areas = array('unconfirms', 'confirms', 'unsubscribes', 'bounces', 'forwards');
												$totals = array('unconfirms' => 0, 'confirms' => 0, 'unsubscribes' => 0, 'forwards' => 0, 'bounces' => 0);
												$now = getdate();
												$today = $now['0'];
												$date = $today;
												$time_display = '';

												for ($i = 1; $i <= 12; $i++) {
													$found_stats = false;
													foreach ($areas as $k => $area) {
														$GLOBALS[$area] = 0;
														foreach ($data[$area] as $p => $details) {
															if ($details['mth'] != $i) {
																continue;
															}

															$GLOBALS['Name'] = GetLang($this->Months[$i]) . ' ' . $details['yr'];

															$GLOBALS[$area] = $this->FormatNumber($details['count']);
															$totals[$area] += $details['count'];
															$found_stats = true;
														}
													}

													if (!$found_stats) {
														continue;
													}

													$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
												}

												foreach ($areas as $k => $area) {
													$GLOBALS['Total_' . $area] = $this->FormatNumber($totals[$area]);
													//$GLOBALS['Total_domain_' . $area] = $this->FormatNumber($domain_totals[$area]);
												}

												$data_url = SENDSTUDIO_APPLICATION_URL . '/admin/functions/stats_chart.php?Area=list&list='.$listid .'&graph=subscribersummary&' . IEM::SESSION_NAME . '=' . IEM::sessionID();

												$this->InsertChartImage('SummaryChart', $data_url, array('graph_title' => GetLang("List_Summary_Graph_subscribersummary")));

												$this->ParseTemplate('Stats_Summary_List');
											break; // case l

											case 'n':
												$GLOBALS['NewsletterID'] = $summary['newsletterid'];

												$sent_when = $GLOBALS['StartSending'] = $this->PrintTime($summary['starttime'], true);

												if ($summary['finishtime'] > 0) {
													$GLOBALS['FinishSending'] = $this->PrintTime($summary['finishtime'], true);
													$GLOBALS['SendingTime'] = $this->TimeDifference($summary['finishtime'] - $summary['starttime']);
												} else {
													$GLOBALS['FinishSending'] = GetLang('NotFinishedSending');
													$GLOBALS['SendingTime'] = GetLang('NotFinishedSending');
												}

												$sent_to = $summary['htmlrecipients'] + $summary['textrecipients'] + $summary['multipartrecipients'];

												$sent_size = $summary['sendsize'];

												$GLOBALS['SentToDetails'] = sprintf(GetLang('NewsletterStatistics_Snapshot_SendSize'), $this->FormatNumber($sent_to), $this->FormatNumber($sent_size));

												$GLOBALS['NewsletterSubject'] = $summary['newslettersubject'];

												$GLOBALS['UserEmail'] = htmlspecialchars($summary['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
												$sent_by = $summary['username'];
												if ($summary['fullname']) {
													$sent_by = $summary['fullname'];
												}
												$GLOBALS['SentBy'] = htmlspecialchars($sent_by, ENT_QUOTES, SENDSTUDIO_CHARSET);

												if (sizeof($summary['lists']) > 1) {
													$GLOBALS['SentToLists'] = GetLang('SentToLists');
													$GLOBALS['MailingLists'] = '';
													$break_up = 4;
													$c = 1;
													foreach ($summary['lists'] as $listid => $listname) {
														if ($c % $break_up == 0) {
															$GLOBALS['MailingLists'] .= '<br/>';
															$c = 0;
														}
														$GLOBALS['MailingLists'] .= htmlspecialchars($listname, ENT_QUOTES, SENDSTUDIO_CHARSET) . ',';
														$c++;
													}

													if (($c - 1) % $break_up != 0) {
														$GLOBALS['MailingLists'] = substr($GLOBALS['MailingLists'], 0, -1);
													}
												} else {
													$GLOBALS['SentToLists'] = GetLang('SentToList');
													$listname = current($summary['lists']);
													$GLOBALS['MailingLists'] = htmlspecialchars($listname, ENT_QUOTES, SENDSTUDIO_CHARSET);
												}

												$GLOBALS['UniqueOpens'] = sprintf(GetLang('EmailOpens_Unique'), $this->FormatNumber($summary['emailopens_unique']));
												$GLOBALS['TotalOpens'] = sprintf(GetLang('EmailOpens_Total'), $this->FormatNumber($summary['emailopens']));

												if ($sent_to != 0) {
													$GLOBALS['OpenRate'] = $this->FormatNumber($summary['emailopens_unique'] / $sent_to * 100,2) . "%" ;
												} else {
													$GLOBALS['OpenRate'] = '0%';
												}

												$clicks = $statsapi->GetUniqueClickRecipients($statid,'','a');
												if ($sent_to == 0) {
													$GLOBALS['ClickThroughRate'] = "0%";
												} else {
													$GLOBALS['ClickThroughRate'] = $this->FormatNumber((int)$clicks / (int)$sent_to * 100,2) . '%';
												}

												$total_bounces = $summary['bouncecount_unknown'] + $summary['bouncecount_hard'] + $summary['bouncecount_soft'];

												$GLOBALS['TotalBounces'] = $this->FormatNumber($total_bounces);
												$unopened = $sent_size - $summary['emailopens_unique'] - $total_bounces;
												$data_url = SENDSTUDIO_APPLICATION_URL . '/admin/stats_chart.php?Opens='.$summary['emailopens_unique'].'&Unopened='.$unopened.'&Bounced='.$total_bounces.'&' . IEM::SESSION_NAME . '=' . IEM::sessionID();

												// Newsletter Summary Chart

												$this->InsertChartImage('SummaryChart',$data_url,array('graph_title' => GetLang("NewsletterSummaryChart")));

												// finally put it all together.
												$this->ParseTemplate('Stats_Summary_Newsletter');
											break; // case 'n'

											case 'a':
												$this->LoadLanguageFile('Autoresponders');

												$GLOBALS['AutoresponderID'] = $autoresponderid;

												$GLOBALS['SummaryIntro'] = sprintf(GetLang('AutoresponderStatistics_Snapshot_Summary'), htmlspecialchars($summary['autorespondername'], ENT_QUOTES, SENDSTUDIO_CHARSET));

												$GLOBALS['AutoresponderSubject'] = htmlspecialchars($summary['autorespondersubject'], ENT_QUOTES, SENDSTUDIO_CHARSET);

												$GLOBALS['UserEmail'] = $summary['emailaddress'];
												$created_by = $summary['username'];
												if ($summary['fullname']) {
													$created_by = $summary['fullname'];
												}
												$GLOBALS['CreatedBy'] = $created_by;

												$GLOBALS['MailingList'] = htmlspecialchars($summary['listname'], ENT_QUOTES, SENDSTUDIO_CHARSET);

												if ($summary['hoursaftersubscription'] < 1) {
													$GLOBALS['SentWhen'] = GetLang('Immediately');
												} else {
													if ($summary['hoursaftersubscription'] == 1) {
														$GLOBALS['SentWhen'] = GetLang('HoursAfter_One');
													} else {
														$GLOBALS['SentWhen'] = sprintf(GetLang('HoursAfter_Many'), $summary['hoursaftersubscription']);
													}
												}

												$total_sent = $summary['htmlrecipients'] + $summary['textrecipients'] + $summary['multipartrecipients'];
												$GLOBALS['SentToDetails'] = $this->FormatNumber($total_sent);

												$GLOBALS['UniqueOpens'] = sprintf(GetLang('EmailOpens_Unique'), $this->FormatNumber($summary['emailopens_unique']));
												$GLOBALS['TotalOpens'] = sprintf(GetLang('EmailOpens_Total'), $this->FormatNumber($summary['emailopens']));

												$total_bounces = $summary['bouncecount_unknown'] + $summary['bouncecount_hard'] + $summary['bouncecount_soft'];

												$GLOBALS['TotalBounces'] = $this->FormatNumber($total_bounces);

												$unopened = $total_sent - $summary['emailopens_unique'] - $total_bounces;
												if ($unopened < 0) {
													$unopened = 0;
												}

												$data_url = SENDSTUDIO_APPLICATION_URL . '/admin/stats_chart.php?Opens='.$summary['emailopens_unique'].'&Unopened='.$unopened.'&Bounced='.$total_bounces.'&Area=autoresponder&' . IEM::SESSION_NAME . '=' . IEM::sessionID();

												$this->InsertChartImage('SummaryChart',$data_url);


												$this->ParseTemplate('Stats_Summary_Autoresponder');
											break; // case 'a'

											case 't':
												$this->LoadLanguageFile('TriggerEmails');

												$summary['processed_totalbounced'] = intval($summary['bouncecount_soft']) + intval($summary['bouncecount_hard']) + intval($summary['bouncecount_unknown']);

												$info = array();
												$info['total_open'] = sprintf(GetLang('EmailOpens_Total'), $this->FormatNumber($summary['emailopens']));
												$info['unique_open'] = sprintf(GetLang('EmailOpens_Unique'), $this->FormatNumber($summary['emailopens_unique']));
												$info['total_bounce'] = $this->FormatNumber($summary['processed_totalbounced']);

												$template = GetTemplateSystem();
												$template->assign('record', $summary);
												$template->assign('info', $info);
												$template->ParseTemplate('Stats_Summary_TriggerEmails');
											break; // case 't'
										} // switch ($statstype)
									break; //snapshot

									case 'perdomain':
										$domain_data = $statsapi->GetSubscriberDomainGraphData(array('unconfirms' => array(),'confirms' => array(),'subscribes' => array(),'unsubscribes' => array(),'bounces' => array(),'forwards' => array()), $listid);
										$domain_totals = array('unconfirms' => 0, 'confirms' => 0, 'unsubscribes' => 0, 'forwards' => 0, 'bounces' => 0);
										$areas = array('unconfirms', 'confirms', 'unsubscribes', 'bounces', 'forwards');

										$domain_lines = array();

										foreach ($areas as $k => $area) {
											foreach ($domain_data[$area] as $p => $details) {
												if (isset($details['domainname'])) {
													$domain = $details['domainname'];
													if (!isset($domain_lines[$domain])) {
														$domain_lines[$domain] = array('unconfirms' => 0, 'confirms' => 0, 'unsubscribes' => 0, 'forwards' => 0, 'bounces' => 0);
													}
													$domain_lines[$domain][$area] = $details['count'];
												}
											}
										}

										$graph_details = array();

										$domain_display = '';

										if (!empty($domain_lines)) {
											foreach ($domain_lines as $domain_name => $domain_info) {
												$GLOBALS['Name'] = htmlspecialchars($domain_name, ENT_QUOTES, SENDSTUDIO_CHARSET);

												foreach ($domain_info as $area => $count) {
													$GLOBALS[$area] = $this->FormatNumber($count);
													$domain_totals[$area] += $count;

													if ($area == 'confirms') {
														if (!isset($graph_details[$domain_name])) {
															$graph_details[$domain_name] = 0;
														}
														$graph_details[$domain_name] += $count;
														continue;
													}
												}

												$domain_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
											}
										} else {
											$GLOBALS['Name'] = '';
											foreach ($areas as $k => $area) {
												$GLOBALS[$area] = 0;
											}
											$domain_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
										}

										IEM::sessionSet('SubscriberDomains', $graph_details);


										$this->DisplayChart('DomainChart', 'subscriberdomains', '0','pie',array(
											'hide_labels_percent' => 2,
											'group_percent' => 2,
											'x_position' => '',
											'radius' => 85,
											'graph_title' => GetLang("ListStatistics_Snapshot_PerDomain")
										));

										$this->ParseTemplate('Stats_Summary_Perdomain');

										if (in_array($option,$options_details)) {
											foreach ($areas as $k => $area) {
												$GLOBALS['Total_domain_' . $area] = $this->FormatNumber($domain_totals[$area]);
											}

											$GLOBALS['DisplayDomainList'] = $domain_display;

											$this->ParseTemplate('Stats_List_Step3_Domains_Table');
										}
									break; // case perdomain

									case 'open':
										if ($statstype == 'l') {
											$total_emails = $summary['emails_sent'];
										} else {
											$total_emails = $summary['htmlrecipients'] + $summary['textrecipients'] + $summary['multipartrecipients'];
										}

										$GLOBALS['TotalEmails'] = $this->FormatNumber($total_emails);
										$GLOBALS['TotalOpens'] = $this->FormatNumber($summary['emailopens']);
										$GLOBALS['TotalUniqueOpens'] = $this->FormatNumber($summary['emailopens_unique']);

										$most_opens = $statsapi->GetMostOpens($statid, $calendar_restrictions);

										$now = getdate();

										if (isset($most_opens['mth'])) {
											$GLOBALS['MostOpens'] = $this->Months[$most_opens['mth']] . ' ' . $most_opens['yr'];
										}

										if (isset($most_opens['hr'])) {
											$GLOBALS['MostOpens'] = $this->PrintDate(mktime($most_opens['hr'], 1, 1, 1, 1, $now['year']), GetLang('Daily_Time_Display'));
										}

										if (isset($most_opens['dow'])) {
											$pos = array_search($most_opens['dow'], array_keys($this->days_of_week));
											// we need to add 1 hour here otherwise we get the wrong day from strtotime.
											$GLOBALS['MostOpens'] = $this->PrintDate(strtotime("last " . $this->days_of_week[$pos] . " +1 hour"), GetLang('Date_Display_Display'));
										}

										if (isset($most_opens['dom'])) {
											$month = $now['mon'];
											// if the day-of-month is after "today", it's going to be for "last month" so adjust the month accordingly.
											if ($most_opens['dom'] > $now['mday']) {
												$month = $now['mon'] - 1;
											}
											$GLOBALS['MostOpens'] = $this->PrintDate(mktime(0, 0, 1, $month, $most_opens['dom'], $now['year']), GetLang('Date_Display_Display'));
										}

										$avg_opens = 0;
										if ($total_emails > 0) {
											$avg_opens = $summary['emailopens'] / $total_emails;
										}
										$GLOBALS['AverageOpens'] = $this->FormatNumber($avg_opens, 1);

										if ($total_emails != 0) {
											$GLOBALS['OpenRate'] = $this->FormatNumber($summary['emailopens_unique'] / $total_emails * 100,2) . "%" ;
										} else {
											$GLOBALS['OpenRate'] = '0%';
										}

										if ($summary['emailopens'] > 0) {
											$this->DisplayChart('OpenChart', $this->area, $statid,'column',array('graph_title' => GetLang("OpensChart")));
										}

										$this->ParseTemplate('Stats_Summary_Newsletter_Opens');

										if (in_array($option,$options_details)) {
											$token = "stats" . md5(uniqid('_'));

											IEM::sessionSet($token,array(
												'statid' => $statid, 'unique_only' => false, 'calendar_restrictions' => $calendar_restrictions,
												'summary' => $summary
											));

											echo '<div id="'.$option . '_details"></div>';
											echo '<script>
												$.ajax({
													type: "get",
													url: "remote_stats.php",
													data: "type=newsletter_opens&pagination=false&token='.$token.'&sort=down",
													success: function (html) {
														$("#'.$option.'_details").html(html);
													}
												});
												</script>';
										}
									break; // opens

									case 'click':
										if (isset($summary['starttime'])) {
											$sent_when = $this->PrintTime($summary['starttime'], true);
										}

										$GLOBALS['StatID'] = (int)$statid;

										$GLOBALS['LinkAction'] = 'Newsletter';

										if (!isset($chosen_link) || !is_numeric($chosen_link)) {
											$chosen_link = 'a';
										}

										$summary['linkclicks'] = $statsapi->GetClicks($statid, 0, 0, $chosen_link, $calendar_restrictions, true);

										// build up the summary table.
										$GLOBALS['TotalClicks'] = $this->FormatNumber($summary['linkclicks']);

										$unique_clicks_count = $statsapi->GetUniqueClicks($statid, $chosen_link, $calendar_restrictions);
										$GLOBALS['TotalUniqueClicks'] = $this->FormatNumber($unique_clicks_count);

										$most_popular_link = $statsapi->GetMostPopularLink($statid, $chosen_link, $calendar_restrictions);

										$GLOBALS['MostPopularLink'] = htmlspecialchars($most_popular_link, ENT_QUOTES, SENDSTUDIO_CHARSET);
										$GLOBALS['MostPopularLink_Short'] = $most_popular_link;

										$averageclicks = 0;
										if (isset($summary['emailopens']) && (int)$summary['emailopens'] > 0) {
											$open_count = (int)$summary['emailopens'];
											$averageclicks = $summary['linkclicks'] / $open_count;
										}
										$GLOBALS['AverageClicks'] = $this->FormatNumber($averageclicks, 1);

										if ($summary['linkclicks'] > 0) {
											$this->DisplayChart('LinksChart', $this->area, $statid,'column',array('graph_title' => GetLang("LinksClickedChart")));
										}

										$this->ParseTemplate('Stats_Summary_Newsletter_Links');

										$token = "stats" . md5(uniqid('_'));

										IEM::sessionSet($token,array(
											'statid' => $statid, 'chosen_link' => 'a', 'calendar_restrictions' => $calendar_restrictions,
											'summary' => $summary
										));

										if (in_array($option,$options_details)) {
											echo '<div id="'.$option . '_details"></div>';
											echo '<script>
												$.ajax({
													type: "get",
													url: "remote_stats.php",
													data: "type=newsletter_links&pagination=false&token='.$token.'&sort=down",
													success: function (html) {
														$("#'.$option.'_details").html(html);
													}
												});
											</script>';
										}

										echo "
											<script>
												$.get('remote_stats.php?Action=get_linkstats&link=a&token={$token}','',function (data) {
													eval(data);
													$('#clickthrough').html(linksjson.clickthrough);
												});
											</script>";

									break; // click

									case 'bounce':
										$chosen_bounce_type = 'a';
										$total_bounces = $statsapi->GetBounces($statid, 0, 10, $chosen_bounce_type, $calendar_restrictions, true);

										$bounce_types_count = $statsapi->GetBounceCounts($statid, $calendar_restrictions);
										$GLOBALS['TotalBounceCount'] = $this->FormatNumber($bounce_types_count['total']);
										$GLOBALS['TotalSoftBounceCount'] = $this->FormatNumber($bounce_types_count['soft']);
										$GLOBALS['TotalHardBounceCount'] = $this->FormatNumber($bounce_types_count['hard']);
										if ($bounce_types_count['total'] > 0) {
											$this->DisplayChart('BounceChart', $this->area, $statid,'column');
										}

										$this->ParseTemplate('stats_summary_newsletter_bounces');

										if (in_array($option,$options_details)) {
											$token = "stats" . md5(uniqid('_'));
											IEM::sessionSet($token,array(
												'statid' => $statid, 'chosen_bounce_type' => false, 'calendar_restrictions' => $calendar_restrictions,
												'summary' => $summary
											));

											echo '<div id="'.$option . '_details"></div>';
											echo '<script>
												$.ajax({
													type: "get",
													url: "remote_stats.php",
													data: "type=newsletter_bounces&pagination=false&token='.$token.'&sort=down",
													success: function (html) {
														$("#'.$option.'_details").html(html);
													}
												});
												</script>';
										}

									break; // bounce

									case 'unsubscribe':
										if ($summary['unsubscribecount'] > 0) {
											$unsubscribes = $statsapi->GetUnsubscribes($statid, 0, 10, $calendar_restrictions);
										}

										$GLOBALS['TotalUnsubscribes'] = $this->FormatNumber($summary['unsubscribecount']);

										$most_unsubscribes = $statsapi->GetMostUnsubscribes($statid, $calendar_restrictions);

										$now = getdate();

										if (isset($most_unsubscribes['mth'])) {
											$GLOBALS['MostUnsubscribes'] = $this->Months[$most_unsubscribes['mth']] . ' ' . $most_unsubscribes['yr'];
										}

										if (isset($most_unsubscribes['hr'])) {
											$GLOBALS['MostUnsubscribes'] = $this->PrintDate(mktime($most_unsubscribes['hr'], 1, 1, 1, 1, $now['year']), GetLang('Daily_Time_Display'));
										}

										if (isset($most_unsubscribes['dow'])) {
											$pos = array_search($most_unsubscribes['dow'], array_keys($this->days_of_week));
											// we need to add 1 hour here otherwise we get the wrong day from strtotime.
											$GLOBALS['MostUnsubscribes'] = $this->PrintDate(strtotime("last " . $this->days_of_week[$pos] . " +1 hour"), GetLang('Date_Display_Display'));
										}

										if (isset($most_unsubscribes['dom'])) {
											$month = $now['mon'];
											// if the day-of-month is after "today", it's going to be for "last month" so adjust the month accordingly.
											if ($most_unsubscribes['dom'] > $now['mday']) {
												$month = $now['mon'] - 1;
											}
											$GLOBALS['MostUnsubscribes'] = $this->PrintDate(mktime(0, 0, 1, $month, $most_unsubscribes['dom'], $now['year']), GetLang('Date_Display_Display'));
										}

										if ($summary['unsubscribecount'] > 0) {
											$this->DisplayChart('UnsubscribeChart', $this->area, $statid, 'column',array('graph_title' => GetLang("UnsubscribesChart")));
										}

										$this->ParseTemplate('stats_summary_newsletter_unsubscribes');

										if (in_array($option,$options_details)) {
											$token = "stats" . md5(uniqid('_'));

											if ($statstype == 't') {
												IEM::sessionSet($token,array(
													'statid' => $statid, 'calendar_restrictions' => array('unsubscribes' => $calendar_restrictions),
													'summary' => $summary
												));
											} else {
												IEM::sessionSet($token,array(
													'statid' => $statid, 'calendar_restrictions' => $calendar_restrictions,
													'summary' => $summary
												));
											}

											$url_data_statstype = 'newsletter_unsubscribes';
											if ($statstype == 't') {
												$url_data_statstype = 'triggeremails_unsubscribes';
											}

											echo '<div id="'.$option . '_details"></div>';
											echo '<script>
												$.ajax({
													type: "get",
													url: "remote_stats.php",
													data: "type=' . $url_data_statstype . '&pagination=false&token='.$token.'&sort=down",
													success: function (html) {
														$("#'.$option.'_details").html(html);
													}
												});
												</script>';
										}

									break; //unsubscribe

									case 'forward':
										if ($summary['emailforwards'] > 0) {
											$forwards = $statsapi->GetForwards($statid, 0, 0, $calendar_restrictions);
										}

										if ($calendar_restrictions != '') {
											$summary['emailforwards'] = $statsapi->GetForwards($statid, $start, $perpage, $calendar_restrictions, true);
										}

										$GLOBALS['TotalForwards'] = $this->FormatNumber($summary['emailforwards']);

										$new_signups = $statsapi->GetForwards($statid, 0, 0, $calendar_restrictions, true, true);

										$GLOBALS['TotalForwardSignups'] = $this->FormatNumber($new_signups);

										if ($summary['emailforwards'] > 0) {
											$this->DisplayChart('ForwardsChart', $this->area, $statid,'column',array('graph_title' => GetLang("ForwardsChart")));
										}

										$this->ParseTemplate('Stats_Summary_Newsletter_Forwards');

										if (in_array($option,$options_details)) {
											$token = "stats" . md5(uniqid('_'));

											if ($statstype == 't') {
												IEM::sessionSet($token,array(
													'statid' => $statid, 'calendar_restrictions' => array('forwards' => $calendar_restrictions),
													'summary' => $summary
												));
											} else {
												IEM::sessionSet($token,array(
													'statid' => $statid, 'calendar_restrictions' => $calendar_restrictions,
													'summary' => $summary
												));
											}

											$url_data_statstype = 'forwards';
											if ($statstype == 't') {
												$url_data_statstype = 'triggeremails_forwards';
											}

											echo '<div id="'.$option . '_details"></div>';
											echo '<script>
												$.ajax({
													type: "get",
													url: "remote_stats.php",
													data: "type=' . $url_data_statstype . '&pagination=false&token='.$token.'&sort=down",
													success: function (html) {
														$("#'.$option.'_details").html(html);
													}
												});
											</script>';
										}
									break; //forward

									default:
								} // switch $option
							} // foreach $options
						} // foreach $stats
						$this->ParseTemplate('Stats_Print_Footer');

					break; // step2

					default: // step1

						$print_options = '';
						$bg_color = 'white';

						if ($_GET['statstype']) {
							$print_options .= '<input type="hidden" name="statstype" value="' . htmlentities($statstype, ENT_QUOTES, SENDSTUDIO_CHARSET) . '" />';
						}

						switch ($statstype) {

							default:
								$itemids = $statsapi->CheckIntVars($_GET['stats']);

								if (isset($_GET['stats'])) {
									foreach ($_GET['stats'] as $val) {
										$print_options .= '<input type="hidden" name="stats[]" value="' . $val . '" />';
									}
								}

								if (isset($_GET['autoresponderid'])) {
									foreach ($_GET['autoresponderid'] as $val) {
										$print_options .= '<input type="hidden" name="autoresponderid[]" value="' . $val . '" />';
									}
								}

								if (isset($_GET['triggerid'])) {
									$triggeremailid = $_GET['triggerid'];
									if (!is_array($triggeremailid)) {
										$triggeremailid = array($triggeremailid);
									}

									foreach ($triggeremailid as $id) {
										$print_options .= '<input type="hidden" name="triggermailsid[]" value="' . intval($id) . '" />';
									}
								}

								if ($statstype == 'l') {
									$a = array (
										'snapshot' => GetLang('ListStatistics_Snapshot'),
										'perdomain' => GetLang('ListStatistics_Snapshot_PerDomain'),
										'open' => GetLang('Opens_Summary'),
										'click' => GetLang('LinkClicks_Summary'),
										'bounce' => GetLang('Bounce_Summary'),
										'unsubscribe' => GetLang('Unsubscribe_Summary'),
										'forward' => GetLang('Forwards_Summary')
									);
								} else {
									$a = array (
										'snapshot' => GetLang('NewsletterStatistics_Snapshot'),
										'open' => GetLang('Opens_Summary'),
										'click' => GetLang('LinkClicks_Summary'),
										'bounce' => GetLang('Bounce_Summary'),
										'unsubscribe' => GetLang('Unsubscribe_Summary'),
										'forward' => GetLang('Forwards_Summary')
									);
								}

								foreach ($a as $key => $val) {
									$bg_color = ($bg_color == 'white') ? '#EDECEC' : 'white';
									$print_options .= '<div style="background: ' . $bg_color . '; padding: 5px; margin-bottom: 5px;">';
									$print_options .= '<input id="print_'.$key.'" type="checkbox" name="options[]" value="'.$key.'" checked="checked" style="margin:0;"/>
										<label for="print_' . $key . '">'.$val.'</label><br />' . "\n";

									if ($key != 'snapshot') {
										$count = 0;
										$function = 'Get' . ucfirst($key) . 's';

										$real_statids = array();
										if ($statstype == 'l') {
											// For lists, $itemids is actually the listids, so we have to get the statids for the lists
											foreach ($itemids as $listid) {
												if (!$this->CanAccessList($listid)) {
													$this->DenyAccess();
													return;
												}
												$summary = $statsapi->GetListSummary($listid);
												$real_statids = array_merge($real_statids, $summary['statids']);
											}
										}

										if ($statstype == 'a') {
											// For autoresponders, $itemids is actually the autoresponderids, so we have to get the statids for the autoresponders
											foreach ($itemids as $arid) {
												$summary = $statsapi->GetAutoresponderSummary($arid, true, 0);
												if (!$this->CanAccessStats($summary['statid'], 'a')) {
													$this->DenyAccess();
													return;
												}
												$real_statids[] = $summary['statid'];
											}
										}

										switch ($key) {
											case 'perdomain':
												$count = $statsapi->GetSubscriberDomainCount($itemids[0]);
											break;

											case 'bounce':
											case 'open':
												$count = $statsapi->$function( ($real_statids === array() ? $itemids : $real_statids), 0, 0, false, '', true);
											break;

											case 'click':
												$count = $statsapi->$function(($real_statids === array() ? $itemids : $real_statids), 0, 0, 'a', '', true);
											break;

											default:
												$count = $statsapi->$function(($real_statids === array() ? $itemids : $real_statids), 0, 0, '', true);
										}

										$print_options .= '<span style="width: 20px;"><img src="images/blank.gif" width="20" height="1" /></span>';
										$print_options .= '<input id="print_details_'.$key.'" type="checkbox" name="options_details[]" value="'.$key.'" style="margin:0;"';
										if ($count == 0) {
											$print_options .= ' disabled="disabled"';
										}
										$print_options .= ' />
											<label for="print_details_' . $key . '">' .
											sprintf(GetLang('Stats_Print_IncludeDetailsOf'),$count,GetLang("Stats_Print_$key")) .
											'</label><br />' . "\n";
									}

									$print_options .= '</div>';
								}
							break;
						}

						$GLOBALS['PrintOptions'] = $print_options;

						$this->ParseTemplate('stats_print_step1');
						break;
					} // switch subaction
			break; //print

			default:
				$token_data = IEM::sessionGet($_GET['token']);
				$statid = $token_data['statid'];
				$calendar_restrictions = $token_data['calendar_restrictions'];

				$GLOBALS['TableToken'] = $_GET['token']; $GLOBALS['Token'] = $_GET['token'];

				if (isset($_GET['pagination']) && ($_GET['pagination'] == 'false')) {
					$perpage = 'all';
				}

				$DisplayPage = (isset($_GET['DisplayPage'])) ? (int)$_GET['DisplayPage'] : 1;
				$GLOBALS['CurrentPage'] = (int)$DisplayPage;
				$start = 0;
				if ($perpage != 'all') {
					$start = ($DisplayPage - 1) * $perpage;
				}

				$summary = &$token_data['summary'];

				if (isset($_GET['sort'])) {
					switch ($_GET['sort']) {
						case 'up':
						case 'down':
							$GLOBALS['SortDirection'] = $_GET['sort'];
						break;

						default:
							$GLOBALS['SortDirection'] = 'up';
					}
					$this->sort = ($GLOBALS['SortDirection'] == 'up' ? 'ASC' : 'DESC');
				} else {
					$this->sort = 'ASC';
					$GLOBALS['SortDirection'] = 'up';
				}

				if (in_array($_GET['type'], array_keys($this->columns))) {
					$GLOBALS['TableType'] = $_GET['type'];
					$this->type = $_GET['type'];

					if (isset($_GET['column']) && in_array($_GET['column'], array_keys($this->columns[$this->type]))) {
						$GLOBALS['SortColumn'] = $_GET['column'];
						$this->column = $this->columns[$this->type][$_GET['column']];
					} else {
						$q = array_keys($this->columns[$this->type]);
						$GLOBALS['SortColumn'] = $q[0];
						$this->column = $this->columns[$this->type][$q[0]];
					}
				} else {
					echo "Invalid parameters";
					exit;
				}


				// Tables:
				header("Content-type: text/html; charset=" . SENDSTUDIO_DEFAULTCHARSET);
				switch ($this->type) {
					case 'newsletter_opens':
						$opens = array();

						$opencount = $statsapi->GetOpens($token_data['statid'], 0, 0, $token_data['unique_only'], $token_data['calendar_restrictions'], true);

						// make sure unique opens are > 0 - if they aren't, something isn't tracking right anyway so no point trying anything else.
						if ($summary['emailopens_unique'] > 0) {
							if (isset($token_data['listid'])) {
								$opens = $statsapi->GetOpens($statid, $start, $perpage, $token_data['unique_only'], $token_data['calendar_restrictions'],false,$this->column,$this->sort,$token_data['listid']);
							} else {
								$opens = $statsapi->GetOpens($statid, $start, $perpage, $token_data['unique_only'], $token_data['calendar_restrictions'],false,$this->column,$this->sort);
							}
						}

						$GLOBALS['CurrentPage'] = (int)$DisplayPage;
						$this->_SetupPaging($opencount, $DisplayPage, $perpage, '', 'newsletter_opens', $_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$open_list = '';
						foreach ($opens as $k => $opendetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($opendetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['DateOpened'] = $this->PrintTime($opendetails['opentime'], true);
							$GLOBALS['OpenedEmailAsType'] = GetLang('OpenedEmailAs_Unknown');

							switch (strtolower($opendetails['opentype'])) {
								case 'h':
									$GLOBALS['OpenedEmailAsType'] = GetLang('OpenedEmailAs_HTML');
								break;

								case 't':
									$GLOBALS['OpenedEmailAsType'] = GetLang('OpenedEmailAs_Text');
								break;
							}

							$open_list .= $this->ParseTemplate('Stats_Step3_Opens_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Opens_List'] = $open_list;
						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Opens_Table', true, false);
					break; //newsletter_opens

					case 'newsletter_links':
						$chosen_link = $token_data['chosen_link'];
						if (isset($_GET['link']) && is_numeric($_GET['link'])) {
							$chosen_link = (int)$_GET['link'];
						} else {
							$chosen_link = 'a';
						}

						$links = array();
						if ($summary['linkclicks'] > 0) {
							$links = $statsapi->GetClicks($statid, $start, $perpage, $chosen_link, $calendar_restrictions,false,$this->column,$this->sort);
						}

						$all_links = $statsapi->GetUniqueLinks($statid);

						if (empty($all_links)) {
							$GLOBALS['DisplayStatsLinkList'] = 'none';
						} else {
							$GLOBALS['DisplayStatsLinkList'] = 'block';
							$all_links_list = '';

							foreach ($all_links as $p => $linkinfo) {
								$selected = '';
								if ($linkinfo['linkid'] == $chosen_link) {
									$selected = ' SELECTED';
								}

								$all_links_list .= '<option value="' . $linkinfo['linkid'] . '"' . $selected . '>' . str_replace(array("'", '"'), "", $linkinfo['url']) . '</option>';
							}

							$GLOBALS['StatsLinkList'] = $all_links_list;
							$GLOBALS['CurrentPage'] = (int)$GLOBALS['CurrentPage'];
							$GLOBALS['StatsLinkDropDown'] = $this->ParseTemplate('Stats_Step3_Links_List', true, false);
						}

						$GLOBALS['CurrentPage'] = (int)$DisplayPage;
						$total_links = $statsapi->GetClicks($statid, $start, $perpage, $chosen_link, $calendar_restrictions,true);
						$this->_SetupPaging($total_links, $DisplayPage, $perpage,'','newsletter_links',$_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$click_list = '';
						foreach ($links as $k => $clickdetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($clickdetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['DateClicked'] = $this->PrintTime($clickdetails['clicktime'], true);

							$GLOBALS['FullURL'] = $url = str_replace(array('"', "'"), "", $clickdetails['url']);

							$GLOBALS['LinkClicked'] = $this->TruncateInMiddle($url);

							$click_list .= $this->ParseTemplate('Stats_Step3_Links_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Links_List'] = $click_list;
						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = ''; $GLOBALS['StatsLinkDropDown'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Links_Table');
					break; // newsletter_links

					case 'newsletter_bounces':
						$chosen_bounce_type = $token_data['chosen_bounce_type'];

						if (isset($_GET['bouncetype']) && in_array($_GET['bouncetype'],array('any','soft','hard'))) {
							$chosen_bounce_type = $_GET['bouncetype'];
						} else {
							$chosen_bounce_type = 'any';
						}

						$bouncetypelist = '';
						$all_bounce_types = array('any', 'hard', 'soft');

						if (!in_array($chosen_bounce_type, $all_bounce_types)) {
							$chosen_bounce_type = 'any';
						}

						foreach ($all_bounce_types as $p => $bounce_type) {
							$selected = '';
							if ($bounce_type == $chosen_bounce_type) {
								$selected = ' SELECTED';
							}
							$bouncetypelist .= '<option value="' . $bounce_type . '"' . $selected . '>' . GetLang('Bounce_Type_' . $bounce_type) . '</option>';
						}
						$GLOBALS['StatsBounceList'] = $bouncetypelist;

						$bounces = array();

						$total_bounces = $statsapi->GetBounces($statid, $start, $perpage, $chosen_bounce_type, $calendar_restrictions, true);

						if ($total_bounces > 0) {
							$bounces = $statsapi->GetBounces($statid, $start, $perpage, $chosen_bounce_type, $calendar_restrictions,false,$this->column,$this->sort);
						}

						$this->_SetupPaging($total_bounces, $DisplayPage, $perpage,'','newsletter_bounces',$_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$bounce_list = '';
						foreach ($bounces as $k => $bouncedetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($bouncedetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['BounceDate'] = $this->PrintTime($bouncedetails['bouncetime'], true);
							$GLOBALS['BounceType'] = GetLang('Bounce_Type_' . $bouncedetails['bouncetype']);
							$GLOBALS['BounceRule'] = GetLang('Bounce_Rule_' . $bouncedetails['bouncerule']);
							$bounce_list .= $this->ParseTemplate('Stats_Step3_Bounces_Row', true, false);
						}
						$GLOBALS['Stats_Step3_Bounces_List'] = $bounce_list;

						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = ''; $GLOBALS['StatsBounceList'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Bounces_Table');

					break; // newsletter_bounces

					case 'newsletter_unsubscribes':
						$unsubscribes = array();

						$listid = 0;
						$token_request = IEM::requestGetGET('token', '');
						$token = IEM::sessionGet($token_request);
						if ($token !== false && isset($token['listid'])) {
							$listid = $token['listid'];
						}

						if ($summary['unsubscribecount'] > 0) {
							$unsubscribes = $statsapi->GetUnsubscribes($statid, $start, $perpage, $calendar_restrictions,false,$this->column,$this->sort, $listid);
						}

						if (empty($unsubscribes)) {
							if ($summary['unsubscribecount'] > 0) {
								$GLOBALS['Error'] = GetLang('NewsletterHasNoUnsubscribes_CalendarProblem');
							} else {
								$GLOBALS['Error'] = GetLang('NewsletterHasNoUnsubscribes');
							}
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							return $this->ParseTemplate('Stats_Step3_Unsubscribes_Empty', true, false);
						}

						$total_unsubscribes = $statsapi->GetUnsubscribes($statid, $start, $perpage, $calendar_restrictions,true, '', '', $listid);

						$this->_SetupPaging($total_unsubscribes, $DisplayPage, $perpage,'','newsletter_unsubscribes',$_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$unsub_list = '';
						foreach ($unsubscribes as $k => $unsubdetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($unsubdetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['UnsubscribeTime'] = $this->PrintTime($unsubdetails['unsubscribetime'], true);
							$unsub_list .= $this->ParseTemplate('Stats_Step3_Unsubscribes_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Unsubscribes_List'] = $unsub_list;

						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Unsubscribes_Table');
					break; // newsletter_unsubscribes

					case 'forwards':
						$forwards = array();

						if ($summary['emailforwards'] > 0) {
							$forwards = $statsapi->GetForwards($statid, $start, $perpage, $calendar_restrictions,false,false,$this->column,$this->sort);
						}
						$total_forwards = $statsapi->GetForwards($statid, $start, $perpage, $calendar_restrictions,true);
						$this->_SetupPaging($total_forwards, $DisplayPage, $perpage,'','forwards',$_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$forward_list = '';
						foreach ($forwards as $k => $forwarddetails) {
							$GLOBALS['ForwardedTo'] = htmlspecialchars($forwarddetails['forwardedto'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['ForwardedBy'] = htmlspecialchars($forwarddetails['forwardedby'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['ForwardTime'] = $this->PrintTime($forwarddetails['forwardtime'], true);
							if ($forwarddetails['subscribed'] > 0) {
								$hassubscribed = GetLang('Yes');
							} else {
								$hassubscribed = GetLang('No');
							}
							$GLOBALS['HasSubscribed'] = $hassubscribed;
							$forward_list .= $this->ParseTemplate('Stats_Step3_Forwards_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Forwards_List'] = $forward_list;

						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Forwards_Table');
					break; // forwards

					case 'triggeremails_opens':
						$opens = array();

						$opencount = $statsapi->GetOpens($statid, 0, 0, $token_data['unique_open_only'], $token_data['calendar_restrictions']['opens'], true);

						if ($opencount > 0) {
							if (isset($token_data['listid'])) {
								$opens = $statsapi->GetOpens($statid, $start, $perpage, $token_data['unique_open_only'], $token_data['calendar_restrictions']['opens'], false, $this->column, $this->sort, $token_data['listid']);
							} else {
								$opens = $statsapi->GetOpens($statid, $start, $perpage, $token_data['unique_open_only'], $token_data['calendar_restrictions']['opens'], false, $this->column, $this->sort);
							}
						}

						$GLOBALS['CurrentPage'] = (int)$DisplayPage;
						$this->_SetupPaging($opencount, $DisplayPage, $perpage, '', 'triggeremails_opens', $_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$open_list = '';
						foreach ($opens as $k => $opendetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($opendetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['DateOpened'] = $this->PrintTime($opendetails['opentime'], true);
							$GLOBALS['OpenedEmailAsType'] = GetLang('OpenedEmailAs_Unknown');

							switch (strtolower($opendetails['opentype'])) {
								case 'h':
									$GLOBALS['OpenedEmailAsType'] = GetLang('OpenedEmailAs_HTML');
								break;

								case 't':
									$GLOBALS['OpenedEmailAsType'] = GetLang('OpenedEmailAs_Text');
								break;
							}

							$open_list .= $this->ParseTemplate('Stats_Step3_Opens_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Opens_List'] = $open_list;
						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Opens_Table', true, false);
					break; //triggeremails_opens

					case 'triggeremails_links':
						$chosen_link = isset($token_data['chosen_link'])? $token_data['chosen_link'] : 'a';
						if (isset($_GET['link']) && is_numeric($_GET['link'])) {
							$chosen_link = (int)$_GET['link'];
						} else {
							$chosen_link = 'a';
						}

						$links = array();
						if ($summary['linkclicks'] > 0) {
							$links = $statsapi->GetClicks($statid, $start, $perpage, $chosen_link, $token_data['calendar_restrictions']['clicks'], false, $this->column, $this->sort);
						}

						$all_links = $statsapi->GetUniqueLinks($statid);

						if (empty($all_links)) {
							$GLOBALS['DisplayStatsLinkList'] = 'none';
						} else {
							$GLOBALS['DisplayStatsLinkList'] = 'block';
							$all_links_list = '';

							foreach ($all_links as $p => $linkinfo) {
								$selected = '';
								if ($linkinfo['linkid'] == $chosen_link) {
									$selected = ' SELECTED';
								}

								$all_links_list .= '<option value="' . $linkinfo['linkid'] . '"' . $selected . '>' . str_replace(array("'", '"'), "", $linkinfo['url']) . '</option>';
							}

							$GLOBALS['StatsLinkList'] = $all_links_list;
							$GLOBALS['CurrentPage'] = (int)$GLOBALS['CurrentPage'];
							$GLOBALS['StatsLinkDropDown'] = $this->ParseTemplate('Stats_Step3_Links_List', true, false);
						}

						$GLOBALS['CurrentPage'] = (int)$DisplayPage;
						$total_links = $statsapi->GetClicks($statid, $start, $perpage, $chosen_link, $token_data['calendar_restrictions']['clicks'], true);
						$this->_SetupPaging($total_links, $DisplayPage, $perpage, '', 'triggeremails_links', $_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$click_list = '';
						foreach ($links as $k => $clickdetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($clickdetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['DateClicked'] = $this->PrintTime($clickdetails['clicktime'], true);

							$GLOBALS['FullURL'] = $url = str_replace(array('"', "'"), "", $clickdetails['url']);

							$GLOBALS['LinkClicked'] = $this->TruncateInMiddle($url);

							$click_list .= $this->ParseTemplate('Stats_Step3_Links_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Links_List'] = $click_list;
						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = '';
							$GLOBALS['StatsLinkDropDown'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Links_Table');
					break; // triggeremails_links

					case 'triggeremails_bounces':
						$chosen_bounce_type = isset($token_data['chosen_bounce_type'])? $token_data['chosen_bounce_type'] : 'any';

						if (isset($_GET['bouncetype']) && in_array($_GET['bouncetype'], array('any', 'soft', 'hard'))) {
							$chosen_bounce_type = $_GET['bouncetype'];
						} else {
							$chosen_bounce_type = 'any';
						}

						$bouncetypelist = '';
						$all_bounce_types = array('any', 'hard', 'soft');

						if (!in_array($chosen_bounce_type, $all_bounce_types)) {
							$chosen_bounce_type = 'any';
						}

						foreach ($all_bounce_types as $p => $bounce_type) {
							$selected = '';
							if ($bounce_type == $chosen_bounce_type) {
								$selected = ' SELECTED';
							}
							$bouncetypelist .= '<option value="' . $bounce_type . '"' . $selected . '>' . GetLang('Bounce_Type_' . $bounce_type) . '</option>';
						}
						$GLOBALS['StatsBounceList'] = $bouncetypelist;

						$bounces = array();

						$total_bounces = $statsapi->GetBounces($statid, $start, $perpage, $chosen_bounce_type, $token_data['calendar_restrictions']['bounces'], true);

						if ($total_bounces > 0) {
							$bounces = $statsapi->GetBounces($statid, $start, $perpage, $chosen_bounce_type, $token_data['calendar_restrictions']['bounces'], false, $this->column,$this->sort);
						}

						$this->_SetupPaging($total_bounces, $DisplayPage, $perpage, '', 'triggeremails_bounces', $_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$bounce_list = '';
						foreach ($bounces as $k => $bouncedetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($bouncedetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['BounceDate'] = $this->PrintTime($bouncedetails['bouncetime'], true);
							$GLOBALS['BounceType'] = GetLang('Bounce_Type_' . $bouncedetails['bouncetype']);
							$GLOBALS['BounceRule'] = GetLang('Bounce_Rule_' . $bouncedetails['bouncerule']);
							$bounce_list .= $this->ParseTemplate('Stats_Step3_Bounces_Row', true, false);
						}
						$GLOBALS['Stats_Step3_Bounces_List'] = $bounce_list;

						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = ''; $GLOBALS['StatsBounceList'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Bounces_Table');

					break; // triggeremails_bounces

					case 'triggeremails_unsubscribes':
						$unsubscribes = array();;

						$statid = $token_data['statid'];

						if ($summary['unsubscribecount'] > 0) {
							$unsubscribes = $statsapi->GetUnsubscribes($statid, $start, $perpage, $token_data['calendar_restrictions']['unsubscribes'], false, $this->column, $this->sort);
						}

						if (empty($unsubscribes)) {
							if ($summary['unsubscribecount'] > 0) {
								$GLOBALS['Error'] = GetLang('NewsletterHasNoUnsubscribes_CalendarProblem');
							} else {
								$GLOBALS['Error'] = GetLang('NewsletterHasNoUnsubscribes');
							}
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							return $this->ParseTemplate('Stats_Step3_Unsubscribes_Empty', true, false);
						}

						$total_unsubscribes = $statsapi->GetUnsubscribes($statid, $start, $perpage, $token_data['calendar_restrictions']['unsubscribes'], true, '', '');

						$this->_SetupPaging($total_unsubscribes, $DisplayPage, $perpage, '', 'triggeremails_unsubscribes', $_GET['token']);

						$paging = $this->ParseTemplate('Stats_Remote_Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$unsub_list = '';
						foreach ($unsubscribes as $k => $unsubdetails) {
							$GLOBALS['EmailAddress'] = htmlspecialchars($unsubdetails['emailaddress'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['UnsubscribeTime'] = $this->PrintTime($unsubdetails['unsubscribetime'], true);
							$unsub_list .= $this->ParseTemplate('Stats_Step3_Unsubscribes_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Unsubscribes_List'] = $unsub_list;

						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Unsubscribes_Table');
					break; // triggeremails_unsubscribes

					case 'triggeremails_forwards':
						$forwards = array();

						$statid = $token_data['statid'];

						if ($summary['emailforwards'] > 0) {
							$forwards = $statsapi->GetForwards($statid, $start, $perpage, $token_data['calendar_restrictions']['forwards'], false, false, $this->column, $this->sort);
						}
						$total_forwards = $statsapi->GetForwards($statid, $start, $perpage, $token_data['calendar_restrictions']['forwards'], true);
						$this->_SetupPaging($total_forwards, $DisplayPage, $perpage, '', 'triggeremails_forwards', $_GET['token']);

						$paging = $this->ParseTemplate('Paging', true, false);

						$GLOBALS['Paging'] = $paging;

						$forward_list = '';
						foreach ($forwards as $k => $forwarddetails) {
							$GLOBALS['ForwardedTo'] = htmlspecialchars($forwarddetails['forwardedto'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['ForwardedBy'] = htmlspecialchars($forwarddetails['forwardedby'], ENT_QUOTES, SENDSTUDIO_CHARSET);
							$GLOBALS['ForwardTime'] = $this->PrintTime($forwarddetails['forwardtime'], true);
							if ($forwarddetails['subscribed'] > 0) {
								$hassubscribed = GetLang('Yes');
							} else {
								$hassubscribed = GetLang('No');
							}
							$GLOBALS['HasSubscribed'] = $hassubscribed;
							$forward_list .= $this->ParseTemplate('Stats_Step3_Forwards_Row', true, false);
						}

						$GLOBALS['Stats_Step3_Forwards_List'] = $forward_list;

						if (isset($_GET['pagination']) && $_GET['pagination'] == 'false') {
							$GLOBALS['PagingBottom'] = $GLOBALS['Paging'] = '';
						}

						echo $this->ParseTemplate('Stats_Step3_Forwards_Table');
					break; // triggeremails_forwards

					default:
					break;
				} // switch type
			break; //export
		} // switch selectaction
	}
	private function _handleSubmitAction()
	{
		// don't escape
		$template_dir = SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/templates';
		$this->_template = 	 GetTemplateSystem($template_dir);

		$this->_template->DefaultHtmlEscape = false;

		$formId      = (int) IEM::requestGetGET('formId');
		$postWidgets = IEM::requestGetPOST('widget');

		// If there are files, take the values and place them in the $postWidgets array so they can
		// get validated and entered into the response values in the same manner. Uploads will be
		// handled separately.

		if (isset($_FILES['widget'])) {
			foreach ($_FILES['widget']['name'] as $widgetId => $widget) {
				foreach ($widget as $fields) {
					foreach ($fields as $fieldId => $field) {
						$postWidgets[$widgetId]['field'][$fieldId]['value'] = 'file_' . $field['value'];
					}
				}
			}
		}

		// If the form and widgets weren't posted in the format we require then redirect back
		if (!$formId) {
			$this->redirectToReferer();
		}

		$surveyApi = $this->getApi();
		$surveyApi->Load($formId);
		$surveyData = $surveyApi->GetData();

		$errors       = 0;
		$widgets      = $surveyApi->getWidgets($formId);
		$widgetErrors = array();


		/****  START OF ERROR VALIDATION ****/

		// compile a list of widget ids so we can check the posted widgets against a list of
		// valid widget ids


		foreach ($widgets as $widgetKey => $widget) {

			if (!isset($widgetErrors[$widget['id']])) {
				$widgetErrors[$widget['id']] = array();
			}

			// validate required fields
			if ($widget['is_required']) {
				// the widget is assumed blank until one of it's fields is found not blank
				$isBlank = true;
				$isOther = false;


				// make sure the required widget was even posted

				if (isset($postWidgets[$widget['id']])) {
					foreach ($postWidgets[$widget['id']]['field'] as $field) {
						if (isset($field['value'])) {
							$values = (array) $field['value'];

							foreach ($values as $value) {

								// get the value of an "other" field if it is one, otherwise just grab
								// the normal value
								if ($value == '__other__') {
									$isOther = true;
									$value   = $field['other'];
								}

								// make sure the value isn't blank
								if ($this->_validateIsBlank($value) !== true) {
									$isBlank = false;
								}
							}
						}
					}
				}

				// if the widget is blank, flag an error
				if ($isBlank) {
					if ($isOther) {
						$error = GetLang('Addon_Surveys_ErrorRequiredOther');
					} else {
						$error = GetLang('Addon_Surveys_ErrorRequired');
					}
					$widgetErrors[$widget['id']][] = $error;
					$errors++;
				}
				
				if ($widget['type'] == 'file') {
					foreach ($postWidgets[$widget['id']]['field'] as $fieldid) {
						if (isset($fieldid['value'])) {$uploaded_file = $fieldid['value'];break;}
					}
					if (empty($uploaded_file) || $uploaded_file == "file_") {
						$error = GetLang('Addon_Surveys_ErrorRequired');
						$widgetErrors[$widget['id']][] = $error;
						$errors++;
					}					
				}
			}




			// validate file types
			if ($widget['type'] == 'file') {
				
				if (!empty($widget['allowed_file_types'])) {
					$typeArr     = preg_split('/\s*,\s*/', strtolower($widget['allowed_file_types']));
					$invalidType = false;


					// foreach of the passed fields (most likely 1) check and see if they are valid file types
					foreach ($postWidgets[$widget['id']]['field'] as $field) {
						$parts = explode('.', $field['value']);
						$ext   = strtolower(end($parts));



						// only if the field has a value we will test its file type
						if (trim($field['value']) != '' && !in_array($ext, $typeArr)) {
							$invalidType = true;
						}
					}

					// if the a file is not a valid file type, then the whole widget fails validation
					if ($invalidType) {
						$lastFileType   = '<em>.' . array_pop($typeArr) . '</em>';
						$firstFileTypes = '<em>.' . implode('</em>, <em>.', $typeArr) . '</em>';
						$widgetErrors[$widget['id']][] = sprintf(GetLang('Addon_Surveys_ErrorInvalidFileType'), $lastFileType, $firstFileTypes);
						$errors++;
					}
				}
			}

			if (isset($postWidgets[$widget['id']])) {
				// add a value to the values array so it can be passed to the email feedback template
				@$widgets[$widgetKey]['values'] = $postWidgets[$widget['id']]['field'];
			}
		}

		// if there were errors, redirect back and display the errors
		if ($errors) {
			// set a global error message to alert the user to the specific errors
			IEM::sessionSet('survey.addon.' . $formId . '.errorMessage', $surveyData['error_message']);
			// set the widget errors so we can retrieve them for the user
			IEM::sessionSet('survey.addon.' . $formId . '.widgetErrors', $widgetErrors);
			$this->redirectToReferer();
		}

		/****  END OF ERROR VALIDATION ****/

		// isntantiate a new response object
		$response = $this->getSpecificApi('responses');

		// associate the response to a particular form
		$response->surveys_id = $formId;

		// if the response was saved, then associate values to the response
		if ($response->Save()) {
			// foreach of the posted widgets, check to see if it belongs in this form and save it if it does

			foreach ($postWidgets as $postWidgetId => $postWidget) {
				// iterate through each field and enter it in the feedback

				foreach ($postWidget['field'] as $field) {
					// make sure it has a value first

					if (isset($field['value'])) {
						// since multiple values can be given, we treat them as an array
						$values = (array) $field['value'];

						foreach ($values as $value) {

							$responseValue = $this->getSpecificApi('responsesvalue');
							// foreign key for the response id
							$responseValue->surveys_response_id = $response->GetId();

							// set the widget id foreign key; widgets can have multiple field values and
							// should be treated as such
							$responseValue->surveys_widgets_id =  $postWidgetId;

							// set the value of the feedback; this should be a single value since widgets
							// can have multiple feed back values
							if ($value == '__other__') {
								$responseValue->value =  $field['other'];
								$responseValue->is_othervalue = 1;
							} else {
								// if file value exist we need to save the md5 name of the file in the database
								$responseValue->file_value = "";
								if (substr($value, 0, 5) == "file_") {
									$value = str_replace("file_", "", $value);
									$responseValue->file_value = md5($value);
								}

								$responseValue->value = $value;
								$responseValue->is_othervalue = 0;
							}

							// save it
							$responseValue->Save();
						}

					}
				}
			}

			// send an email if desired
			/**
			 *  Prepare for sending the email..
			 */

			$widget_api = $this->getSpecificApi('widgets');

			if ($surveyData['email_feedback']) {
				foreach ($widgets as &$widget) {
					$widget_api->populateFormData($widget);

					// set the values (normally 1, unless it's a list of checkboxes)
					$widget['values'] = $widget_api->getResponseValues($response->id);

					// get the other value
					$other = $widget_api->getOtherField();

					// add the full url to the file
					if ($widget['type'] == 'file') {
						$attachment_url = "admin/index.php?Page=Addons&Addon=surveys&Action=DownloadAttach&ajax=1&formId=" . $formId . "&responseId=" . $response->id . "&value=" . base64_encode($widget['values'][0]['value']);
						$attachment_tag =  SENDSTUDIO_APPLICATION_URL . "/" .  $attachment_url;
						// . "'>" . $widget['values'][0]['value'];
						$widget['values'][0]['value'] = $attachment_tag;
					}

					if ($other) {
						// the other value will be the last one
						$otherValueIndex = count($widget['values']) - 1;
						$widget['values'][$otherValueIndex]['value'] = $other['other_label_text'] . ' ' . $widget['values'][$otherValueIndex]['value'];
					}
				}


				$viewUri = SENDSTUDIO_APPLICATION_URL
					 . '/admin/index.php?Page=Addons&Addon=surveys&Action=viewresponses&surveyId='
					 . $surveyApi->id
					 . '&responseId='
					 . $response->id;
				$editUri = SENDSTUDIO_APPLICATION_URL
					 . '/admin/index.php?Page=Addons&Addon=surveys&Action=editresponse&surveyId='
					 . $surveyApi->id
					 . '&responseId='
					 . $response->id;

				$this->_template->Assign('form', $surveyApi->GetData());
				$this->_template->Assign('widgets', $widgets);
				$this->_template->Assign('emailBodyStart', sprintf(GetLang('Addon_Surveys_emailBodyStart'), $surveyApi->Get('name')));
				$this->_template->Assign('emailViewLink', sprintf(GetLang('Addon_Surveys_emailViewLink'), $viewUri));
				$this->_template->Assign('emailEditLink', sprintf(GetLang('Addon_Surveys_emailEditLink'), $editUri));

				// parse the email template for its content
				$emailTemplate = $this->_template->ParseTemplate('email', true);

				require_once(IEM_PATH . '/ext/interspire_email/email.php');
				$emailapi = new Email_API();

				$emailapi->SetSmtp(SENDSTUDIO_SMTP_SERVER, SENDSTUDIO_SMTP_USERNAME, @base64_decode(SENDSTUDIO_SMTP_PASSWORD), SENDSTUDIO_SMTP_PORT);
				//if ($this->smtpserver) {
				//	$emailapi->SetSmtp($this->smtpserver, $this->smtpusername, $this->smtppassword, $this->smtpport);
				//}

				$emailapi->ClearRecipients();
				$emailapi->ForgetEmail();
				$emailapi->Set('forcechecks', false);

				$to = ($surveyApi->Get('email'));
				$emailapi->AddRecipient($to);

				$emailapi->Set('FromAddress', (defined('SENDSTUDIO_EMAIL_ADDRESS') ? SENDSTUDIO_EMAIL_ADDRESS : $userobject->emailaddress));
				$emailapi->Set('BounceAddress', SENDSTUDIO_EMAIL_ADDRESS);
				$emailapi->Set('CharSet', SENDSTUDIO_CHARSET);

				$subject = sprintf(GetLang('Addon_Surveys_emailSubject'), $surveyApi->Get('name'));
				$emailapi->Set('Subject', $subject);


				//email body
				$emailapi->AddBody('text', $emailTemplate);
				$status = $emailapi->Send();
				if ($status['success'] != 1) {
					trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Was not able to send email: ' . serialize($status['failed']), E_USER_NOTICE);
					return false;
				}
			}

			// perform file uploading

			if (isset($_FILES['widget']['name'])) {
				$files = $_FILES['widget']['name'];

				foreach ($files as $widgetId => $widget) {
					foreach ($widget as $widgetKey => $fields) {
						foreach ($fields as $fieldId => $field) {
							// gather file information
							$name    = $_FILES['widget']['name'][$widgetId]['field'][$fieldId]['value'];
							$type    = $_FILES['widget']['type'][$widgetId]['field'][$fieldId]['value'];
							$tmpName = $_FILES['widget']['tmp_name'][$widgetId]['field'][$fieldId]['value'];
							$error   = $_FILES['widget']['error'][$widgetId]['field'][$fieldId]['value'];
							$size    = $_FILES['widget']['size'][$widgetId]['field'][$fieldId]['value'];

							// if the upload was successful to the temporary folder, move it
							if ($error == UPLOAD_ERR_OK) {
								$tempdir   = TEMP_DIRECTORY;
								$upBaseDir = $tempdir . DIRECTORY_SEPARATOR . 'surveys';
								$upSurveyDir = $upBaseDir . DIRECTORY_SEPARATOR . $formId;
								$upDir     = $upSurveyDir . DIRECTORY_SEPARATOR . $response->GetId();

								// if the base upload directory doesn't exist create it
								if (!is_dir($upBaseDir)) {
									mkdir($upBaseDir, 0755);
								}

								if (!is_dir($upSurveyDir)) {
									mkdir($upSurveyDir, 0755);
								}

								// if the upload directory doesn't exist create it
								if (!is_dir($upDir)) {
									mkdir($upDir, 0755);
								}

								// upload the file
								move_uploaded_file($tmpName, $upDir . DIRECTORY_SEPARATOR . $name);
							}
						}
					}
				}
			}
		}

		// if we are redirecting to a url, redirect them
		switch ($surveyData['after_submit']) {
			case 'show_uri':
				header('Location: ' . $surveyApi->show_uri);
				exit;
			break;

			case 'show_message':
				IEM::sessionSet('survey.addon.' . $formId . '.successMessage', $surveyApi->show_message);

			default:
				// redirect back
				$this->redirectToReferer();
		}
	}
	/**
	* EditAutoresponderStep4
	* Loads up step 4 of editing an autoresponder which is editing the actual content.
	* If you pass in an autoresponderid, it will load it up and set the appropriate language variables.
	*
	* @param Int $autoresponderid AutoresponderID to edit.
	*
	* @return Void Prints out step 4, doesn't return anything.
	*/
	function EditAutoresponderStep4($autoresponderid=0)
	{

		$autoapi = $this->GetApi();
		$autorespondercontents = array('text' => '', 'html' => '');

		$this->DisplayCronWarning();

		$user = GetUser();
		$GLOBALS['FromPreviewEmail'] = $user->Get('emailaddress');

		//$GLOBALS['DisplayAttachmentsHeading'] = 'none';
		$tpl = GetTemplateSystem();
		if ($autoresponderid > 0) {
			$GLOBALS['SaveAction'] = 'Edit&SubAction=Save&id=' . $autoresponderid;
			$GLOBALS['Heading'] = GetLang('EditAutoresponder');
			$GLOBALS['Intro'] = GetLang('EditAutoresponderIntro_Step4');
			$GLOBALS['Action'] = 'Edit&SubAction=Complete&id=' . $autoresponderid;
			$GLOBALS['CancelButton'] = GetLang('EditAutoresponderCancelButton');

			$autoapi->Load($autoresponderid);
			$autorespondercontents['text'] = $autoapi->GetBody('text');
			$autorespondercontents['html'] = $autoapi->GetBody('html');

			$GLOBALS['Subject'] = htmlspecialchars($autoapi->subject, ENT_QUOTES, SENDSTUDIO_CHARSET);

		} else {

			$GLOBALS['SaveAction'] = 'Create&SubAction=Save&id=' . $autoresponderid;
			$GLOBALS['Heading'] = GetLang('CreateAutoresponder');
			$GLOBALS['Intro'] = GetLang('CreateAutoresponderIntro_Step4');
			$GLOBALS['Action'] = 'Create&SubAction=Complete';
			$GLOBALS['CancelButton'] = GetLang('CreateAutoresponderCancelButton');
		}

		if (SENDSTUDIO_ALLOW_ATTACHMENTS) {
				$attachmentsarea = strtolower(get_class($this));
				$attachments_list = $this->GetAttachments($attachmentsarea, $autoresponderid);
				$GLOBALS['AttachmentsList'] = $attachments_list;
				$tpl->Assign('ShowAttach', true);
		} else {
			$GLOBALS['DisplayAttachments'] = 'none';
			$user = IEM::getCurrentUser();
			if($user) {
				if ($user->isAdmin()) {
					$GLOBALS['AttachmentsMsg'] = GetLang('NoAttachment_Admin');
				} else {
					$GLOBALS['AttachmentsMsg'] = GetLang('NoAttachment_User');
				}
			}
			$tpl->Assign('ShowAttach', false);
		}

		$GLOBALS['PreviewID'] = $autoresponderid;

		// we don't really need to get/set the stuff here.. we could use references.
		// if we do though, it segfaults! so we get and then set the contents.
		$session_autoresponder = IEM::sessionGet('Autoresponders');

		$GLOBALS['List'] = $session_autoresponder['list'];

		if (isset($session_autoresponder['TemplateID'])) {
			$templateApi = $this->GetApi('Templates');
			if (is_numeric($session_autoresponder['TemplateID'])) {
				$templateApi->Load($session_autoresponder['TemplateID']);
				$autorespondercontents['text'] = $templateApi->textbody;
				$autorespondercontents['html'] = $templateApi->htmlbody;
			} else {
				$autorespondercontents['html'] = $templateApi->ReadServerTemplate($session_autoresponder['TemplateID']);
			}
			unset($session_autoresponder['TemplateID']);
		}

		$session_autoresponder['id'] = (int)$autoresponderid;

		$session_autoresponder['contents'] = $autorespondercontents;

		// we use the lowercase variable when we save, but the editor expects the uppercased version.
		$session_autoresponder['Format'] = $session_autoresponder['format'];

		IEM::sessionSet('Autoresponders', $session_autoresponder);
		$editor = $this->FetchEditor();
		$GLOBALS['Editor'] = $editor;

		unset($session_autoresponder['Format']);
		$GLOBALS['MaxFileSize'] = SENDSTUDIO_ATTACHMENT_SIZE*1024;

		$user = GetUser();
		if ($user->Get('forcespamcheck')) {
			$GLOBALS['ForceSpamCheck'] = 1;
		}

		$tpl->ParseTemplate('Autoresponder_Form_Step4');
	}
	protected function printEditor($record = array())
	{
		$user               = IEM::userGetCurrent();
		$group              = new record_UserGroups($record);
		$permissionList     = $user->getProcessedPermissionList();
		$availableLists     = $user->GetLists();
		$availableSegments  = $user->GetSegmentList();
		$availableTemplates = $user->GetTemplates();
		$requestToken       = md5(mt_rand());

		$page = array(
			'messages' => GetFlashMessages()
		);

		IEM::sessionSet('UsersGroups_Editor_RequestToken', $requestToken);

		if (!isset($record['permissions']) || !is_array($record['permissions'])) {
			$record['permissions'] = array();
		}

		if (!isset($record['access']) || !is_array($record['access'])) {
			$record['access'] = array();
		}

		$record['permissions_stupid_template'] = array();
		
		if (isset($record['permissions'])) {
			foreach ($record['permissions'] as $key => $value) {
				foreach ($value as $each) {
					$record['permissions_stupid_template'][] = "{$key}.{$each}";
				}
			}
		}
		
		$this->PrintHeader();
		
		$tpl = GetTemplateSystem();
		$tpl->Assign('PAGE', $page);
		$tpl->Assign('record', $record);
		$tpl->Assign('permissionList', $permissionList);
		$tpl->Assign('isSystemAdmin', $group->isAdmin());
		$tpl->Assign('isLastAdminWithUsers', $group->isLastAdminWithUsers());
		$tpl->Assign('availableLists', $availableLists, true);
		$tpl->Assign('availableSegments', $availableSegments, true);
		$tpl->Assign('availableTemplates', $availableTemplates, true);
		$tpl->Assign('requestToken', $requestToken);

		$tpl->ParseTemplate('UsersGroups_Form');

		$this->PrintFooter();

		return;
	}
    /**
     * DisplayEditNewsletter
     * Prints out the editor for stage 2 of editing a newsletter (the wysiwyg area or textarea depending on the format chosen in stage 1). If you have selected a template in the previous step, the content from that template will be displayed here.
     *
     * @param Int $newsletterid Newsletter to load up. If there is one, it will pre-load that content. If there is no newsletterid, it displays a blank area to create your content.
     *
     * @see CreateNewsletter
     * @see EditNewsletter
     * @see GetApi
     * @see Newsletter_API::Load
     * @see Newsletter_API::GetBody
     * @see GetAttachments
     * @see FetchEditor
     *
     * @return Void Prints out the form, doesn't return anything.
     */
    function DisplayEditNewsletter($newsletterid=0) {
        $newsletter = $this->GetApi();
        $newslettercontents = array('text' => '', 'html' => '');

        $user = GetUser();

        $GLOBALS['FromPreviewEmail'] = $user->Get('emailaddress');

        $GLOBALS['DisplayAttachmentsHeading'] = 'none';

        $tpl = GetTemplateSystem();


        if ($newsletterid > 0) {
            $GLOBALS['SaveAction'] = 'Edit&SubAction=Save&id=' . $newsletterid;
            $GLOBALS['Heading'] = GetLang('EditNewsletter');
            $GLOBALS['Intro'] = GetLang('EditNewsletterIntro_Step2');
            $GLOBALS['Action'] = 'Edit&SubAction=Complete&id=' . $newsletterid;
            $GLOBALS['CancelButton'] = GetLang('EditNewsletterCancelButton');

            $newsletter->Load($newsletterid);
            $GLOBALS['IsActive'] = ($newsletter->Active()) ? ' CHECKED' : '';
            $GLOBALS['Archive'] = ($newsletter->Archive()) ? ' CHECKED' : '';
            $newslettercontents['text'] = $newsletter->GetBody('text');
            $newslettercontents['html'] = $newsletter->GetBody('html');

            $GLOBALS['Subject'] = htmlspecialchars($newsletter->subject, ENT_QUOTES, SENDSTUDIO_CHARSET);
        } else {
            $GLOBALS['SaveAction'] = 'Create&SubAction=Save&id=' . $newsletterid;
            $GLOBALS['Heading'] = GetLang('CreateNewsletter');
            $GLOBALS['Intro'] = GetLang('CreateNewsletterIntro_Step2');
            $GLOBALS['Action'] = 'Create&SubAction=Complete';
            $GLOBALS['CancelButton'] = GetLang('CreateNewsletterCancelButton');

            $GLOBALS['IsActive'] = ' CHECKED';
            $GLOBALS['Archive'] = ' CHECKED';
        }

        if (!SENDSTUDIO_ALLOW_ATTACHMENTS) {
            $tpl->Assign('ShowAttach', false);
            $GLOBALS['DisplayAttachments'] = 'none';
            $user = IEM::getCurrentUser();
            if ($user) {
                if ($user->isAdmin()) {
                    $GLOBALS['AttachmentsMsg'] = GetLang('NoAttachment_Admin');
                } else {
                    $GLOBALS['AttachmentsMsg'] = GetLang('NoAttachment_User');
                }
            }
        } else {
            $tpl->Assign('ShowAttach', true);
            $attachmentsarea = strtolower(get_class($this));
            $attachments_list = $this->GetAttachments($attachmentsarea, $newsletterid);
            $GLOBALS['AttachmentsList'] = $attachments_list;
        }

        $GLOBALS['PreviewID'] = $newsletterid;
        // we don't really need to get/set the stuff here.. we could use references.
        // if we do though, it segfaults! so we get and then set the contents.
        $session_newsletter = IEM::sessionGet('Newsletters');
        $session_newsletter['id'] = (int) $newsletterid;

        if (isset($session_newsletter['TemplateID'])) {
            $templateApi = $this->GetApi('Templates');
            if (is_numeric($session_newsletter['TemplateID'])) {
                $templateApi->Load($session_newsletter['TemplateID']);
                $newslettercontents['text'] = $templateApi->textbody;
                $newslettercontents['html'] = $templateApi->htmlbody;
            } else {
                $newslettercontents['html'] = $templateApi->ReadServerTemplate($session_newsletter['TemplateID']);
            }
            unset($session_newsletter['TemplateID']);
        }

        $session_newsletter['contents'] = $newslettercontents;
        IEM::sessionSet('Newsletters', $session_newsletter);
        $editor = $this->FetchEditor();
        $GLOBALS['Editor'] = $editor;

        $user = GetUser();
        if ($user->group->forcespamcheck) {
            $GLOBALS['ForceSpamCheck'] = 1;
        }

        $tpl->ParseTemplate('Newsletter_Form_Step2');
    }
Example #22
0
//}

// Make sure that the IEM controller does NOT redirect request.
if (!defined('IEM_NO_CONTROLLER')) {
	define('IEM_NO_CONTROLLER', true);
}

if (empty($_GET['id'])) {
	echo "Invalid Id";
	exit();
}

$surveyId = $_GET['id'];

/**
 * Require base sendstudio functionality. This connects to the database, sets up our base paths and so on.
 *
 */
require_once dirname(__FILE__) . '/admin/index.php';
require_once SENDSTUDIO_FUNCTION_DIRECTORY . '/sendstudio_functions.php';
require_once SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/api/surveys.php';


// now use the API...

$tpl = GetTemplateSystem('admin/addons/surveys/templates');
$survey_api = new Addons_survey_api();
$survey_api->getSurveyContent($surveyId, $tpl)


?>