Esempio n. 1
0
	/**
	 * RunUpgrde
	 * Run current upgrade
	 * @return Boolean Returns TRUE if successful, FALSE otherwise
	 */
	function RunUpgrade()
	{
		$new_version = '20081215';

		$errors = IEM::sessionGet('DatabaseUpgradesFailed');

		if (empty($errors)) {
			$query = 'UPDATE ' . SENDSTUDIO_TABLEPREFIX . 'settings SET database_version=' . $new_version;
			$result = $this->Db->Query($query);
			return $result;
		}

		return false;
	}
Esempio n. 2
0
	/**
	* Process
	* All the action happens here.
	* If you are not logged in, it will print the login form.
	* Submitting that form will then try to authenticate you.
	* If you are successfully authenticated, you get redirected back to the main index page (quickstats etc).
	* Otherwise, will show an error message and the login form again.
	*
	* @see ShowLoginForm
	* @uses AuthenticationSystem::Authenticate()
	*
	* @return Void Doesn't return anything. Checks the action and passes it off to the appropriate area.
	*/
	function Process()
	{
		$action = IEM::requestGetGET('Action', '', 'strtolower');
		switch ($action) {
			case 'forgotpass':
				$this->ShowForgotForm();
			break;

			case 'changepassword':
				if (!IEM::sessionGet('ForgotUser')) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				$userapi = GetUser(-1);
				$loaded = $userapi->Load(IEM::sessionGet('ForgotUser'));

				if (!$loaded) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				$password = IEM::requestGetPOST('ss_password', false);
				$confirm = IEM::requestGetPOST('ss_password_confirm', false);

				if ($password == false || ($password != $confirm)) {
					$this->ShowForgotForm_Step2($userapi->Get('username'), 'login_error', GetLang('PasswordsDontMatch'));
					break;
				}

				$userapi->password = $password;
				$userapi->Save();

				$code = md5(uniqid(rand(), true));

				$userapi->ResetForgotCode($code);

				$this->ShowLoginForm('login_success', GetLang('PasswordUpdated'));
			break;

			case 'sendpass':
				$user = GetUser(-1);
				$username = IEM::requestGetPOST('ss_username', '');

				/**
				 * Fix vulnerabilities with MySQL
				 * Documented here: http://www.suspekt.org/2008/08/18/mysql-and-sql-column-truncation-vulnerabilities/
				 *
				 * Basically MySQL is truncating values in a column
				 */
					$username = preg_replace('/\s+/', ' ', $username);
					$username = trim($username);
				/**
				 * -----
				 */

				$founduser = $user->Find($username);
				if (!$founduser) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Forgot'));
					break;
				}

				$user->Load($founduser, false);

				$code = md5(uniqid(rand(), true));

				$user->ResetForgotCode($code);

				$link = SENDSTUDIO_APPLICATION_URL . '/admin/index.php?Page=Login&Action=ConfirmCode&user='******'&code=' . $code;

				$message = sprintf(GetLang('ChangePasswordEmail'), $link);

				$email_api = $this->GetApi('Email');
				$email_api->Set('CharSet', SENDSTUDIO_CHARSET);
				$email_api->Set('Multipart', false);
				$email_api->AddBody('text', $message);
				$email_api->Set('Subject', GetLang('ChangePasswordSubject'));

				$email_api->Set('FromAddress', SENDSTUDIO_EMAIL_ADDRESS);
				$email_api->Set('ReplyTo', SENDSTUDIO_EMAIL_ADDRESS);
				$email_api->Set('BounceAddress', SENDSTUDIO_EMAIL_ADDRESS);

				$email_api->SetSmtp(SENDSTUDIO_SMTP_SERVER, SENDSTUDIO_SMTP_USERNAME, @base64_decode(SENDSTUDIO_SMTP_PASSWORD), SENDSTUDIO_SMTP_PORT);

				$user_fullname = $user->Get('fullname');

				$email_api->AddRecipient($user->emailaddress, $user_fullname, 't');

				$email_api->Send();

				$this->ShowForgotForm_Step2($username,'login_success', sprintf(GetLang('ChangePassword_Emailed'), $user->emailaddress));
			break;

			case 'confirmcode':
				$user = IEM::requestGetGET('user', false, 'intval');
				$code = IEM::requestGetGET('code', false, 'trim');

				if (empty($user) || empty($code)) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				$userapi = GetUser(-1);
				$loaded = $userapi->Load($user, false);

				if (!$loaded || $userapi->Get('forgotpasscode') != $code) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				IEM::sessionSet('ForgotUser', $user);

				$this->ShowForgotForm_Step2($userapi->Get('username'));
			break;

			case 'login':
				$auth_system = new AuthenticationSystem();
				$username = IEM::requestGetPOST('ss_username', '');
				$password = IEM::requestGetPOST('ss_password', '');
				$result = $auth_system->Authenticate($username, $password);
				if ($result === -1) {
					$this->ShowLoginForm('login_error', GetLang('PleaseWaitAWhile'));
					break;
				} elseif ($result === -2) {
					$this->ShowLoginForm('login_error', GetLang('FreeTrial_Expiry_Login'));
					break;
				} elseif (!$result) {
					$this->ShowLoginForm('login_error', GetLang('BadLogin'));
					break;
				} elseif ($result && defined('IEM_SYSTEM_ACTIVE') && !IEM_SYSTEM_ACTIVE) {
					$msg = (isset($result['admintype']) && $result['admintype'] == 'a') ? 'ApplicationInactive_Admin' : 'ApplicationInactive_Regular';
					$this->ShowLoginForm('login_error', GetLang($msg));
					break;
				}

                $user = false;
                $rand_check = false;

				IEM::userLogin($result['userid']);

				$oneyear = 365 * 24 * 3600; // one year's time.

				$redirect = $this->_validateTakeMeToRedirect(IEM::requestGetPOST('ss_takemeto', 'index.php'));

				header('Location: ' . SENDSTUDIO_APPLICATION_URL . '/admin/' . $redirect);
				exit();
			break;

			default:
				$msg = false; $template = false;
				if ($action == 'logout') {
					$this->LoadLanguageFile('Logout');
				}
				$this->ShowLoginForm($template, $msg);
			break;
		}
	}
Esempio n. 3
0
	/**
	* ViewSubscriber
	* Prints the 'view subscriber' page and all appropriate options including custom fields.
	*
	* @param Int $listid The list the subscriber is on. This is checked to make sure the user has 'manage' access to the list before anything else.
	* @param Int $subscriberid The subscriberid to view.
	* @param Int $segmentid The ID of the segment that the subscriber is going to be fetched from
	* @param String $msgtype The heading to show when viewing a subscriber. This can be either error or success. Used with $msg to display something.
	* @param String $msg The message to display in the heading. If this is not present, no message is displayed.
	*
	* @see GetApi
	* @see Subscribers_API::GetCustomFieldSettings
	* @see Lists_API::GetCustomFields
	* @see Lists_API::Load
	* @see Lists_API::GetListFormat
	*
	* @return Void Doesn't return anything. Prints out the view form and that's it.
	*/
	function ViewSubscriber($listid = 0, $subscriberid = 0, $segmentid = 0, $msgtype = 'Error', $msg = false)
	{
		$user = GetUser();
		$access = $user->HasAccess('Subscribers', 'Manage');
		if (!$access) {
			$this->DenyAccess();
			return;
		}

		$this->SetupGoogleCalendar();

		$search_info = IEM::sessionGet('Search_Subscribers');

		$GLOBALS['list'] = $listid;

		if ($msg && $msgtype) {
			switch (strtolower($msgtype)) {
				case 'success':
					$GLOBALS['Success'] = $msg;
					$GLOBALS['Message'] = $this->ParseTemplate('SuccessMsg', true, false);
				break;
				default:
					$GLOBALS['Error'] = $msg;
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
			}
		}

		$SubscriberApi = $this->GetApi('Subscribers');
		$subscriberinfo = false;

		/**
		 * Get Subscriber record from the database
		 */
			$adminAccess = false;

			// If this user is an admin/list admin/list admintype == a then give permission
			if ($user->Admin() || $user->ListAdminType() == 'a' || $user->ListAdmin()) {
				$adminAccess = true;
			}

			// Get subscribers from list
			if ($segmentid == 0) {
				if (!$adminAccess && !$SubscriberApi->CheckPermission($user->userid, $subscriberid)) {
					$this->DenyAccess();
					return;
				}

				$subscriberinfo = $SubscriberApi->LoadSubscriberList($subscriberid, $listid);


			// Get subscribers from segment
			} else {
				if (!$adminAccess) {
					$segmentapi = $this->GetApi('Segment', true);
					$segmentapi->Load($segmentid);

					if ($segmentapi->ownerid != $user->userid && !$user->HasAccess('Segments', 'View', $segmentid)) {
						$this->DenyAccess();
						return;
					}
				}

				$subscriberinfo = $SubscriberApi->LoadSubscriberSegment($subscriberid, $segmentid);
			}
		/**
		 * -----
		 */

		// hmm, the subscriber doesn't exist or can't be loaded? show an error.
		if (empty($subscriberinfo)) {
			$GLOBALS['ErrorMessage'] = GetLang('SubscriberDoesntExist_View');
			$this->DenyAccess();
			return;
		}

		// Log this to "User Activity Log"
		$logURL = SENDSTUDIO_APPLICATION_URL . '/admin/index.php?Page=Subscribers&Action=Edit&List=' . $_GET['List'] . '&id=' . $_GET['id'];
		IEM::logUserActivity($logURL, 'images/contacts_view.gif', $subscriberinfo['emailaddress']);

		$list_api = $this->GetApi('Lists');
		$list_api->Load($listid);

		$GLOBALS['emailaddress'] = $subscriberinfo['emailaddress'];
		$GLOBALS['subscriberid'] = $subscriberid;

		if ($subscriberinfo['requestdate'] == 0) {
			$GLOBALS['requestdate'] = GetLang('Unknown');
		} else {
			$GLOBALS['requestdate'] = $this->PrintTime($subscriberinfo['requestdate']);
		}

		$GLOBALS['requestip'] = ($subscriberinfo['requestip'] == '') ? GetLang('Unknown') : $subscriberinfo['requestip'];

		if ($subscriberinfo['confirmdate'] == 0) {
			$GLOBALS['confirmdate'] = GetLang('Unknown');
		} else {
			$GLOBALS['confirmdate'] = $this->PrintTime($subscriberinfo['confirmdate']);
		}

		$GLOBALS['confirmip'] = ($subscriberinfo['confirmip'] == '') ? GetLang('Unknown') : $subscriberinfo['confirmip'];

		if ($subscriberinfo['confirmed'] == 1) {
			$confirmed = 'Confirmed';
		} elseif ($subscriberinfo['confirmed'] == 0) {
			$confirmed = 'Unconfirmed';
		}

		$GLOBALS['ConfirmedList'] = GetLang($confirmed);

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

		$subscriber_status = 'a';
		if ($subscriberinfo['unsubscribed'] > 0) {
			$subscriber_status = 'u';
			$GLOBALS['unsubscribetime'] = $this->PrintTime($subscriberinfo['unsubscribed']);
			$GLOBALS['unsubscribeip'] = ($subscriberinfo['unsubscribeip'] == '') ? GetLang('Unknown') : $subscriberinfo['unsubscribeip'];
			$GLOBALS['ShowUnsubscribeInfo'] = '';
		}

		if ($subscriberinfo['bounced'] > 0) {
			$subscriber_status = 'b';
		}

		switch ($subscriber_status) {
			case 'a':
				$status = 'Active';
			break;

			case 'u':
				$status = 'Unsubscribed';
			break;

			case 'b':
				$status = 'Bounced';
			break;

			default:
		}

		// this is used both by the 'edit' and 'delete' buttons.
		$GLOBALS['subscriberid'] = $subscriberid;
		if ($segmentid != 0) {
			$GLOBALS['SegmentID'] = $segmentid;
			$GLOBALS['ExtraParameter'] = '&SegmentID=' . $segmentid;
		} else {
			$GLOBALS['SegmentID'] = 0;
			$GLOBALS['ExtraParameter'] = '';
		}

		$GLOBALS['EditButton'] = '';
		if ($user->HasAccess('Subscribers', 'Edit')) {
			$GLOBALS['EditButton'] = $this->ParseTemplate('Subscribers_View_Button_Edit', true, false);
		}

		$GLOBALS['DeleteButton'] = '';
		if ($user->HasAccess('Subscribers', 'Delete')) {
			$GLOBALS['DeleteButton'] = $this->ParseTemplate('Subscribers_View_Button_Delete', true, false);
		}

		$GLOBALS['StatusList'] = GetLang($status);

		$listformat = $list_api->GetListFormat();

		if ($subscriberinfo['format'] == 'h') {
			$format = GetLang('Format_HTML');
		} elseif ($subscriberinfo['format'] == 't') {
			$format = GetLang('Format_Text');
		}

		$GLOBALS['FormatList'] = $format;

		$customfields = $list_api->GetCustomFields($listid);

		$customfield_display = array();
		$customfieldinfo = '';

		if (!empty($customfields)) {
			$customfields_api = $this->GetApi('CustomFields');

			$customfieldinfo .= $this->ParseTemplate('Subscribers_Edit_Step2_CustomFields', true, false);
			foreach ($customfields as $pos => $customfield_info) {
				$GLOBALS['FieldID'] = $customfield_info['fieldid'];
				if ($customfield_info['required']) {
					$GLOBALS['Required'] = $this->ParseTemplate('Required', true, false);
				} else {
					$GLOBALS['Required'] = $this->ParseTemplate('Not_Required', true, false);
				}

				$subscriber_settings = $SubscriberApi->GetCustomFieldSettings($customfield_info['fieldid']);

				$customfields_api->fieldid = $customfield_info['fieldid'];
				$customfields_api->fieldtype = $customfield_info['fieldtype'];

				$subfield = $customfields_api->LoadSubField();

				$GLOBALS['FieldName'] = htmlspecialchars($customfield_info['name'], ENT_QUOTES, SENDSTUDIO_CHARSET);
				$GLOBALS['FieldValue'] = htmlspecialchars($subfield->GetRealValue($subscriber_settings), ENT_QUOTES, SENDSTUDIO_CHARSET);

				switch ($customfield_info['fieldtype']) {
					case 'textarea':
						$template_name = 'Subscribers_View_CustomField_TextArea';
					break;
					case 'date':
						$fieldsettings = unserialize($customfield_info['fieldsettings']);
						$GLOBALS['DateJSON'] = '';
						$GLOBALS['GoogleCalendarButton'] = '';
						if (strlen($GLOBALS['FieldValue'])) {
							$date = explode('/',$GLOBALS['FieldValue']);
							$datejson = array_combine(array_slice($fieldsettings['Key'],0,3),$date);

							$GLOBALS['DateJSON'] = GetJSON($datejson);

							if (strlen($user->googlecalendarusername) && strlen($user->googlecalendarpassword)) {
								$GLOBALS['GoogleCalendarButton'] =  $this->ParseTemplate('google_calendar_button',true);
							} else {
								$GLOBALS['GoogleCalendarButton'] =  $this->ParseTemplate('google_calendar_button_disabled',true);
							}
						}

						$template_name = 'Subscribers_View_CustomField_Date';
					break;
					default:
						$template_name = 'Subscribers_View_CustomField';
				}

				$customfield_display[] = $this->ParseTemplate($template_name, true, false);
				unset($subfield);
			}

			$column1 = $column2 = array();
			if (count($customfield_display) > 9) {
				$customfieldinfo_template = 'Subscribers_customfieldinfo_twocolumns';
				$split = ceil(count($customfield_display) / 2);

				for ($i = 0; $i < $split; $i++) {
					$column1[] = $customfield_display[$i];
					if (isset($customfield_display[$i + $split])) {
						$column2[] = $customfield_display[$i + $split];
					} else {
						$column2[] = '<td>&nbsp;</td><td>&nbsp;</td>';
					}
				}

				$GLOBALS['CustomFieldInfo_1'] = '<tr>' . implode('</tr><tr>',$column1) . '</tr>';
				$GLOBALS['CustomFieldInfo_2'] = '<tr>' . implode('</tr><tr>',$column2) . '</tr>';
			} else {
				$customfieldinfo_template = 'Subscribers_customfieldinfo_onecolumn';
				$GLOBALS['CustomFieldInfo_1'] = '';
				foreach ($customfield_display as $field) {
					$GLOBALS['CustomFieldInfo_1'] .= '<tr>' . $field . '</tr>';
				}
			}
			$GLOBALS['CustomFieldInfo'] = $customfieldinfo . $this->ParseTemplate($customfieldinfo_template,true);
		}

		$GLOBALS['listid'] = $listid;

		$actions = $user->GetEventActivityType();
		$GLOBALS['Actions'] = '';
		foreach ($actions as $action) {
			$GLOBALS['Actions'] .= '<option value="' . htmlspecialchars($action,ENT_QUOTES, SENDSTUDIO_CHARSET) . '">'. htmlspecialchars($action,ENT_QUOTES, SENDSTUDIO_CHARSET) . "</option>";
		}

		$GLOBALS['EventTypesJSON'] = GetJSON($actions);
		$GLOBALS['EventAddForm'] = $this->ParseTemplate('Subscriber_Event_Add',true,false);

		$GLOBALS['DatePickerJavascript'] = $this->ParseTemplate('ui.datepicker.custom_iem',true,false);

		if (IEM::sessionGet('gcal_allday')) {
			$GLOBALS['GoogleCalendarAllDay'] = 'true';
		} else {
			$GLOBALS['GoogleCalendarAllDay'] = 'false';
		}

		$GLOBALS['SubscriberEvents_Intro'] = GetLang('SubscriberEvents_Intro');
		if ($user->HasAccess('Subscribers','EventSave')) {
			$GLOBALS['SubscriberEvents_Intro'] .= GetLang('SubscriberEvents_Intro_AddEvent');
		}

		$this->ParseTemplate('Subscribers_View_Step2');
	}
	/**
	* 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');
	}
	/**
	* PrintStatusReport
	* Prints out the status report of what we're importing. So we can quickly see how many successful imports, updated subscribers, duplicate subscribers found, failures etc.
	*
	* @param Boolean $return Specify whether or not to return the report instead of printing it (Optional, default FALSE - print to screen)
	*
	* @return Void|String Depending on the parameter, it will either print out the report and return nothing or return the report as a string
	*/
	function PrintStatusReport($return = false)
	{
		$importresults = IEM::sessionGet('ImportResults');
		$importinfo = IEM::sessionGet('ImportInfo');

		$GLOBALS['ImportResults_Message'] = sprintf(GetLang('ImportResults_InProgress_Message'), $this->FormatNumber($importinfo['TotalSubscribers']));

		$report = '';
		foreach (array('success', 'updates', 'duplicates', 'failures', 'bans', 'unsubscribes', 'bads') as $pos => $key) {
			$amount = $importresults[$key];
			if ($amount == 1) {
				$report .= GetLang('ImportSubscribers_InProgress_' . $key . '_One');
			} else {
				$report .= sprintf(GetLang('ImportSubscribers_InProgress_' . $key . '_Many'), $this->FormatNumber($importresults[$key]));
			}
			$report .= '<br/>';
		}
		$GLOBALS['Report'] = $report;

		$temp = $this->ParseTemplate('Subscribers_Import_ReportProgress', $return);
		return $temp;
	}
Esempio n. 6
0
 /**
  * Admin_Action_PreConfig
  *
  * is use to preconfigured any request before hitting any of of the Action..
  * Perhaps this can be used to setup any prerequeisite like seting error messages or warning
  * and other related used that can be used accross action..
  *
  *
  * @return void
  */
 public function Admin_Action_PreConfig()
 {
     $messageText = IEM::sessionGet('MessageText');
     $messageType = IEM::sessionGet('MessageType');
     if ($messageText) {
         $message['type'] = $messageType;
         $message['message'] = $messageText;
         $messageArr[] = $message;
         IEM::sessionSet('FlashMessages', $messageArr);
         // removing the session for next usage
         IEM::sessionRemove('MessageText');
         IEM::sessionRemove('MessageType');
     }
 }
	/**
	* 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
	}
	/**
	* Process
	* Does all of the work.
	* This handles processing of the functions. This includes adding, deleting, editing, associating with lists.
	*
	* @see EditCustomField
	* @see CreateCustomField_Step1
	* @see CreateCustomField_Step2
	* @see ManageCustomField_Lists
	* @see ManageCustomFields
	*
	* @return Void Doesn't return anything, just prints out the results.
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

		$this->PrintHeader();
		$user = GetUser();

		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : null;

		if ($action == 'processpaging') {
			$this->SetPerPage($_GET['PerPageDisplay']);
			$action = 'manage';
		}

		$effective_action = $action;
		if ($action == 'associate') {
			$effective_action = null;
		}

		$access = $user->HasAccess('customfields', $effective_action);

		if ($access) {
			// The user is allowed to perform the action only on their own fields.
			$field_owner = $user->userid;
			$api = $this->GetApi();
			$check = array();
			if (isset($_POST['customfields'])) {
				$check = $_POST['customfields'];
			}
			if (isset($_GET['id'])) {
				$check[] = $_GET['id'];
			}
			if (isset($_POST['fieldid'])) {
				$check[] = $_POST['fieldid'];
			}
			foreach ($check as $id) {
				if (!$api->Load(intval($id))) {
					$this->DenyAccess();
				}
				if ($api->ownerid != $field_owner && !$user->Admin()) {
					$this->DenyAccess();
				}
			}
		}

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

		switch ($action) {
			case 'associate':
				$associations = (isset($_POST['listid'])) ? $_POST['listid'] : array();
				$fieldid = $_POST['fieldid'];

				$api = $this->GetApi();
				$api->Load($fieldid);

				$fieldapi = $this->GetApi('CustomFields_' . $api->fieldtype);
				if (!$fieldapi) {
					return false;
				}

				unset($api);

				$fieldapi->Load($fieldid);

				$saveresult = $fieldapi->SetAssociations($associations, $user);
				if (!$saveresult) {
					$GLOBALS['Error'] = GetLang('UnableToUpdateCustomField');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				} else {
					$GLOBALS['Message'] = $this->PrintSuccess('CustomFieldUpdated');
				}
				$this->ManageCustomFields();
			break;

			case 'edit':
				$fieldid = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;

				$subaction = (isset($_GET['SubAction'])) ? strtolower($_GET['SubAction']) : '';

				switch ($subaction) {
					case 'update':
						$api = $this->GetApi();
						$api->Load($fieldid);

						$fieldapi = $this->GetApi('CustomFields_' . $api->fieldtype);
						if (!$fieldapi) {
							return false;
						}

						$fieldapi->Load($fieldid);
						$alloptions = $fieldapi->GetOptions();

						$newoptions = array();
						foreach ($alloptions as $fieldname => $option) {
							if (isset($_POST[$fieldname]) && is_array($_POST[$fieldname])) {
								$value = $_POST[$fieldname];
							} else {
								if (isset($customfield_settings[$fieldname])) {
									$value = $customfield_settings[$fieldname];
								} else {
									if (isset($_POST[$fieldname])) {
										$value = $_POST[$fieldname];
									} else {
										$value = false;
									}
								}
							}
							$newoptions[$fieldname] = $value;
						}

						if (isset($newoptions['Key']) && is_array($newoptions['Key'])) {
							foreach ($newoptions['Key'] as $key => $val) {
								if (!strlen($val) && isset($newoptions['Value'][$key]) && strlen($newoptions['Value'][$key])) {
									$newoptions['Key'][$key] = $newoptions['Value'][$key];
								}
							}
						}

                        $AllOptions = array_merge($fieldapi->SharedOptions, $fieldapi->Options);

                        foreach ($AllOptions as $name => $val) {
                            $newval = $newoptions[$name];
                            if (is_array($newval)) {
                                $checkvals = array();
                                foreach ($newval as $k => $v) {
                                    if ($v != '') {
                                        $checkvals[] = $v;
                                    }
                                }
                                $newval = $checkvals;
                            }
                            $fieldapi->Settings[$name] = $newval;
                        }

                        $fieldapi->Save();

						$this->ManageCustomField_Lists($fieldid);

					break;
					default:
						$this->EditCustomField($fieldid);
				}
			break;

			case 'delete':
				$deletelist = (isset($_POST['customfields'])) ? $_POST['customfields'] : array();
				if (isset($_GET['id'])) {
					$deletelist = array((int)$_GET['id']);
				}
				$this->RemoveCustomFields($deletelist);
			break;

			case 'create':
				// see what step we're up to.
				$subaction = (isset($_GET['SubAction'])) ? strtolower($_GET['SubAction']) : '';
				switch ($subaction) {
					case 'step2':
						$newfield = array();
						$newfield['FieldName'] = $_POST['FieldName'];
						$newfield['FieldType'] = $_POST['FieldType'];
						$newfield['FieldRequired'] = '';
						if(isset($_POST['FieldRequired'])){ $newfield['FieldRequired'] = 'on'; $GLOBALS['ApplyDefault'] = ' CHECKED';} else { $GLOBALS['ApplyDefault'] = ''; }
						IEM::sessionSet('CustomFields', $newfield);
						$this->CreateCustomField_Step2($newfield);
					break;

					case 'step3':
						$customfield_settings = IEM::sessionGet('CustomFields');

						$fieldapi = $this->GetApi('CustomFields_' . $customfield_settings['FieldType']);
						if (!$fieldapi) {
							return false;
						}

						$alloptions = $fieldapi->GetOptions();

						$newoptions = array();
                        if(isset($_POST['ApplyDefault'])){$newoptions['ApplyDefault'] = 'on';}
						foreach ($alloptions as $fieldname => $option) {
						    if(isset($newoptions[$fieldname])){continue;}  
							$value = (isset($customfield_settings[$fieldname])) ? $customfield_settings[$fieldname] : $_POST[$fieldname];

							$newoptions[$fieldname] = $value;
						}

                        $AllOptions = array_merge($fieldapi->SharedOptions, $fieldapi->Options);

                        foreach ($AllOptions as $name => $val) {
                            $newval = $newoptions[$name];
                            if (is_array($newval)) {
                                $checkvals = array();
                                foreach ($newval as $k => $v) {
                                    if ($v != '') {
                                        $checkvals[] = $v;
                                    }
                                }
                                $newval = $checkvals;
                            }
                            $fieldapi->Settings[$name] = $newval;
                        }

						$fieldapi->ownerid = $user->userid;

						$create = $fieldapi->Create();

						if (!$create) {
							$GLOBALS['Error'] = GetLang('UnableToCreateCustomField');
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							break;
						}
						$this->ManageCustomField_Lists($create, true);
					break;

					default:
						$this->CreateCustomField_Step1();
				}
			break;
			default:
				$this->ManageCustomFields();
		}
		$this->PrintFooter();
	}
	/**
	* GetImagesList
	* A function to generate a list of the available images for the editor displays
	*
	* @param String $type The type of the folder.
	* @param Interger $typeId The Id of the folder type.
	*
	* @return Void Doesn't return anything. Display the javascript content.
	*/
	function GetImagesList($type, $typeId)
	{
        $d_path = TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $type. DIRECTORY_SEPARATOR . $typeId;
        if(!is_dir($d_path)){CreateDirectory($d_path,TEMP_DIRECTORY, 0777);}
        $remove_temp_dir = IEM::sessionGet($type.'_creation['.$this->user->Get('userid').']');
        if(empty($remove_temp_dir)){IEM::sessionSet($type.'_creation['.$this->user->Get('userid').']',true);}
    	$api = $this->GetApi();
		$api->Init('asc', 'name', $type, $typeId);
		$output = '';

		$output .= 'var tinyMCEImageList = new Array(';
		$outputArray = array();

		$imgDir = $api->GetImageDirFiles();
		foreach ($imgDir as $k=>$image){
			$outputArray[] = '["' . $image['name'] . '", "' . $image['url'] . '"]';
		}

		$output .= implode(",\n", $outputArray) . ');';

		header('Content-type: text/javascript');
		
		die($output);
	}
	public function page_saveRecord()
	{
		$record = IEM::requestGetPOST('record', array());

        $record['groupname'] = htmlspecialchars($record['groupname']);

		$created = ((IEM::ifsetor($record['groupid'], 0, 'intval') == 0) ? true : false);

		/*
		 * Transform the permission so that it will be recognized by the API
		 */

		$permissions = IEM::ifsetor($record['permissions'], array());


		$new_permissions = array();
		if (!is_array($permissions)) {
			$permissions = array();
		}
		if (!empty($permissions)) {
			foreach ($permissions as $each) {
				$temp = explode('.', $each);

				// This can only handle 2 level permissions,
				// ie. autoresponders.create, autoresponders.delete, autoresponders.edit
				// will become $permissions['autoresponders'] = array('create', 'delete', 'edit');
				if (count($temp) != 2) {
					continue;
				}

				if (!isset($new_permissions[$temp[0]])) {
					$new_permissions[$temp[0]] = array();
				}

				$new_permissions[$temp[0]][] = $temp[1];
			}
		}

		$record['permissions'] = $new_permissions;

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

		// Check if "Request Token" matches
		// This tries to prevent CSRF
		$token = IEM::sessionGet('UsersGroups_Editor_RequestToken', false);
		if (!$token || $token != IEM::requestGetPOST('requestToken', false)) {
			return $this->page_createGroup($record);
		}

		$status = API_USERGROUPS::saveRecord($record);
		if (!$status) {
			FlashMessage(GetLang('UsersGroups_From_Error_CannotSave'), SS_FLASH_MSG_ERROR);
			return $this->printEditor($record);
		}

		$messageVariable = 'UsersGroups_From_Success_Saved';
		if ($created) {
			$messageVariable = 'UsersGroups_From_Success_Created';
		}

		FlashMessage(GetLang($messageVariable), SS_FLASH_MSG_SUCCESS, IEM::urlFor('UsersGroups'));
	}
Esempio n. 11
0
	/**
	* ManageSubscribers_Step3
	* Prints out the subscribers for the list chosen and criteria selected in steps 1 & 2. This handles sorting, paging and searching. If you are coming in for the first time, it remembers your search criteria in the session. If you change number per page, sorting criteria, it fetches the search criteria from the session again before continuing.
	*
	* @see ManageSubscribers_Step2
	* @see GetApi
	* @see GetPerPage
	* @see GetCurrentPage
	* @see GetSortDetails
	* @see Subscribers_API::FetchSubscribers
	* @see SetupPaging
	* @see Lists_API::Load
	*
	* @return Void Doesn't return anything. Prints out the results and that's it.
	*/
	function ManageSubscribers_Step3($change=false)
	{
		$subscriber_api = $this->GetApi('Subscribers');
		$user = IEM::getCurrentUser();
		$search_info = IEM::sessionGet('Search_Subscribers');

		$this->SetupGoogleCalendar();

		$user_lists = $user->GetLists();

		if (!isset($GLOBALS['Message'])) {
			$GLOBALS['Message'] = '';
		}

		// if we are posting a form, we are most likely resetting the search criteria.
		// we are also resetting the search criteria once we detect "Lists" variable in the GET Request
		$resetsearch = ((isset($_POST) && !empty($_POST)) || isset($_GET['Lists']) || isset($_GET['Segment'])) ? true : false;

		// except if we're changing paging!
		if (isset($_GET['SubAction'])) {
			$subaction =  strtolower($_GET['SubAction']);
			if ($subaction == 'processpaging' || $subaction == 'change') {
				$resetsearch = false;
			}
		}

		if (!$search_info || $resetsearch) {
			$this->SetCurrentPage(1); // forget current page
			$search_details = array();
			if (isset($_POST['emailaddress']) && $_POST['emailaddress'] != '') {
				$search_details['Email'] = trim($_POST['emailaddress']);
			}

			if (isset($_POST['format']) && $_POST['format'] != '-1') {
				$search_details['Format'] = $_POST['format'];
			}

			if (isset($_POST['confirmed']) && $_POST['confirmed'] != '-1') {
				$search_details['Confirmed'] = $_POST['confirmed'];
			}

			if (isset($_POST['status']) && $_POST['status'] != '-1') {
				$search_details['Status'] = $_POST['status'];
			}

			if (isset($_POST['datesearch']) && isset($_POST['datesearch']['filter'])) {
				$search_details['DateSearch'] = $_POST['datesearch'];

				$search_details['DateSearch']['StartDate'] = AdjustTime(array(0, 0, 1, $_POST['datesearch']['mm_start'], $_POST['datesearch']['dd_start'], $_POST['datesearch']['yy_start']));

				$search_details['DateSearch']['EndDate'] = AdjustTime(array(0, 0, 1, $_POST['datesearch']['mm_end'], $_POST['datesearch']['dd_end'], $_POST['datesearch']['yy_end']));
			}

			$customfields = array();
			if (isset($_POST['CustomFields']) && !empty($_POST['CustomFields'])) {
				$customfields = $_POST['CustomFields'];
			}

			$search_details['CustomFields'] = $customfields;

			if (isset($_GET['Lists']) || isset($_GET['List'])) {
				$search_details['List'] = isset($_GET['Lists'])? $_GET['Lists'] : $_GET['List'];
			} else {
				$search_details['List'] = 'any';
			}

			// Get segment, and make sure user have access permission to it
			if ($user->HasAccess('Segments')) {
				$search_details['Segment'] = null;
				if (isset($_GET['Segment'])) {
					$tempSegmentList = array_keys($user->GetSegmentList());
					$tempSegment = $_GET['Segment'];

					// Make sure that selected segment is allowed for user
					if (!is_array($tempSegment)) {
						if (!in_array($tempSegment, $tempSegmentList)) {
							$tempSegment = null;
						}
					} else {
						$tempSegment = array_intersect($tempSegment, $tempSegmentList);
					}

					if (!is_null($tempSegment)) {
						$search_details['Segment'] = $tempSegment;
					}
				}
			}

			if (is_array($search_details['List'])) {
				// Make sure that "any" is not selected when you are selecting multiple list
				if (count($search_details['List']) > 1) {
					if (($index = array_search('any', $search_details['List'])) !== false) {
						unset($search_details['List'][$index]);
					}
				}

				// If the array only contain 1 id, make take it out of the array
				if (count($search_details['List']) == 1) {
					$search_details['List'] = array_pop($search_details['List']);
				}
			}

			// Get allowable list
			if (!$user->ListAdmin()) {
				$search_details['AvailableLists'] = array_keys($user_lists);
			}

			if (is_array($search_details['List'])) {
				// Make sure IDs are numerics
				if (is_array($search_details['List'])) {
					$listIDs = array();
					foreach ($search_details['List'] as $id) {
						array_push($listIDs, intval($id));
					}
					$search_details['List'] = $listIDs;
				}
			}

			// Make sure that user can only select newsletter from his/her allowable list
			if (isset($search_details['AvailableLists']) && (is_numeric($search_details['List']) || is_array($search_details['List']))) {
				if (is_array($search_details['List'])) {
					$search_details['List'] = array_intersect($search_details['List'], $search_details['AvailableLists']);
				} else {
					$temp = in_array($search_details['List'], $search_details['AvailableLists']);
					if (!$temp) {
						$search_details['List'] = null;
					}
				}

				if (empty($search_details['List'])) {
					$search_details['List'] = $search_details['AvailableLists'];
				}

				// Make sure to unset available list, otherwise Subscribers API will think
				// we are looking to query all list
				unset($search_details['AvailableLists']);
			}

			if (isset($_POST['clickedlink']) && isset($_POST['linkid'])) {
				$search_details['LinkType'] = 'clicked';
				if (isset($_POST['linktype']) && $_POST['linktype'] == 'not_clicked') {
					$search_details['LinkType'] = 'not_clicked';
				}

				$search_details['Link'] = $_POST['linkid'];
			}

			if (isset($_POST['openednewsletter']) && isset($_POST['newsletterid'])) {
				$search_details['OpenType'] = 'opened';
				if (isset($_POST['opentype']) && $_POST['opentype'] == 'not_opened') {
					$search_details['OpenType'] = 'not_opened';
				}

				$search_details['Newsletter'] = $_POST['newsletterid'];
			}

			if (isset($_POST['Search_Options'])) {
				$search_details['Search_Options'] = $_POST['Search_Options'];
			}

			// Flag to differentiate where the search details are coming from
			$GLOBALS['Search'] = '';
			if (!empty($_POST) || !empty($search_details['Email'])) {
				$search_details['Source'] = 'search';
				$GLOBALS['Search'] = isset($search_details['Email'])? $search_details['Email'] : '';
			} else {
				if (!empty($search_details['Segment'])) {
					$search_details['Source'] = 'segment';
				} else {
					$search_details['Source'] = 'list';
				}
			}

			IEM::sessionSet('Search_Subscribers', $search_details);
		}

		$search_info = IEM::sessionGet('Search_Subscribers');

		// Process segmenting information
		if (!empty($search_info['Segment'])) {
			$segmentAPI = $this->GetApi('Segment');

			if (is_array($search_info['Segment'])) {
				$search_info['List'] = $segmentAPI->GetMailingListUsed($search_info['Segment']);
			} else {
				$segmentAPI->Load($search_info['Segment']);
				$search_info['List'] = $segmentAPI->GetMailingListUsed();
			}

			$subscriber_header_template = 'Subscribers_Manage_AnyList';
			$subscriber_row_template = 'Subscribers_Manage_AnyList_Row';

			$GLOBALS['Segment'] = is_array($search_info['Segment'])? implode('&Segment[]=', $search_info['Segment']) : $search_info['Segment'];
		}

		$GLOBALS['List'] = is_array($search_info['List'])? implode('&Lists[]=', $search_info['List']) : $search_info['List'];

		// Load visible fields for each list
		if (isset($_POST['VisibleFields'])) {
			IEM::sessionSet('visiblefields', $_POST['VisibleFields']);
			$visiblefields_set = $_POST['VisibleFields'];
		} elseif (IEM::sessionGet('visiblefields')) {
			$visiblefields_set = IEM::sessionGet('visiblefields');
		} else {
			list(,$visiblefields_set) = $this->GetVisibleFields($search_info['List']);
		}

		$perpage = $this->GetPerPage();
		$pageid = $this->GetCurrentPage();

		$sortinfo = $this->GetSortDetails();

		// Check if we are sorting by a custom field
		if (is_numeric($sortinfo['SortBy'])) {
			if (in_array($sortinfo['SortBy'], $visiblefields_set)) {
				$sortinfo['CustomFields'] = array($sortinfo['SortBy']);
				$sortinfo['SortBy'] = 'sd.data';
			} else {
				$sortinfo['SortBy'] = 'emailaddress';
			}
		}

		if (!empty($search_info['Segment'])) {
			$tempEmail = null;
			if (!empty($search_details['Email'])) {
				$tempEmail = $search_details['Email'];
			}

			$subscriber_list = $subscriber_api->FetchSubscribersFromSegment($pageid, $perpage, $search_info['Segment'], $sortinfo, $tempEmail);
		} else {
			$subscriber_list = $subscriber_api->FetchSubscribers($pageid, $perpage, $search_info, $sortinfo);
		}

		$subscriber_edited = (isset($_GET['Edit'])) ? true : false;

		$totalsubscribers = $subscriber_list['count'];
		unset($subscriber_list['count']);

		if ($subscriber_edited) {
			$GLOBALS['Message'] .= $this->PrintSuccess('SubscriberEditSuccess');
		}

		$GLOBALS['TotalSubscriberCount'] = $this->FormatNumber($totalsubscribers);

		$tempMessageStringSubfix = '';
		switch ($search_info['Source']) {
			case 'list':
				if ($search_info['List'] == 'any') {
					$tempMessageStringSubfix = 'AllList_';
				} elseif (is_array($search_info['List'])) {
					$tempMessageStringSubfix = 'ManyList_';
				} else {
					$tempMessageStringSubfix = 'OneList_';
				}
			break;

			case 'segment':
				$tempMessageStringSubfix = 'Segment_';
			break;
		}


		$DisplayPage = $pageid;

		$GLOBALS['PAGE'] = 'Subscribers&Action=Manage&SubAction=Step3';

		// set up paging before we add the Lists[]= part, as we never want paging links to reset a search
		$this->SetupPaging($totalsubscribers, $DisplayPage, $perpage);
		$GLOBALS['FormAction'] = 'SubAction=ProcessPaging';
		$paging = $this->ParseTemplate('Paging', true, false);

		if (!empty($search_info['Segment'])) {
			$GLOBALS['PAGE'] .= '&Segment[]=' . $GLOBALS['Segment'];
		} else {
			$GLOBALS['PAGE'] .= '&Lists[]=' . $GLOBALS['List'];
		}

		$subscriberdetails = '';

		// If no visible fields are selected, make emailaddress visible
		if (count($visiblefields_set) == 0) {
			array_unshift($visiblefields_set,'emailaddress');
		}

		// Make "View" PopUp menu
		$GLOBALS['SubscriberViewPickerMenu'] = $this->MakeViewPopupMenu($search_info, $user);

		$loaded_customfields = array();

		$customfields = array();

		$visiblefields = array();
		$visiblefields_lists = array();

		$subscriber_header_template = 'Subscribers_Manage_AnyList';
		$subscriber_row_template = 'Subscribers_Manage_AnyList_Row';

		if (!$user->HasAccess('Subscribers', 'Add')) {
			$GLOBALS['AddButtonDisplay'] = 'none';
		}

		if (!empty($search_info['Segment'])) {
			$segmentAPI = $this->GetApi('Segment');
			$tempSegmentID = $search_info['Segment'];
			$usedLists = array();

			if (!is_array($tempSegmentID)) {
				$tempSegmentID = array($tempSegmentID);
			}

			foreach ($tempSegmentID as $id) {
				$segmentAPI->Load($id);
				$tempList = $segmentAPI->GetMailingListUsed();

				$usedLists = array_merge($usedLists, $tempList);
			}

			$search_info['List'] = $usedLists;

			/**
			 * Segments contain lists (as they can go across multiple lists)
			 */
			$listids = $search_info['List'];

			if ($search_info['Source'] == 'search' || is_array($search_info['Segment'])) {
				$title = GetLang('SubscribersManageSearchResult');
			} else {
				$title = sprintf(GetLang('SubscribersManageSegment'), htmlspecialchars($segmentAPI->segmentname, ENT_QUOTES, SENDSTUDIO_CHARSET));
			}

			$GLOBALS['AddButtonURL'] = 'index.php?Page=Subscribers&Action=Add';
		} else {
			/**
			 * Only viewing one list here.
			 */
			if (is_numeric($search_info['List'])) {
				$listids = array($search_info['List']);
				$subscriber_header_template = 'Subscribers_Manage';
				$subscriber_row_template = 'Subscribers_Manage_Row';

				$GLOBALS['ColumnCount'] = 3;

				if ($search_info['Source'] == 'search') {
					$title = GetLang('SubscribersManageSearchResult');
				} else {
					$listname = $user_lists[$search_info['List']]['name'];
					$title = sprintf(GetLang('SubscribersManageSingleList'), htmlspecialchars($listname, ENT_QUOTES, SENDSTUDIO_CHARSET));
				}

				$GLOBALS['AddButtonURL'] = 'index.php?Page=Subscribers&Action=Add&SubAction=Step2&list=' . $search_info['List'];
			} else {
				/**
				 * If we're viewing more than one list, use those id's.
				 */
				if (is_array($search_info['List'])) {
					$listids = $search_info['List'];
					$title = GetLang('SubscribersManageMultipleList');
				} else {
					/**
					 * The default is all of the users lists.
					*/
					$listids = array_keys($user_lists);
					$title = GetLang('SubscribersManageAnyList');
				}

				/**
				 * Override the title if we're coming from a search result.
				 */
				if ($search_info['Source'] == 'search') {
					$title = GetLang('SubscribersManageSearchResult');
				}

				$GLOBALS['AddButtonURL'] = 'index.php?Page=Subscribers&Action=Add';
				$GLOBALS['ColumnCount'] = 4;
			}
		}

		$GLOBALS['SubscribersManage'] = $title;

		// Log this to "User Activity Log" except when is deleting.
		if (!(isset($_GET['SubAction']) && strtolower($_GET['SubAction']) != "delete")) {
			IEM::logUserActivity($_SERVER['REQUEST_URI'], 'images/lists_view.gif', $title);
		}

		if ($totalsubscribers < 1) {
			IEM::sessionRemove('Search_Subscribers');
			if ($subscriber_edited) {
				$GLOBALS['Message'] .= $this->PrintSuccess('SubscriberEditSuccess');
			} else {
				$GLOBALS['Message'] .= $this->PrintSuccess('NoSubscribersMatch', true);
			}
			$this->ParseTemplate('Subscribers_Manage_Empty');
			return;
		}

		if ($totalsubscribers == 1) {
			$GLOBALS['Message'] .= $this->PrintSuccess('Subscribers_' . $tempMessageStringSubfix . 'FoundOne');
		} else {
			$GLOBALS['Message'] .= $this->PrintSuccess('Subscribers_' . $tempMessageStringSubfix . 'FoundMany', $GLOBALS['TotalSubscriberCount']);
		}

		$CustomFieldsApi = $this->GetApi('CustomFields');
		$customfields_for_all_lists = $CustomFieldsApi->GetCustomFieldsForLists($listids, $visiblefields_set);
		$listNames = array();

		foreach ($listids as $listid) {
			array_push($listNames, $user_lists[$listid]['name']);

			foreach ($this->BuiltinFields as $key => $name) {
				if (in_array($key,$visiblefields_set) && !in_array($key,$visiblefields)) {
					if (!isset($visiblefields_lists[$key])) {
						$visiblefields_lists[$key] = array();
					}
					$visiblefields_lists[$key][] = (int)$listid;

					$visiblefields[] = $key;
				}
			}

			foreach ($customfields_for_all_lists as $key => $details) {
				if (in_array($details['fieldid'],$visiblefields_set)) {
					if (!isset($visiblefields_lists[$details['fieldid']])) {
						$visiblefields_lists[$details['fieldid']] = array();
					}
					$visiblefields_lists[$details['fieldid']][] = (int)$listid;

					if (!in_array($details['fieldid'],$visiblefields)) {
						$visiblefields[] = $details['fieldid'];
					}
				}
			}
		}

		$customfield_data = array();

		$GLOBALS['Columns'] = '';
		foreach ($visiblefields as $name) {
			if (!in_array($name,$visiblefields_set)) {
				continue;
			}

			if (is_numeric($name)) {
				$customfieldinfo = array();
				foreach ($customfields_for_all_lists as $pos => $details) {
					if ($details['fieldid'] === $name) {
						$customfieldinfo = $details;
						break;
					}
				}

				/**
				 * Check we got some data here.
				 * We may have just changed the lists we are viewing and the custom field isn't associated with this new list
				*/
				if (!empty($customfieldinfo)) {
					$GLOBALS['FieldName'] = htmlspecialchars($customfieldinfo['name'], ENT_QUOTES, SENDSTUDIO_CHARSET);

					$subfield = $CustomFieldsApi->LoadSubField($customfieldinfo);

					$loaded_customfields[$name] = $subfield;

					$customfield_data[] = array (
						'fieldid' => $name,
						'fieldtype' => $subfield->fieldtype,
						'defaultvalue' => $subfield->GetDefaultValue(),
						'name' => $subfield->GetFieldName(),
					);
				}
			} elseif (in_array($name,array_keys($this->BuiltinFields))) {
				$GLOBALS['FieldName'] = GetLang($this->BuiltinFields[$name]);
			}

			if ($name == 'emailaddress') {
				$GLOBALS['Width'] = 'width="17%"';
			} else {
				$GLOBALS['Width'] = '';
			}

			$GLOBALS['SortName'] = htmlspecialchars($name, ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['Columns'] .= $this->ParseTemplate('Subscribers_Manage_Column_Sortable',true,false);
		}

		if (isset($GLOBALS['Segment'])) {
			$GLOBALS['URLQueryString'] = '&Segment[]=' . $GLOBALS['Segment'];
		} else {
			$GLOBALS['URLQueryString'] = '&Lists[]=' . $GLOBALS['List'];
		}

		$actions = $user->GetEventActivityType();
		$GLOBALS['Actions'] = '';
		foreach ($actions as $action) {
			$GLOBALS['Actions'] .= '<option value="' . htmlspecialchars($action,ENT_QUOTES, SENDSTUDIO_CHARSET) . '">'. htmlspecialchars($action,ENT_QUOTES, SENDSTUDIO_CHARSET) . "</option>";
		}

		$GLOBALS['EventTypesJSON'] = GetJSON($actions);
		$GLOBALS['EventAddForm'] = $this->ParseTemplate('Subscriber_Event_Add',true,false);

		$GLOBALS['EventJavascript'] = $this->ParseTemplate('Subscribers_Events_Javascript',true,false);
		$GLOBALS['DatePickerJavascript'] = $this->ParseTemplate('ui.datepicker.custom_iem',true,false);


		$template = $this->ParseTemplate($subscriber_header_template, true, false);

		$GLOBALS['List'] = $search_info['List'];

		$subscriber_customfields = array();
		$customfield_ids = $visiblefields;
		$customfield_ids = $subscriber_api->CheckIntVars($customfield_ids);

		if (!empty($customfield_ids)) {
			$subids = array();
			foreach ($subscriber_list['subscriberlist'] as $info) {
				$subids[] = $info['subscriberid'];
			}
			$subscriber_customfields = $subscriber_api->GetAllSubscriberCustomFields($listids, array(), $subids, $customfield_ids);
			unset($subids);
		}

		if (!isset($GLOBALS['ColumnCount'])) {
			$GLOBALS['ColumnCount'] = 0;
		}
		$GLOBALS['ColumnCount'] += count($visiblefields);

		foreach ($subscriber_list['subscriberlist'] as $pos => $subscriberinfo) {
			$GLOBALS['Columns'] = '';
			$GLOBALS['FieldValue'] = '';
			$subscriberfields = array();
			foreach ($visiblefields as $fieldname) {
				switch ($fieldname) {
					case 'emailaddress':
						$GLOBALS['FieldValue'] = htmlspecialchars($subscriberinfo[$fieldname], ENT_QUOTES, SENDSTUDIO_CHARSET);
					break;
					case 'subscribedate':
						$GLOBALS['FieldValue'] = $this->PrintDate($subscriberinfo['subscribedate']);
					break;
					case 'format':
						$GLOBALS['FieldValue'] = ($subscriberinfo['format'] == 't') ? 	GetLang('Format_Text') : GetLang('Format_HTML');
					break;
					case 'confirmed':
						$GLOBALS['FieldValue'] = ($subscriberinfo['confirmed'] == '1') ? GetLang('Confirmed') : GetLang('Unconfirmed');
					break;
					case 'status':
						$status = GetLang('Active');

						if ($subscriberinfo['unsubscribed'] > 0) {
							$status = GetLang('Unsubscribed');
						}

						if ($subscriberinfo['bounced'] > 0) {
							$status = GetLang('Bounced');
						}

						$GLOBALS['FieldValue'] = $status;
					break;
					default:
						$GLOBALS['FieldValue'] = '&nbsp;';
						if (is_numeric($fieldname)) {
							$subfield = $loaded_customfields[$fieldname];
							$subid = $subscriberinfo['subscriberid'];

							/**
							* If there is no custom field for this subscriber, go to the next field.
							* This could happen if you view all lists but a field is only associated with one particular list
							*/
							if (!isset($subscriber_customfields[$subid])) {
								continue;
							}

							foreach ($subscriber_customfields[$subid] as $cf_p => $cf_details) {
								if ($cf_details['fieldid'] != $fieldname) {
									continue;
								}
								$GLOBALS['FieldValue'] = htmlspecialchars($subfield->GetRealValue($cf_details['data'],','), ENT_QUOTES, SENDSTUDIO_CHARSET);
							}
						}
				}
				$GLOBALS['Columns'] .= $this->ParseTemplate('Subscribers_Manage_Row_Column',true,false);
			}
			// if we are searching "any" list then we need to adjust the link.
			if (isset($subscriberinfo['listid'])) {
				$GLOBALS['List'] = $subscriberinfo['listid'];
			}
			if (isset($subscriberinfo['listname'])) {
				$GLOBALS['MailingListName'] = htmlspecialchars($subscriberinfo['listname'], ENT_QUOTES, SENDSTUDIO_CHARSET);
			}

			$GLOBALS['subscriberid'] = $subscriberinfo['subscriberid'];
			$GLOBALS['SubscriberID'] = $subscriberinfo['subscriberid'];
			$GLOBALS['EditSubscriberID'] = $subscriberinfo['subscriberid'];

			if (array_key_exists('Segment', $search_info) && $search_info['Segment'] != 0) {
				$GLOBALS['SegmentID'] = $search_info['Segment'];
				$GLOBALS['ExtraParameter'] = '&SegmentID=' . $search_info['Segment'];
			} else {
				$GLOBALS['SegmentID'] = 0;
				$GLOBALS['ExtraParameter'] = '';
			}

			$GLOBALS['SubscriberAction'] = $this->ParseTemplate('Subscribers_Manage_ViewLink', true, false);

			if ($user->HasAccess('Subscribers', 'Eventsave')) {
				$GLOBALS['SubscriberAction'] .= $this->ParseTemplate('Subscribers_Manage_EventAddLink', true, false);
			}

			if ($user->HasAccess('Subscribers', 'Edit')) {
				$GLOBALS['SubscriberAction'] .= $this->ParseTemplate('Subscribers_Manage_EditLink', true, false);
			}

			if ($user->HasAccess('Subscribers', 'Delete')) {
				$GLOBALS['DeleteSubscriberID'] = $subscriberinfo['subscriberid'];
				$GLOBALS['SubscriberAction'] .= $this->ParseTemplate('Subscribers_Manage_DeleteLink', true, false);
			}
			$events = $subscriber_api->CountEvents($subscriberinfo['subscriberid']);

			$GLOBALS['EventButton'] = '';
			if ($events) {
				$GLOBALS['EventButton'] = $this->ParseTemplate('Subscribers_Manage_Row_Eventbutton',true,false);
			}


			$subscriberdetails .= $this->ParseTemplate($subscriber_row_template, true, false);
		}

		$template = str_replace('%%TPL_' . $subscriber_row_template . '%%', $subscriberdetails, $template);
		$template = str_replace('%%TPL_Paging%%', $paging, $template);
		$template = str_replace('%%TPL_Paging_Bottom%%', $GLOBALS['PagingBottom'], $template);

		echo $template;
	}
	/**
	* RunUpgrade
	* Runs the query for the upgrade process
	* and returns the result from the query.
	* The calling function looks for a true or false result
	*
	* @return Mixed Returns true if the condition is already met (eg the column already exists).
	*  Returns false if the database query can't be run.
	*  Returns the resource from the query (which is then checked to be true).
	*/
	function RunUpgrade()
	{
		$tablePrefix = SENDSTUDIO_TABLEPREFIX;

		// ----- Splitting process into chunks
			$dbUpgradeStatus = IEM::sessionGet('DatabaseUpgradeStatusList');
			$thisQuery = null;
			if (isset($dbUpgradeStatus[get_class($this)])) {
				$thisQuery = $dbUpgradeStatus[get_class($this)];
			}

			if (is_null($thisQuery)) {
				$result = $this->Db->Query("	SELECT	COUNT(autoresponderid) AS listcount
												FROM 	{$tablePrefix}autoresponders");
				$row = $this->Db->Fetch($result);
				$this->Db->FreeResult($result);

				$thisQuery = array(
					'Total' 	=> $row['listcount'],
					'Processed' => 0,
					'Offset' 	=> 0,
					'Limit'		=> 10
				);
			}
		// -----

		$query = "	SELECT	autoresponderid, listid
					FROM 	{$tablePrefix}autoresponders
					LIMIT	{$thisQuery['Limit']}
					OFFSET	{$thisQuery['Offset']}";

		$result = $this->Db->Query($query);
		while ($row = $this->Db->Fetch($result)) {
			$statid = $this->Db->NextId(SENDSTUDIO_TABLEPREFIX . 'stats_sequence');

			$query = "INSERT INTO " . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks(clicktime, clickip, subscriberid, statid, linkid) SELECT lc.timestamp, lc.ipaddress, lc.memberid, " . $statid . ", ln.linkid FROM " . SENDSTUDIO_TABLEPREFIX . "link_clicks lc, " . SENDSTUDIO_TABLEPREFIX . "links l, " . SENDSTUDIO_TABLEPREFIX . "links_new ln WHERE lc.linkid=l.linkid AND l.url=ln.url AND lc.ComposedID=l.ComposedID AND UPPER(lc.LinkType)='AUTO' AND lc.ListID='" . $row['listid'] . "'";

			$this->Db->Query($query);

			$query = "INSERT INTO " . SENDSTUDIO_TABLEPREFIX . "stats_emailopens(subscriberid, statid, opentime, openip) SELECT MemberID, " . $statid . ", TimeStamp, NULL FROM " . SENDSTUDIO_TABLEPREFIX . "email_opens WHERE SendID='" . $row['autoresponderid'] . "' AND UPPER(EmailType)='AUTO'";

			$this->Db->Query($query);


			$link_clicks_query = "SELECT COUNT(linkid) AS linkcount FROM " . SENDSTUDIO_TABLEPREFIX . "stats_links WHERE statid='" . $statid . "'";
			$clicks_result = $this->Db->Query($link_clicks_query);
			$link_clicks = $this->Db->FetchOne($clicks_result, 'linkcount');

			$link_clicks_query = "SELECT COUNT(openid) AS opencount FROM " . SENDSTUDIO_TABLEPREFIX . "stats_emailopens WHERE statid='" . $statid . "'";
			$opens_result = $this->Db->Query($link_clicks_query);
			$email_opens = $this->Db->FetchOne($opens_result, 'opencount');


			$insert_query = "INSERT INTO " . SENDSTUDIO_TABLEPREFIX . "stats_autoresponders(statid, htmlrecipients, textrecipients, multipartrecipients, bouncecount_soft, bouncecount_hard, bouncecount_unknown, unsubscribecount, autoresponderid, linkclicks, emailopens, emailforwards, emailopens_unique, hiddenby) VALUES ('" . $statid . "', '0', '0', '0', 0, 0, 0, 0, '" . $row['autoresponderid'] . "', '" . $link_clicks . "', '" . $email_opens . "', 0, '" . $email_opens . "', 0)";

			$insert_result = $this->Db->Query($insert_query);
		}

		// ----- Make sure the process run for the next chunk
			$thisQuery['Processed'] += $thisQuery['Limit'];
			if ($thisQuery['Processed'] > $thisQuery['Total']) {
				$thisQuery['Processed'] = $thisQuery['Total'];
			}
			$thisQuery['Offset'] = $thisQuery['Processed'] - 1;

			$dbUpgradeStatus[get_class($this)] = $thisQuery;
			IEM::sessionSet('DatabaseUpgradeStatusList', $dbUpgradeStatus);
		// -----

		// -----
		// Will return 1 if need to process the same table, TRUE if processing complete, FALSE if process failed
		// Will also process subsequent commands after finishing the main process
		// -----
			if ($thisQuery['Processed'] >= $thisQuery['Total']) {
				// save all of the stat -> link associations here.
				$query = "INSERT INTO " . SENDSTUDIO_TABLEPREFIX . "stats_links SELECT statid, linkid FROM " . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks GROUP BY statid, linkid";
				$this->Db->Query($query);
				return true;
			} else {
				return 1;
			}
		// -----
	}
Esempio n. 13
0
	/**
	* DisplayEditTemplate
	* Prints out stage 2 of editing a template based on whether this is a text, html or multipart template. This information is stored in the session, so we need to retrieve those settings.
	* This function is used both when creating and editing a template.
	*
	* @param Int $templateid If there is a template id, we are updating an existing template. If there is no template id, we are creating a new template. This changes form actions depending on what we're doing.
	*
	* @see GetApi
	* @see GetUser
	* @see Templates_API::Load
	* @see Templates_API::GetBody
	* @see FetchEditor
	*
	* @return Void Prints out the form, doesn't return anything.
	*/
	function DisplayEditTemplate($templateid=0, $server_template=false)
	{
		$template = $this->GetApi();
		$templatecontents = array('text' => '', 'html' => '');

		$user = IEM::getCurrentUser();

		if ($templateid > 0) {
			$GLOBALS['SaveAction'] = 'Edit&SubAction=Save&id=' . $templateid;
			$GLOBALS['Heading'] = GetLang('EditTemplate');
			$GLOBALS['Intro'] = GetLang('EditTemplateIntro_Step2');
			$GLOBALS['Action'] = 'Edit&SubAction=Complete&id=' . $templateid;
			$GLOBALS['CancelButton'] = GetLang('EditTemplateCancelButton');

			$template->Load($templateid);

			$show_misc_options = false;
			if ($user->HasAccess('Templates', 'Approve')) {
				$show_misc_options = true;
				$GLOBALS['IsActive'] = ($template->Active()) ? ' CHECKED' : '';
			} else {
				$GLOBALS['ShowActive'] = 'none';
			}

			if ($user->HasAccess('Templates', 'Global')) {
				$show_misc_options = true;
				$GLOBALS['IsGlobal'] = ($template->IsGlobal() && $template->Active()) ? ' CHECKED' : '';
			} else {
				$GLOBALS['ShowGlobal'] = 'none';
			}

			if (!$show_misc_options) {
				$GLOBALS['ShowMiscOptions'] = 'none';
			}

			$templatecontents['text'] = $template->GetBody('text');
			$templatecontents['html'] = $template->GetBody('html');
		} else {
			$GLOBALS['SaveAction'] = 'Create&SubAction=Save&id=' . $templateid;
			$GLOBALS['Heading'] = GetLang('CreateTemplate');
			$GLOBALS['Intro'] = GetLang('CreateTemplateIntro_Step2');
			$GLOBALS['Action'] = 'Create&SubAction=Complete';
			$GLOBALS['CancelButton'] = GetLang('CreateTemplateCancelButton');

			if (!$user->HasAccess('Templates', 'Global')) {
				$GLOBALS['ShowGlobal'] = 'none';
			}

			$show_misc_options = false;
			if ($user->HasAccess('Templates', 'Approve')) {
				$GLOBALS['IsActive'] = ' CHECKED';
				$show_misc_options = true;
			} else {
				$GLOBALS['ShowActive'] = 'none';
			}

			if (!$show_misc_options) {
				$GLOBALS['ShowMiscOptions'] = 'none';
			}
		}

		if ($server_template) {
			$templatecontents['html'] = $template->ReadServerTemplate($server_template);
		}

		// 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_template = IEM::sessionGet('Templates'.$templateid);
		$session_template['id'] = (int)$templateid;
		$session_template['contents'] = $templatecontents;
		IEM::sessionSet('Templates'.$templateid, $session_template);
		$editor = $this->FetchEditor('Templates'.$templateid);
		$GLOBALS['Editor'] = $editor;
		$this->ParseTemplate('Template_Form_Step2');
	}
Esempio n. 14
0
	/**
	* Process
	* This handles working out what stage you are up to and so on with workflow.
	* Handles editing of schedules, pausing, resuming and deleting of schedules.
	* Deleting a scheduled event (especially) needs to update statistics if there are any emails left over in the queue.
	*
	* @see GetUser
	* @see User_API::HasAccess
	* @see SENDSTUDIO_CRON_ENABLED
	* @see GetApi
	* @see Jobs_API::PauseJob
	* @see Jobs_API::ResumeJob
	* @see Jobs_API::LoadJob
	* @see ManageSchedules
	* @see CheckJob
	* @see AdjustTime
	*/
	function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : null;
		if (!SENDSTUDIO_CRON_SEND) {
			$popup = (in_array($action, $this->PopupWindows)) ? true : false;
			$this->PrintHeader($popup);
			$GLOBALS['Error'] = GetLang('CronNotEnabled');
			$this->ParseTemplate('ErrorMsg');
			$this->PrintFooter();
			return;
		}
		
		$user = GetUser();
		$access = $user->HasAccess('Newsletters', 'Send');

		$popup = (in_array($action, $this->PopupWindows)) ? true : false;
		$this->PrintHeader($popup);

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

		if ($action == 'processpaging') {
			$this->SetPerPage($_GET['PerPageDisplay']);
			$action = '';
		}

		$jobapi = $this->GetApi('Jobs');

		$approve_job = IEM::sessionGet('ApproveJob');
		if ($approve_job) {
			if (isset($_GET['A'])) {
				$jobapi->ApproveJob($approve_job, $user->Get('userid'));
				$GLOBALS['Message'] = $this->PrintSuccess('JobScheduledOK');
				IEM::sessionRemove('ApproveJob');
			}
		}

		$jobid = 0;
		if (isset($_GET['job'])) {
			$jobid = (int)$_GET['job'];
		}

		switch ($action) {
			/**
			 * These methods are all called the same thing:
			 * 'ActionJob'
			 * The 'action' has an upper-case first letter
			 * then 'Job' has the same.
			 * They also all just take the jobid as the argument.
			 */
			case 'approve':
			case 'edit':
			case 'pause':
			case 'resend':
			case 'resume':
			case 'update':
				if (!$this->CanAccessJobs($jobid)) {
					$this->DenyAccess();
					return false;
				}

				$method = ucwords($action) . 'Job';
				call_user_func(array($this, $method), $jobid);
			break;

			case 'delete':
				$jobids = array();

				if (isset($_POST['jobs'])) {
					$jobids = $_POST['jobs'];
				} else {
					$jobids[] = $jobid;
				}

				if (!$this->CanAccessJobs($jobids)) {
					$this->DenyAccess();
					return false;
				}

				$this->DeleteJobs($jobids);

			break;

			default:
				$this->ManageSchedules();
		}
		$this->PrintFooter($popup);
	}
Esempio n. 15
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;
			}
		}
	}
Esempio n. 16
0
	/**
	 * TestBounceSettings
	 * Tries to log into the bounce server. It will print a success message or the error.
	 *
	 * @param Array $param Any parameters that needed to be passed into this function
	 *
	 * @return Void Doesn't return anything.
	 */
	private function TestBounceSettings($param)
	{
		$this->LoadLanguageFile('Bounce');

		$test_bounce_details = IEM::sessionGet('TestBounceDetails');

		if ($test_bounce_details === false || empty($test_bounce_details)) {
			$GLOBALS['Error'] = sprintf(GetLang('BadLogin_Details'), GetLang('BounceError_NoDetails'));
			$this->ParseTemplate('ErrorMsg');
			return;
		}

		$bounce_server = $test_bounce_details['server'];
		$bounce_user = $test_bounce_details['username'];
		$bounce_pass = $test_bounce_details['password'];

		$extra_settings = false;
		if ($test_bounce_details['extra_settings'] !== '') {
			$extra_settings = $test_bounce_details['extra_settings'];
		}

		$imap = ($test_bounce_details['imap'] === 1) ? true : false;

		$bounce_api = $this->GetApi('Bounce');

		$bounce_api->Set('bounceuser', $bounce_user);
		$bounce_api->Set('bouncepassword', base64_encode($bounce_pass));
		$bounce_api->Set('bounceserver', $bounce_server);
		$bounce_api->Set('imapaccount', $imap);
		if ($extra_settings) {
			$bounce_api->Set('extramailsettings', $extra_settings);
		}

		$login_ok = $bounce_api->Login();

		if (!$login_ok) {
			$GLOBALS['Error'] = sprintf(GetLang('BadLogin_Details'), $bounce_api->Get('ErrorMessage'));
			$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
		} else {
			$GLOBALS['Message'] = $this->PrintSuccess('BounceLogin_Successful');
		}
		$bounce_api->Logout(false);

		return $GLOBALS['Message'];
	}
Esempio n. 17
0
	/**
	 * CreateBackup
	 * @return Void Returns nothing
	 */
	function CreateBackup()
	{

		?>
			<script>
				self.parent.parent.location = 'index.php?Page=Upgrade&Step=2';
			</script>
		<?php
		return;

		$disabled_functions = explode(',', str_replace(' ', '', SENDSTUDIO_DISABLED_FUNCTIONS));

		if (!SENDSTUDIO_SAFE_MODE && !in_array('set_time_limit', $disabled_functions)) {
			set_time_limit(0);
		}

		$backupfile = IEM::sessionGet('BackupFile');
		if (!$backupfile) {
			$orig_backupfile = TEMP_DIRECTORY . '/system_backup.' . date('m-d-Y').'.txt';
			$backupfile = $orig_backupfile;
			$c = 1;
			while (true) {
				if (!is_file($backupfile)) {
					break;
				}
				$backupfile = $orig_backupfile . '.' . $c;
				$c++;
			}

			IEM::sessionSet('BackupFile', $backupfile);

			$tables_todo = $this->FetchTables();
			IEM::sessionSet('DatabaseTables_Todo', $tables_todo);

			$tables_done = array();
			IEM::sessionSet('DatabaseTables_Done', $tables_done);

			$backup_errors = array();
			IEM::sessionSet('DatabaseTables_BackupErrors', $backup_errors);
		}

		$tables_todo = IEM::sessionGet('DatabaseTables_Todo');

		$tables_done = IEM::sessionGet('DatabaseTables_Done');

		$backup_errors = IEM::sessionGet('DatabaseTables_BackupErrors');

		if ($tables_done == $tables_todo) {
			?>
				<script>
					self.parent.parent.location = 'index.php?Page=Upgrade&Step=2';
				</script>
			<?php
			return;
		}

		$tableProcessed = count($tables_done);
		$tableTotal = count($tables_todo);
		$percentProcessed = 0;

		foreach ($tables_todo as $p => $table) {
			if (in_array($table, $tables_done)) {
				continue;
			}

			$percentProcessed = ceil(($tableProcessed / $tableTotal)*100);
			echo "<script>\n";
			echo sprintf("self.parent.UpdateStatusReport('%s');", "Tables backed-up: {$tableProcessed}/{$tableTotal}");
			echo sprintf("self.parent.UpdateStatus('%s', %d);", "Backing up table \\'{$table}\\' ...", $percentProcessed);
			echo "</script>\n";
			flush();

			echo "Backing up table '" . $table . "'..<br/>\n";

			$this->PrintFooter(true);

			$result = $this->BackupTable($table, $backupfile);
			if (!$result) {
				$backup_errors[] = $table;
			}
			$tables_done[] = $table;

			$tableProcessed++;

			break;
		}

		IEM::sessionSet('DatabaseTables_Done', $tables_done);
		IEM::sessionSet('DatabaseTables_BackupErrors', $backup_errors);
		?>
			<script>
				setTimeout('window.location="index.php?Page=Upgrade&Action=CreateBackup"', 1);
			</script>
		<?php
	}
Esempio n. 18
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;
}
Esempio n. 19
0
$emailapi->TrackLinks(false);
$emailapi->ForceLinkChecks(false);
$emailapi->TrackOpens(false);

$emailapi->DisableUnsubscribe(true);

$emailapi->Set('CharSet', SENDSTUDIO_CHARSET);
$mail_result = $emailapi->Send(true);

/**
* Record the forward for statistical purposes.
*/
$forwardip = GetRealIp();
$forwardtime = $statsapi->GetServerTime();

$statid = IEM::sessionGet('Statid');

$forward_details = array(
	'forwardtime' => $forwardtime,
	'forwardip' => $forwardip,
	'subscriberid' => $subscriber_id,
	'statid' => $statid,
	'listid' => $list,
	'emailaddress' => $friendsemail
);

$statsapi->RecordForward($forward_details, $stats_idtype);

/**
* After all that, we'll print out the thanks message!
*/
 /**
  * IEM_Menu
  * This builds both the nav menu (with the dropdown items) and the text menu links at the top
  * It gets the main nav items from SendStudio_Functions::GenerateMenuLinks
  * It gets the text menu items from SendStudio_Functions::GenerateTextMenuLinks
  *
  * It will also see if test-mode is enabled (and display an appropriate message)
  * and also generate the right headers at the top (user is logged in as 'X', the current time is 'Y' etc).
  *
  * <b>Do *not* put any "ParseTemplate" calls inside IEM_Menu as you will cause an infinite loop.</b>
  * "ParseTemplate" calls "IEM_Menu" via IEM_DefaultVariables
  * Since the header menu has not yet finished building (ie the $menu variable is still null),
  * calling IEM_Menu at this stage will then call ParseTemplate (which then calls IEM_Menu).
  *
  * It returns an array:
  * - the first item is the main nav menu (contact lists, contacts, email campaigns etc)
  * - the second item is the text menu links at the top of the page (templates, users/manage account, logout etc)
  *
  * @uses SendStudio_Functions::GenerateMenuLinks
  * @uses SendStudio_Functions::GenerateTextMenuLinks
  *
  * @return Array Returns an array containing the main nav menu (the first item of the array) and the text menu items (the second item of the array).
  */
 private function IEM_Menu()
 {
     static $menu = null;
     // we've already built the menu? just return it.
     if ($menu !== null) {
         return $menu;
     }
     // see if there is an upgrade required or problem with the lk.
     if (!isset($_GET['Page']) || strtolower($_GET['Page']) != 'upgradenx') {
         if (IEM::sessionGet('LicenseError')) {
             if (!isset($_GET['Page']) || strtolower($_GET['Page']) != 'settings') {
                 header('Location: index.php?Page=Settings');
                 exit;
             }
         }
     }
     $user = IEM::getCurrentUser();
     // we're not logged in? we don't have a menu so just return empty items.
     if (!$user) {
         $menu = array('', '');
         return $menu;
     }
     $textlinks = SendStudio_Functions::GenerateTextMenuLinks();
     $nav_menus = '';
     if (!IEM::sessionGet('LicenseError')) {
         $nav_menus = SendStudio_Functions::GenerateMenuLinks();
     }
     $GLOBALS['UsingWYSIWYG'] = '0';
     if ($user->Get('usewysiwyg') == 1) {
         $GLOBALS['UsingWYSIWYG'] = '1';
     }
     $adjustedtime = AdjustTime();
     $GLOBALS['SystemDateTime'] = sprintf(GetLang('UserDateHeader'), AdjustTime($adjustedtime, false, GetLang('UserDateFormat'), true), $user->Get('usertimezone'));
     $name = $user->Get('username');
     $fullname = $user->Get('fullname');
     if ($fullname != '') {
         $name = $fullname;
     }
     $GLOBALS['UserLoggedInAs'] = sprintf(GetLang('LoggedInAs'), htmlentities($name, ENT_QUOTES, SENDSTUDIO_CHARSET));
     $unlimited_total_emails = $user->hasUnlimitedTotalCredit();
     if (!$unlimited_total_emails) {
         $creditUsed = API_USERS::getRecordById($user->userid)->getUsedCredit();
         $creditLeft = (int) $user->group->limit_totalemailslimit - (int) $creditUsed;
         $GLOBALS['TotalEmailCredits'] = sprintf(GetLang('User_Total_CreditsLeft'), SendStudio_Functions::FormatNumber($creditLeft));
     }
     $GLOBALS['MonthlyEmailCredits'] = '';
     $unlimited_monthly_emails = $user->hasUnlimitedMonthlyCredit();
     if (!$unlimited_monthly_emails) {
         $creditUsed = API_USERS::getRecordById($user->userid)->getUsedMonthlyCredit();
         $creditLeft = (int) $user->group->limit_emailspermonth - (int) $creditUsed;
         $GLOBALS['MonthlyEmailCredits'] = sprintf(GetLang('User_Monthly_CreditsLeft'), SendStudio_Functions::FormatNumber($creditLeft), SendStudio_Functions::FormatNumber($user->group->limit_emailspermonth));
         if (!$unlimited_total_emails) {
             $GLOBALS['MonthlyEmailCredits'] .= '&nbsp;&nbsp;|';
         }
     }
     $menu = array($nav_menus, $textlinks);
     return $menu;
 }
Esempio n. 21
0
 /**
  * Show_Send_Step_10
  * This is the page that gets shown when a user clicks "pause" in the split test send popup window.
  *
  * It marks the job as "paused" in the database
  * then shows an appropriate message.
  *
  * @uses GetApi
  * @uses Splittest_Send_API::PauseJob
  */
 public function Show_Send_Step_10()
 {
     $send_details = IEM::sessionGet('SplitTestSendDetails');
     if (!$send_details || !isset($send_details['splitid']) || (int) $send_details['splitid'] <= 0) {
         FlashMessage(GetLang('Addon_splittest_Send_InvalidSplitTest'), SS_FLASH_MSG_ERROR, $this->admin_url);
         return;
     }
     $job = (int) $send_details['Job'];
     /**
      * Pause it in the split test.
      * This makes it easier to work out a send's "state" (paused, in progress etc).
      */
     $send_api = $this->GetApi('Splittest_Send');
     $paused = $send_api->PauseJob($job, $send_details['splitid']);
     if ($paused) {
         FlashMessage(GetLang('Addon_splittest_Send_Paused_Success'), SS_FLASH_MSG_SUCCESS);
     } else {
         FlashMessage(GetLang('Addon_splittest_Send_Paused_Failure'), SS_FLASH_MSG_ERROR);
     }
     $flash_messages = GetFlashMessages();
     $this->template_system->Assign('FlashMessages', $flash_messages, false);
     $this->template_system->Assign('AdminUrl', $this->admin_url);
     $this->template_system->ParseTemplate('send_paused');
 }
Esempio n. 22
0
	/**
	* ExportSubscriber
	* Actually does the exporting of the subscriber.  Gets what it needs to export from the session, prints out the subscriber info to the export file.
	*
	* @param Int $subscriberid The subscriber to export.
	* @param Int $listid The list id subscriber is listed on
	* @param boolean $first Indicates whether or not this is the first record, used only by XML export (OPTIONAL)
	* @param boolean $last Indicates whether or not this is the last record, used only by XML export (OPTIONAL)
	*
	* @see GetApi
	* @see Subscribers_API::LoadSubscriberList
	* @see Subscribers_API::GetCustomFieldSettings
	*
	* @return Void Exports the subscriber information to the export file.
	*/
	function ExportSubscriber($subscriberid=0, $listid=0, $first = false, $last = false)
	{

		$exportinfo = IEM::sessionGet('ExportInfo');

		$list = $listid;
		$exportfile = $exportinfo['ExportFile'];
		$exportsettings = $exportinfo['Settings'];

		$subscriberApi = $this->GetApi('Subscribers');
		$subscriberinfo = $subscriberApi->LoadSubscriberList($subscriberid, $list);

		$CustomFieldApi = $this->GetApi('CustomFields');

		$bounce_info = false;

		if (in_array('btype', $exportsettings['FieldOptions'])) {
			$bounce_info = $subscriberApi->LoadSubscriberBounceInfo($subscriberid, $list);
		}

		if (in_array('btime', $exportsettings['FieldOptions'])) {
			if (!$bounce_info) {
				$bounce_info = $subscriberApi->LoadSubscriberBounceInfo($subscriberid, $list);
			}
		}

		if ($bounce_info) {
			$this->LoadLanguageFile('Stats');
		}

		$parts = array();
		foreach ($exportsettings['FieldOptions'] as $pos => $type) {
			switch (strtolower($type)) {
				case 'n':
					continue;
				break;

				case 'e':
					$parts[] = $subscriberinfo['emailaddress'];
				break;

				case 'f':
					$parts[] = ($subscriberinfo['format'] == 'h') ? GetLang('Format_HTML') : GetLang('Format_Text');
				break;

				case 'c':
					$parts[] = ($subscriberinfo['confirmed']) ? GetLang('Confirmed') : GetLang('Unconfirmed');
				break;

				case 'dmy':
					$parts[] = AdjustTime($subscriberinfo['subscribedate'], false, 'd/m/Y');
				break;

				case 'mdy':
					$parts[] = AdjustTime($subscriberinfo['subscribedate'], false, 'm/d/Y');
				break;

				case 'ymd':
					$parts[] = AdjustTime($subscriberinfo['subscribedate'], false, 'Y/m/d');
				break;

				case 'i':
					// if they have a confirm ip, we'll use that.
					$ip = $subscriberinfo['confirmip'];

					// if they don't have a confirm ip, check for the request ip.
					if (!$ip) {
						$ip = $subscriberinfo['requestip'];
					}

					// if they still don't have an ip then chuck in a message.
					if (!$ip) {
						$ip = GetLang('SubscriberIP_Unknown');
					}
					$parts[] = $ip;
				break;

				case 'btime':
					$parts[] = AdjustTime($bounce_info['bouncetime'], false, GetLang('BounceTimeFormat'));
				break;

				case 'btype':
					$parts[] = sprintf(GetLang('BounceTypeFormat'), GetLang('Bounce_Rule_' . $bounce_info['bouncerule']), $bounce_info['bouncetype']);
				break;

				default:
					if (is_numeric($type)) {
						$customfield_data = $subscriberApi->GetCustomFieldSettings($type, true);

						//if ($customfield_data['fieldtype'] == 'checkbox') {
							/**
							* See if we have loaded this custom field yet or not.
							* If we haven't then load it up.
							*
							* If we have, then use that instead for the checkdata calls.
							*
							* Doing it this way saves a lot of db queries/overhead especially with lots of custom fields.
							*/
							$fieldid = $customfield_data['fieldid'];

							if (!in_array($fieldid, array_keys($this->_customfields_loaded))) {
								$field_options = $CustomFieldApi->Load($fieldid, false, true);
								$subfield = $CustomFieldApi->LoadSubField($field_options);
								$this->_customfields_loaded[$fieldid] = $subfield;
							}

							$subf = $this->_customfields_loaded[$fieldid];
							$customfield_data['data'] = $subf->GetRealValue($customfield_data['data']);
						//}

						if (!isset($customfield_data['data'])) {
							$parts[] = '';
							continue;
						}

						$customfield_data = $customfield_data['data'];

						if (!is_array($customfield_data)) {
							if (substr_count($customfield_data, $exportsettings['FieldSeparator']) > 0) {
								if ($exportsettings['FieldEnclosedBy'] == '') {
									$customfield_data = '"' . $customfield_data . '"';
								}
							}

							$parts[] = $customfield_data;
							continue;
						}

						if ($exportsettings['FieldEnclosedBy'] != '') {
							$customfield_sanitized = implode(',', $customfield_data);
						} else {
							if (sizeof($customfield_data) > 1) {
								$customfield_sanitized = '"' . implode(',', $customfield_data) . '"';
							} else {
								$customfield_sanitized = implode(',', $customfield_data);

								if (substr_count($customfield_sanitized, $exportsettings['FieldSeparator']) > 0) {
									$customfield_sanitized = '"' . $customfield_sanitized . '"';
								}
							}
						}
						$parts[] = $customfield_sanitized;
					}
				break;
			}
		}


		switch($exportsettings['FileType']) {
			case 'xml':
				$line = '';

				if($first) {
					$line = "\t".'<records>'."\n";
				}

				$line .= "\t\t".'<record>'."\n";
				foreach($parts as $index => $part) {
					$line .= "\t\t\t".'<field id="'.$index.'">'.htmlspecialchars($part, ENT_QUOTES, SENDSTUDIO_CHARSET).'</field>'."\n";
				}
				$line .= "\t\t".'</record>'."\n";

				if($last) {
					$line .= "\t".'</records>' . "\n" . '</export>' . "\n";
				}
			break;

			case 'csv':
			default:
				if ($exportsettings['FieldEnclosedBy'] != '') {
					$line = '';
					foreach ($parts as $p => $part) {
						// To escape a field enclosure inside a field we double it up
						$part = str_replace($exportsettings['FieldEnclosedBy'], $exportsettings['FieldEnclosedBy'].$exportsettings['FieldEnclosedBy'], $part);
						$line .= $exportsettings['FieldEnclosedBy'] . $part . $exportsettings['FieldEnclosedBy'] . $exportsettings['FieldSeparator'];
					}
					$line = substr($line, 0, -1);
				} else {
					$line = implode($exportsettings['FieldSeparator'], $parts);
				}

				$line .= "\n";
			break;
		}

		$fp = fopen(TEMP_DIRECTORY . '/' . $exportinfo['ExportFile'], 'a');
		fputs($fp, $line, strlen($line));
		fclose($fp);
	}
Esempio n. 23
0
	/**
	* LoadSecret
	*
	* If the secret is stored in the Session, retrieve and decode it
	* Otherwise create a new secret.
	*
	* @return secret
	*/
	function LoadSecret()
	{
		$captchaCode = IEM::sessionGet('CaptchaCode');

		// if the secret stored in the session, retreive it
		// otherwise create a new secret
		if ($captchaCode) {
			$this->__secret = $captchaCode;
		}else{
			$this->CreateSecret();
		}
		return $this->__secret;
	}
Esempio n. 24
0
	/**
	 * GetNextUpgrade
	 * @return String Returns TRUE if successful, FALSE otherwise
	 */
	function GetNextUpgrade()
	{
		$upgrades_done = IEM::sessionGet('DatabaseUpgradesCompleted');

		$upgrades_todo = IEM::sessionGet('UpgradesToRun');

		if (empty($upgrades_todo)) {
			return null;
		}

		$versions = array_keys($upgrades_todo);

		if (empty($versions)) {
			IEM::sessionSet('UpgradesToRun', array());
			return null;
		}

		$version = $versions[0];

		$upgrade = array_shift($upgrades_todo[$version]);

		// if we've grabbed the last upgrade for that version, array_shift returns null.
		if ($upgrade === null) {
			unset($upgrades_todo[$version]);

			// if we've grabbed the last upgrade for that old version, see if there's another version we need to look at.
			$versions = array_keys($upgrades_todo);

			// if there are no more versions, then we're finished.
			if (empty($versions)) {
				IEM::sessionSet('UpgradesToRun', array());
				return null;
			}

			$version = $versions[0];

			$upgrade = array_shift($upgrades_todo[$version]);
		}

		$file = IEM_PATH . '/upgrades/' . $version . '/' . $upgrade . '.php';

		if (!is_readable($file)) {
			$this->error = 'Invalid Version - File Doesn\'t Exist';
			return false;
		}

		require_once($file);

		if (isset($upgrade_description)) {
			$this->FriendlyDescription = $upgrade_description;
		}

		return $upgrade;
	}
Esempio n. 25
0
	/**
	* PrintManageUsers
	* Prints a list of users to manage. If you are only allowed to manage your own account, only shows your account in the list. This allows you to edit, delete and so on.
	*
	* @see GetApi
	* @see GetPerPage
	* @see GetSortDetails
	* @see User_API::Admin
	* @see GetUsers
	* @see SetupPaging
	*
	* @return Void Prints out the list, doesn't return anything.
	*/
	function PrintManageUsers()
	{
		// ----- Sanitize and declare variables that is going to be used in this function
			$pageRecordPP		= 0;
			$pageCurrentIndex	= $this->GetCurrentPage();
			$pageSortInfo		= $this->GetSortDetails();

			$requestPreserveQuickSearch	= IEM::requestGetGET('PreserveQuickSearch', 0, 'intval');
			$requestSearch				= IEM::requestGetPOST('QuickSearchString', false);
			$requestGroupID				= IEM::requestGetGET('GroupID', 0, 'intval');

			$records			= array();
			$recordTotal		= 0;

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

			$currentUser		= IEM::getCurrentUser();

			$page = array(
				'messages'		=> GetFlashMessages(),
				'userreport'	=> '',
				'currentuserid'	=> $currentUser->userid
			);

			$permissions = array(
				'admin'				=> $currentUser->UserAdmin()
			);

			$groupInformation = array();
		// -----

		// Only admin/user admin able to view these pages
		if (!$currentUser->isAdmin()) {
			$this->DenyAccess();
		}

		$temp = ssk23twgezm2();
		if (is_array($temp) && isset($temp['message'])) {
			$page['userreport'] = $temp['message'];
		}

		if ($requestSearch === false && $requestPreserveQuickSearch) {
			$requestSearch = IEM::sessionGet('Users_Manage_QuickSearchString', '');
		} else {
			$requestSearch = trim($requestSearch);
			IEM::sessionSet('Users_Manage_QuickSearchString', $requestSearch);
		}

		// ----- Get "Record Per Page"
			if ($pageRecordPP == 0) {
				$pageRecordPP = $this->GetPerPage();
			}
		// -----

		$start = 0;
		if ($pageRecordPP != 'all') {
			$start = ($pageCurrentIndex - 1) * $pageRecordPP;
		}

		$recordTotal = $api->GetUsers(0, $pageSortInfo, true, $start, $pageRecordPP, $requestSearch, $requestGroupID);
		$records = $api->GetUsers(0, $pageSortInfo, false, $start, $pageRecordPP, $requestSearch, $requestGroupID);

		if (!empty($requestGroupID)) {
			$groupInformation = API_USERGROUPS::getRecordByID($requestGroupID);
		}

		for ($i = 0, $j = count($records); $i < $j; ++$i) {
			$records[$i]['processed_CreateDate'] = $this->PrintDate($records[$i]['createdate']);
			$records[$i]['processed_LastLoggedIn'] = ($records[$i]['lastloggedin'] ? $this->PrintDate($records[$i]['lastloggedin']) : '-');
		}

		// ----- Calculate pagination, this is using the older method of pagination
			$GLOBALS['PAGE'] = 'Users&PreserveQuickSearch=1' . (!empty($requestGroupID) ? "&GroupID={$requestGroupID}" : '');
			$GLOBALS['FormAction'] = 'Action=ProcessPaging&PreserveQuickSearch=1' . (!empty($requestGroupID) ? "&GroupID={$requestGroupID}" : '');

			$this->SetupPaging($recordTotal, $pageCurrentIndex, $pageRecordPP);
		// -----

		// ----- Print out HTML
			$tpl = GetTemplateSystem();
			$tpl->Assign('PAGE', $page);
			$tpl->Assign('records', $records);
			$tpl->Assign('permissions', $permissions);
			$tpl->Assign('quicksearchstring', $requestSearch);
			$tpl->Assign('groupInformation', $groupInformation);

			echo $tpl->ParseTemplate('Users', true);
		// -----

		return;
	}
Esempio n. 26
0
	/**
	* Process
	* Prints out the preview frames.
	*
	* @return Void Prints out the frame previews, doesn't return anything.
	*/
	function Process()
	{
		$design_rule_directory = IEM_PATH . '/resources/design_rules/';
		$design_rule_files = list_files($design_rule_directory);

		foreach ($design_rule_files as $design_rule) {
			$filename_parts = pathinfo($design_rule);
			if (isset($filename_parts['extension']) && $filename_parts['extension'] == 'php') {
				require_once $design_rule_directory . $design_rule;
			}
		}

		$valid_design_rules = array_keys($GLOBALS['Design_Rules']);

		$action = '';
		if (isset($_GET['Action'])) {
			$action = strtolower($_GET['Action']);
		}

		$sync_key = IEM::requestGetGET('sync', false);

		if ($sync_key) {
			$details = IEM::sessionGet('PreviewWindowHash');
			$details = $details[$sync_key];
		} else {
			$details = IEM::sessionGet('PreviewWindow');
		}

		if (empty($details)) {
			return;
		}

		switch ($action) {
			case 'top':
				$GLOBALS['SwitchOptions'] = '';

				if ($details['format'] == 't' || $details['format'] == 'b') {
					$GLOBALS['SwitchOptions'] .= '<option value="text">' . GetLang('TextPreview') . '</option>';
					$GLOBALS['HideDescription'] = "'';";
					$GLOBALS['ShowDescription'] = "none;";
				}

				if ($details['format'] == 'h' || $details['format'] == 'b') {
					$GLOBALS['SwitchOptions'] .= '<option value="html" SELECTED>' . GetLang('HTMLPreview') . '</option>';
					$GLOBALS['ShowDescription'] = "'';";
					$GLOBALS['HideDescription'] = "none;";
				}

				if ($details['showBroken']) {
					$designrules_description = '<a href="#" onClick="javascript: changeDisplay(\'html\');">'.GetLang('OriginalHTMLVersion').'</a>';
					foreach ($valid_design_rules as $design_rule) {
						$designrules_description .= '&nbsp;|&nbsp;<a href="#" onClick="javascript: changeDisplay(\'' . $design_rule . '\');">'.
													'<img border="0" src="images/email_clients/'.str_replace(' ', '_', $design_rule).'.gif" />&nbsp;'.$design_rule.
													'</a>';
					}
					$GLOBALS['DesignRules_Description'] = $designrules_description;
				} else $GLOBALS['DesignRules_Description'] = '';

				$this->ParseTemplate('Preview_Window_TopFrame', false, false);
			break;

			case 'brokenrules':
				$content = '';
				if (isset($details['htmlcontent'])) {
					$content = $details['htmlcontent'];
				}

				$GLOBALS['BrokenRuleList'] = '';
				foreach ($valid_design_rules as $design_rule) {
					$GLOBALS['BrokenRuleList'] .= 	'<a name="broken_rule_'.$design_rule.'"></a>'.
													'<div class="designRule" rulename="'.$design_rule.'">'.
													'<div class="designRuleLoading"> '. sprintf(GetLang('DesignRules_LoadingRules'), $design_rule).
													'... &nbsp;<img src="images/loading.gif" alt="loading" />'.
													'</div>'.
													'</div>';
				}
				header('Content-type: text/html; charset="' . SENDSTUDIO_CHARSET . '"');
				$this->ParseTemplate('Design_Rules_Broken', false, false);
			break;

			case 'processeachrule':
				header('Content-type: text/html; charset="' . SENDSTUDIO_CHARSET . '"');
				$reqRuleName = isset($_POST['rulename'])? $_POST['rulename'] : null;
				if (in_array($reqRuleName, $valid_design_rules)) {
					$details = IEM::sessionGet('PreviewWindow');
					$contents = isset($details['htmlcontent'])? $details['htmlcontent'] : '';

					require_once(SENDSTUDIO_API_DIRECTORY . '/design_rules_check.php');
					$api = new Design_Rules_Check_API();
					$api->Load($reqRuleName);
					$api->Process($contents);

					$broken_rules = $api->GetBrokenRules();

					print	'<div class="designRuleName">'.
							'<img src="images/'.(empty($broken_rules)? 'success.gif' : 'error.gif').'" alt="'.(empty($broken_rules)? 'success' : 'failed').'" />&nbsp;'.$reqRuleName.
							'</div>';

					$response = '';
					if (!empty($broken_rules)) {
						$response .= '<ul>';
						foreach ($broken_rules as $i=>$broken_rule) {
							$className = (($i + 1) % 2 == 0)? 'even' : 'odd';
							$response .= '<li class="'.$className.'">'.$broken_rule.'</li>';
						}
						$response .= '</ul>';
					} else {
						$response .= '<div class="designRuleOK">'.GetLang('DesignRules_NoRulesBroken').'</div>';
					}

					print $response;
				}
			break;

			case 'display':
				$displaytype = 'html';

				if (isset($_GET['Type'])) {
					$displaytype = $_GET['Type'];
				}

				if ($displaytype != 'html' && $displaytype != 'text') {
					if (!in_array($displaytype, $valid_design_rules)) {
						$displaytype = 'html';
					}
				}

				if ($details['format'] == 't') {
					$displaytype = 'text';
				}

				if ($displaytype == 'html') {
					header('Content-type: text/html; charset=' . SENDSTUDIO_CHARSET);
					echo $details['htmlcontent'];
					exit;
				}

				if ($displaytype == 'text') {
					header('Content-type: text/html; charset=' . SENDSTUDIO_CHARSET);
					echo nl2br($details['textcontent']);
					exit;
				}

				require_once(SENDSTUDIO_API_DIRECTORY . '/design_rules_check.php');
				$api = new Design_Rules_Check_API($displaytype);
				$new_content = $api->Process($details['htmlcontent'], true);

				header('Content-type: text/html; charset=' . SENDSTUDIO_CHARSET);
				echo $new_content;
			break;
		}
	}
Esempio n. 27
0
	/**
	* ShowStep_4
	* This prints the "upgrade failed" message to send to interspire if something went wrong.
	*
	* @return Void Prints the page out, doesn't return it.
	*/
	function ShowStep_4()
	{
		$errors = IEM::sessionGet('DatabaseUpgradesFailed');

		$errorReport = "Interspire Email Marketer Upgrade Error Report\n";
		$errorReport .= "----------------------------------------------\n";
		$errorReport .= gmdate("r")."\n";
		$errorReport .= "\n";
		$errorReport .= "Application URL: ".SENDSTUDIO_APPLICATION_URL."\n";
		$errorReport .= "Contact Email: ".SENDSTUDIO_EMAIL_ADDRESS."\n";
		$errorReport .= "\n";

		$errorReport .= "Upgrade Details:\n";
		$errorReport .= "----------------\n";
		$errorReport .= "Upgrade From: ".IEM::sessionGet('PreviousVersion')." (".IEM::sessionGet('PreviousDBVersion').")\n";
		$errorReport .= "Upgrade To: ".GetLang('SENDSTUDIO_VERSION')." (".SENDSTUDIO_DATABASE_VERSION.")\n";
		$errorReport .= "\n";

		$errorReport .= "Upgrade Error:\n";
		$errorReport .= "----------------\n";
		$errorReport .= implode("\n", $errors);
		$errorReport .= "\n";
		$errorReport .= "\n";

		$errorReport .= "Server Information:\n";
		$errorReport .= "---------------------\n";
		$errorReport .= "PHP Version: ".phpversion()."\n";
		$errorReport .= "Database Type: ".SENDSTUDIO_DATABASE_TYPE."\n";
		$errorReport .= "Database Version: ".SENDSTUDIO_SYSTEM_DATABASE_VERSION."\n";

		$this->PrintHeader();
		?>
		<br /><br /><br /><br />
		<table style="margin:auto;"><tr><td style="border:solid 2px #DDD; padding:20px; background-color:#FFF; width:450px">
		<table>
			<tr>
				<td class="Heading1">
						<img src="images/logo.jpg" />
				</td>
			</tr>
			<tr>
				<td style="padding:10px 0px 5px 0px">
						<strong><?php echo GetLang('Upgrade_Errors_Heading'); ?></strong>
						<p><?php echo GetLang('Upgrade_Errors_Message'); ?></p>
						<textarea class="Field400" style="width: 100%" rows="10" cols="20" onfocus="this.select();"><?php echo $errorReport; ?></textarea>
				</td>
			</tr>
		</table>
		</td></tr></table>
		<?php
		$this->PrintFooter();
	}
Esempio n. 28
0
	/**
	* ShowFriendStep
	* If this is a send to a friend form, then this step is shown.
	*
	* @see GetAPI
	* @see Forms_API::Load
	* @see GetHTMLEditor
	*
	* @return Void Doesn't return anything. Prints out the form for editing the send to friend message.
	*/
	function ShowFriendStep()
	{
		$user = GetUser();

		$formsession = IEM::sessionGet('Form');

		$formid = 0; $loaded = false;

		if (isset($formsession['FormID'])) {
			$formid = (int)$formsession['FormID'];
		}

		$GLOBALS['Action'] = 'Step5';

		if ($formid > 0) {
			$formapi = $this->GetApi();
			$loaded = $formapi->Load($formid);
			if ($loaded) {
				$GLOBALS['CancelButton'] = GetLang('EditFormCancelButton');
				$GLOBALS['Heading'] = GetLang('EditForm');
				$GLOBALS['Intro'] = GetLang('EditFormIntro');

				$GLOBALS['TextContent'] = $formapi->pages['SendFriendPage']['emailtext'];
				$htmlvalue = $formapi->pages['SendFriendPage']['emailhtml'];
			}
		}
		if ($formid <= 0 || !$loaded) {
			$GLOBALS['CancelButton'] = GetLang('CreateFormCancelButton');
			$GLOBALS['Heading'] = GetLang('CreateForm');
			$GLOBALS['Intro'] = GetLang('SendFriendPageIntro');

			$htmlvalue = GetLang('FormSendFriendPage_Email_HTML');
			$GLOBALS['TextContent'] = GetLang('FormSendFriendPage_Email_Text');
		}

		$GLOBALS['HTMLEditorName'] = 'myDevEditControl';

		$GLOBALS['TextHelpTip'] = $this->_GenerateHelpTip('HLP_SendFriendTextVersion');
		$GLOBALS['HTMLHelpTip'] = $this->_GenerateHelpTip('HLP_SendFriendHTMLVersion');

		$GLOBALS['ShowCustomFields'] = 'none';
		$GLOBALS['HTMLContent'] = $this->GetHTMLEditor($htmlvalue, false, 'myDevEditControl', 'exact', 260, 400);
		$GLOBALS['EditorHTML'] = $this->ParseTemplate('Form_Editor_HTML', true, false);
		$GLOBALS['EditorText'] = $this->ParseTemplate('Form_Editor_Text', true, false);

		$GLOBALS['FormSendFriendPage'] = $this->ParseTemplate('Form_Form_SendFriendPage', true);
	}
    /**
     * 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');
    }
Esempio n. 30
0
 /**
  * Admin_Action_ShowReport
  * This shows the detailed report window of the table errors.
  *
  * @return Void Does not return anything.
  */
 public function Admin_Action_ShowReport()
 {
     $report = IEM::sessionGet($this->addon_id . '_TablesReport');
     $report = print_r($report, true);
     $this->template_system->Assign('report', $report);
     $this->template_system->Assign('ApplicationUrl', $this->application_url, false);
     $this->template_system->ParseTemplate('error_report');
 }