/**
	* Process
	* Takes the appropriate action based on the action and user permissions
	*
	* @see GetUser
	* @see User_API::HasAccess
	* @see PrintHeader
	* @see PrintFooter
	*
	* @return Void Doesn't return anything. Takes the appropriate action.
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

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

		$secondary_actions = array('step2', 'sendpreview', 'view', 'processpaging', 'activate', 'deactivate', 'pause', 'resume', 'change', 'checkspam', 'viewcompatibility');
		if (in_array($action, $secondary_actions)) {
			$access = $user->HasAccess('Autoresponders');
		} else {
			$access = $user->HasAccess('Autoresponders', $action);
		}

		$popup = (in_array($action, $this->PopupWindows)) ? true : false;
		if (!in_array($action, $this->SuppressHeaderFooter)) {
			$this->PrintHeader($popup);
		}

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

		/**
		 * Check user permission to see whether or not they have access to the autoresponder
		 */
			$tempAPI = null;
			$tempCheckActions = array('activate', 'deactivate', 'copy', 'change', 'pause', 'resume', 'delete', 'step2', 'sendpreview', 'view', 'edit');
			$tempID = null;

			if (isset($_GET['id'])) {
				$tempID = $_GET['id'];
			} elseif(isset($_POST['autoresponders'])) {
				$tempID = $_POST['autoresponders'];
			}

			if (!is_null($tempID)) {
				$_GET['id'] = $tempID;
				$_POST['autoresponders'] = $tempID;

				if (!$user->Admin() && in_array($action, $tempCheckActions)) {
					if (!is_array($tempID)) {
						$tempID = array($tempID);
					}

					$tempAPI = $this->GetApi();

					foreach ($tempID as $tempEachID) {
						$tempEachID = intval($tempEachID);
						if ($tempEachID == 0) {
							continue;
						}

						if (!$tempAPI->Load($tempEachID)) {
							continue;
						}

						if ($tempAPI->ownerid != $user->userid) {
							$this->DenyAccess();
							return;
						}
					}
				}
			}

			unset($tempID);
			unset($tempCheckActions);
			unset($tempAPI);
		/**
		 * -----
		 */

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


		switch ($action) {
			case 'pause':
			case 'resume': 
				$autoresponderAPI = $this->GetApi();
				$autoresponderID = IEM::requestGetGET('id', 0, 'intval');
				$listID = IEM::requestGetGET('list', 0, 'intval');

				if ($action == 'pause') {
					$autoresponderAPI->PauseAutoresponder($autoresponderID);
				} else {
					$autoresponderAPI->ResumeAutoresponder($autoresponderID);
				}

				$this->ManageAutoresponders($listID);
			break;

			case 'viewcompatibility':
				$auto_info = IEM::sessionGet('Autoresponders');

				$html = (isset($_POST['myDevEditControl_html'])) ? $_POST['myDevEditControl_html'] : false;
				$text = (isset($_POST['TextContent'])) ? $_POST['TextContent'] : false;
				$showBroken = isset($_REQUEST['ShowBroken']) && $_REQUEST['ShowBroken'] == 1;
				$details = array();
				$details['htmlcontent'] = $html;
				$details['textcontent'] = $text;
				$details['format'] = $auto_info['Format'];

				$this->PreviewWindow($details, $showBroken);
				exit;
			break;

			case 'checkspamdisplay':
				$force = IEM::ifsetor($_GET['Force'], false);
				$this->CheckContentForSpamDisplay($force);
			break;

			case 'checkspam':
				$text = (isset($_POST['TextContent'])) ? $_POST['TextContent'] : false;
				$html = (isset($_POST['myDevEditControl_html'])) ? $_POST['myDevEditControl_html'] : false;
				$this->CheckContentForSpam($text, $html);
			break;

			case 'activate':
			case 'deactivate':
				$access = $user->HasAccess('Autoresponders', 'Approve');
				if (!$access) {
					$this->DenyAccess();
					break;
				}

				$id = (int)$_GET['id'];
				$autoapi = $this->GetApi();
				$autoapi->Load($id);
				if ($action == 'activate') {
					$prob_found = false;
					$max_size = (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024);
					if ($max_size > 0) {
						if ($autoapi->Get('autorespondersize') > $max_size) {
							$prob_found = true;
							if ($autoapi->Get('embedimages')) {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_Embed';
							} else {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_No_Embed';
							}
							$GLOBALS['Error'] = sprintf(GetLang($error_langvar), $this->EasySize($max_size, 0));
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						}
					}
					if (!$prob_found) {
						$allow_attachments = $this->CheckForAttachments($id, 'autoresponders');
						if ($allow_attachments) {
							$autoapi->Set('active', $user->Get('userid'));
							$GLOBALS['Message'] = $this->PrintSuccess('AutoresponderActivatedSuccessfully');
						} else {
							$GLOBALS['Error'] = GetLang('AutoresponderActivateFailed_HasAttachments');
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						}
					}
				} else {
					$autoapi->Set('active', 0);
					$GLOBALS['Message'] = $this->PrintSuccess('AutoresponderDeactivatedSuccessfully');
				}
				$autoapi->Save();

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

				$this->ManageAutoresponders($listid);
			break;

			case 'copy':
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$api = $this->GetApi();
				list($result, $files_copied) = $api->Copy($id);
				if (!$result) {
					$GLOBALS['Error'] = GetLang('AutoresponderCopyFail');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				} else {
					$api->Set('active', 0);
					$api->Save();
					$GLOBALS['Message'] = $this->PrintSuccess('AutoresponderCopySuccess');
					$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled');
					if (!$files_copied) {
						$GLOBALS['Error'] = GetLang('AutoresponderFilesCopyFail');
						$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
					}
				}
				if (isset($_GET['list'])) {
					$listid = (int)$_GET['list'];
				}

				$this->ManageAutoresponders($listid);
			break;

			case 'change':
				$subaction = strtolower($_POST['ChangeType']);
				$autolist = $_POST['autoresponders'];

				switch ($subaction) {
					case 'delete':
						$access = $user->HasAccess('Autoresponders', 'Delete');
						if ($access) {
							$this->DeleteAutoresponders($autolist);
						} else {
							$this->DenyAccess();
						}
					break;

					case 'approve':
					case 'disapprove':
						$access = $user->HasAccess('Autoresponders', 'Approve');
						if ($access) {
							$this->ActionAutoresponders($autolist, $subaction);
						} else {
							$this->DenyAccess();
						}
					break;
				}
			break;

			case 'delete':
				$id = (int)$_GET['id'];
				$autolist = array($id);
				$access = $user->HasAccess('Autoresponders', 'Delete');
				if ($access) {
					$this->DeleteAutoresponders($autolist);
				} else {
					$this->DenyAccess();
				}
			break;

			case 'step2':
				$listid = 0;
				if (isset($_GET['list'])) {
					$listid = (int)$_GET['list'];
				}

				$this->ManageAutoresponders($listid);
			break;

			case 'sendpreviewdisplay':
				$this->SendPreviewDisplay();
			break;

			case 'sendpreview':
				$this->SendPreview();
			break;

			case 'view':
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$type = strtolower(get_class($this));
				$autoresponderapi = $this->GetApi();
				if (!$autoresponderapi->Load($id)) {
					break;
				}

				// Log this to "User Activity Log"
				$logURL = SENDSTUDIO_APPLICATION_URL . '/admin/index.php?Page=' . __CLASS__ . '&Action=Edit&id=' . $_GET['id'];
				IEM::logUserActivity($logURL, 'images/autoresponders_view.gif', $autoresponderapi->name);

				$details = array();
				$details['htmlcontent'] = $autoresponderapi->GetBody('HTML');
				$details['textcontent'] = $autoresponderapi->GetBody('Text');
				$details['format'] = $autoresponderapi->format;
				$this->PreviewWindow($details);
			break;

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

				switch ($subaction) {
					case 'save':
					case 'complete':
						$user = IEM::getCurrentUser();
						$session_autoresponder = IEM::sessionGet('Autoresponders');

						$listid = $session_autoresponder['list'];

						if (!$session_autoresponder || !isset($session_autoresponder['autoresponderid'])) {
							$this->ManageAutoresponders($listid);
							break;
						}

						$text_unsubscribelink_found = true;
						$html_unsubscribelink_found = true;

						$id = $session_autoresponder['autoresponderid'];

						$autoapi = $this->GetApi();
						$autoapi->Load($id);

						$autoapi->Set('listid', $listid);

						if (isset($_POST['TextContent'])) {
							$textcontent = $_POST['TextContent'];
							$autoapi->SetBody('Text', $textcontent);
							$text_unsubscribelink_found = $this->CheckForUnsubscribeLink($textcontent, 'text');
							$session_autoresponder['contents']['text'] = $textcontent;
						}

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

							/**
							 * This is an effort not to overwrite the eixsting HTML contents
							 * if there isn't any contents in it (DevEdit will have '<html><body></body></html>' as a minimum
							 * that will be passed to here)
							 */
							if (trim($htmlcontent) == '') {
								$GLOBALS['Error'] = GetLang('UnableToUpdateAutoresponder');
								$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
								$this->EditAutoresponderStep4($id);
								break;
							}

							$autoapi->SetBody('HTML', $htmlcontent);
							$html_unsubscribelink_found = $this->CheckForUnsubscribeLink($htmlcontent, 'html');
							$session_autoresponder['contents']['html'] = $htmlcontent;
						}

						if (isset($_POST['subject'])) {
							$autoapi->Set('subject', $_POST['subject']);
						}

						foreach (array('name', 'format', 'searchcriteria', 'sendfromname', 'sendfromemail', 'replytoemail', 'bounceemail', 'tracklinks', 'trackopens', 'multipart', 'embedimages', 'hoursaftersubscription', 'charset', 'includeexisting', 'to_firstname', 'to_lastname') as $p => $area) {
							$autoapi->Set($area, $session_autoresponder[$area]);
						}

						$autoapi->Set('active', 0);

						$dest = strtolower(get_class($this));

						$movefiles_result = $this->MoveFiles($dest, $id);

						if ($movefiles_result) {
							if (isset($textcontent)) {
								$textcontent = $this->ConvertContent($textcontent, $dest, $id);
								$autoapi->SetBody('Text', $textcontent);
							}
							if (isset($htmlcontent)) {
								$htmlcontent = $this->ConvertContent($htmlcontent, $dest, $id);
								$autoapi->SetBody('HTML', $htmlcontent);
							}
						}

						// Delete any attachments we're meant to first
						if (SENDSTUDIO_ALLOW_ATTACHMENTS) {
							list($del_attachments_status, $del_attachments_status_msg) = $this->CleanupAttachments($dest, $id);

							if ($del_attachments_status) {
								if ($del_attachments_status_msg) {
									$GLOBALS['Success'] = $del_attachments_status_msg;
									$GLOBALS['Message'] .= $this->ParseTemplate('SuccessMsg', true, false);
								}
							} else {
								$GLOBALS['Error'] = $del_attachments_status_msg;
								$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
							}

							// Only save the new attachments after deleting the old ones
							list($attachments_status, $attachments_status_msg) = $this->SaveAttachments($dest, $id);

							if ($attachments_status) {
								if ($attachments_status_msg != '') {
									$GLOBALS['Success'] = $attachments_status_msg;
									$GLOBALS['Message'] .= $this->ParseTemplate('SuccessMsg', true, false);
								}
							} else {
								$GLOBALS['AttachmentError'] = $attachments_status_msg;
								$GLOBALS['Error'] = $attachments_status_msg;
								$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
							}
						}

						list($autoresponder_size, $autoresponder_img_warnings) = $this->GetSize($session_autoresponder);
						$GLOBALS['Message'] .= $this->PrintSuccess('AutoresponderUpdated', sprintf(GetLang('Autoresponder_Size_Approximate'), $this->EasySize($autoresponder_size)));
						$max_size = (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024);

						if (SENDSTUDIO_EMAILSIZE_WARNING > 0) {
							$warning_size = SENDSTUDIO_EMAILSIZE_WARNING * 1024;
							if ($autoresponder_size > $warning_size && ($max_size > 0 && $autoresponder_size < $max_size)) {
								if ($session_autoresponder['embedimages']) {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_Embed';
								} else {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_No_Embed';
								}
								$GLOBALS['Message'] .= $this->PrintWarning($warning_langvar, $this->EasySize($warning_size));
							}
						}

						if ($max_size > 0 && $autoresponder_size >= $max_size) {
							if ($session_autoresponder['embedimages']) {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_Embed';
							} else {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_No_Embed';
							}
							$GLOBALS['Error'] = sprintf(GetLang($error_langvar), $this->EasySize($max_size, 0));

							$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
						}

						$autoapi->Set('autorespondersize', $autoresponder_size);

						$result = $autoapi->Save();

						if (!$result) {
							$GLOBALS['Error'] = GetLang('UnableToUpdateAutoresponder');
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							$this->ManageAutoresponders($listid);
							break;
						}

						if ($autoresponder_img_warnings) {
							if ($session_autoresponder['embedimages']) {
								$warning_var = 'UnableToLoadImage_Autoresponder_List_Embed';
							} else {
								$warning_var = 'UnableToLoadImage_Autoresponder_List';
							}
							$GLOBALS['Message'] .= $this->PrintWarning($warning_var, $autoresponder_img_warnings);
						}

						if (!$html_unsubscribelink_found) {
							$GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInHTMLContent');
						}

						if (!$text_unsubscribelink_found) {
							$GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInTextContent');
						}
						
                        if(is_dir(TEMP_DIRECTORY . "/autoresponders/".$user->userid."_tmp")){remove_directory(TEMP_DIRECTORY . "/autoresponders/".$user->userid."_tmp");}


						if ($subaction == 'save') {
							$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled_Save');

							$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);

							$this->EditAutoresponderStep4($id);
							break;
						}

						$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled');

						$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);

						$this->ManageAutoresponders($listid);

					break;

					case 'step4':
						$sessionauto = IEM::sessionGet('Autoresponders');

						$sessionauto['sendfromname'] = $_POST['sendfromname'];
						$sessionauto['sendfromemail'] = $_POST['sendfromemail'];
						$sessionauto['replytoemail'] = $_POST['replytoemail'];
						$sessionauto['bounceemail'] = $_POST['bounceemail'];

						$sessionauto['charset'] = $_POST['charset'];

						$sessionauto['format'] = $_POST['format'];
						$sessionauto['hoursaftersubscription'] = (int)$_POST['hoursaftersubscription'];
						$sessionauto['trackopens'] = (isset($_POST['trackopens'])) ? true : false;
						$sessionauto['tracklinks'] = (isset($_POST['tracklinks'])) ? true : false;
						$sessionauto['multipart'] = (isset($_POST['multipart'])) ? true : false;
						$sessionauto['embedimages'] = (isset($_POST['embedimages'])) ? true : false;
						$sessionauto['includeexisting'] = (isset($_POST['includeexisting'])) ? true : false;

						$sessionauto['to_lastname'] = 0;
						if (isset($_POST['to_lastname'])) {
							$sessionauto['to_lastname'] = (int)$_POST['to_lastname'];
						}
						$sessionauto['to_firstname'] = 0;
						if (isset($_POST['to_firstname'])) {
							$sessionauto['to_firstname'] = (int)$_POST['to_firstname'];
						}

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep4($sessionauto['autoresponderid']);
					break;

					case 'step3':
						$sessionauto = IEM::sessionGet('Autoresponders');
						$sessionauto['name'] = $_POST['name'];
						$sessionauto['searchcriteria'] = array(
							'emailaddress' => '',
							'format' => '-1',
							'confirmed' => '1',
							'search_options' => array(),
							'customfields' => array()
						);

						if ($_POST['ShowFilteringOptions'] == 1) {
							$sessionauto['searchcriteria']['emailaddress'] = $_POST['emailaddress'];
							$sessionauto['searchcriteria']['format'] = $_POST['format'];
							$sessionauto['searchcriteria']['confirmed'] = $_POST['confirmed'];

							$search_options = (isset($_POST['Search_Options'])) ? $_POST['Search_Options'] : array();
							$sessionauto['searchcriteria']['search_options'] = $search_options;

							$customfields = (isset($_POST['CustomFields'])) ? $_POST['CustomFields'] : array();
							$sessionauto['searchcriteria']['customfields'] = $customfields;

							foreach ($sessionauto['searchcriteria']['customfields'] as $fieldid => $fieldvalue) {
								if (!$fieldvalue) {
									unset($sessionauto['searchcriteria']['customfields'][$fieldid]);
									continue;
								}
							}

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

								$sessionauto['searchcriteria']['link'] = $_POST['linkid'];
							}

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

								$sessionauto['searchcriteria']['newsletter'] = $_POST['newsletterid'];
							}
						}

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep3($sessionauto['autoresponderid']);
					break;

					default:
						$id = (int)$_GET['id'];

						IEM::sessionRemove('Autoresponders');
						$autosession = array('list' => (int)$_GET['list'], 'autoresponderid' => $id);
						IEM::sessionSet('Autoresponders', $autosession);

						$this->EditAutoresponderStep1($id);
				}
			break;

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

				switch ($subaction) {

					case 'save':
					case 'complete':
						$autoresponder = $this->GetApi();

						$user = IEM::getCurrentUser();
						$session_autoresponder = IEM::sessionGet('Autoresponders');

						if (!$session_autoresponder || !isset($session_autoresponder['name'])) {
							$this->ManageAutoresponders($listid);
							break;
						}

						$text_unsubscribelink_found = true;
						$html_unsubscribelink_found = true;

						$listid = $session_autoresponder['list'];

						$autoresponder->Set('listid', $listid);

						if (isset($_POST['TextContent'])) {
							$textcontent = $_POST['TextContent'];
							$autoresponder->SetBody('Text', $textcontent);
							$text_unsubscribelink_found = $this->CheckForUnsubscribeLink($textcontent, 'text');
							$session_autoresponder['contents']['text'] = $textcontent;
						}

						if (isset($_POST['myDevEditControl_html'])) {
							$htmlcontent = $_POST['myDevEditControl_html'];
							$autoresponder->SetBody('HTML', $htmlcontent);
							$html_unsubscribelink_found = $this->CheckForUnsubscribeLink($htmlcontent, 'html');
							$session_autoresponder['contents']['html'] = $htmlcontent;
						}

						if (isset($_POST['subject'])) {
							$autoresponder->Set('subject', $_POST['subject']);
						}

						foreach (array('name', 'format', 'searchcriteria', 'sendfromname', 'sendfromemail', 'replytoemail', 'bounceemail', 'tracklinks', 'trackopens', 'multipart', 'embedimages', 'hoursaftersubscription', 'charset', 'includeexisting', 'to_firstname', 'to_lastname') as $p => $area) {
							$autoresponder->Set($area, $session_autoresponder[$area]);
						}

						$autoresponder->Set('active', 0);

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

						$result = $autoresponder->Create();

						if (!$result) {
							$GLOBALS['Error'] = GetLang('UnableToCreateAutoresponder');
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							$this->ManageAutoresponders($listid);
							break;
						}

						/**
						* explicitly set the 'includeexisting' flag to false so we don't import the existing subscribers twice.
						* Create() & Save() both call ImportQueue if this flag is set, so ensure we don't do it twice.
						*/
						$autoresponder->Set('includeexisting', false);

						$session_autoresponder['autoresponderid'] = $result;
						IEM::sessionSet('Autoresponders', $session_autoresponder);

						if (SENDSTUDIO_ALLOW_ATTACHMENTS) {
							$dest = strtolower(get_class($this));
							$movefiles_result = $this->MoveFiles($dest, $result);
							if ($movefiles_result) {
								if (isset($textcontent)) {
									$textcontent = $this->ConvertContent($textcontent, $dest, $result);
									$autoresponder->SetBody('Text', $textcontent);
								}
								if (isset($htmlcontent)) {
									$htmlcontent = $this->ConvertContent($htmlcontent, $dest, $result);
									$autoresponder->SetBody('HTML', $htmlcontent);
								}
							}

							list($attachments_status, $attachments_status_msg) = $this->SaveAttachments($dest, $result);

							if ($attachments_status) {
								if ($attachments_status_msg != '') {
									$GLOBALS['Success'] = $attachments_status_msg;
									$GLOBALS['Message'] .= $this->ParseTemplate('SuccessMsg', true, false);
								}
							} else {
								$GLOBALS['Error'] = $attachments_status_msg;
								$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
							}
						}

						list($autoresponder_size, $autoresponder_img_warnings) = $this->GetSize($session_autoresponder);
						$GLOBALS['Message'] .= $this->PrintSuccess('AutoresponderUpdated', sprintf(GetLang('Autoresponder_Size_Approximate'), $this->EasySize($autoresponder_size)));
						$max_size = (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024);

						if (SENDSTUDIO_EMAILSIZE_WARNING > 0) {
							$warning_size = SENDSTUDIO_EMAILSIZE_WARNING * 1024;
							if ($autoresponder_size > $warning_size && ($max_size > 0 && $autoresponder_size < $max_size)) {
								if ($session_autoresponder['embedimages']) {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_Embed';
								} else {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_No_Embed';
								}
								$GLOBALS['Message'] .= $this->PrintWarning($warning_langvar, $this->EasySize($warning_size));
							}
						}

						if ($max_size > 0 && $autoresponder_size >= $max_size) {
							if ($session_autoresponder['embedimages']) {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_Embed';
							} else {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_No_Embed';
							}
							$GLOBALS['Error'] = sprintf(GetLang($error_langvar), $this->EasySize($max_size, 0));

							$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
						}

						$autoresponder->Set('autorespondersize', $autoresponder_size);

						$autoresponder->Save();

						if ($autoresponder_img_warnings) {
							if ($session_autoresponder['embedimages']) {
								$warning_var = 'UnableToLoadImage_Autoresponder_List_Embed';
							} else {
								$warning_var = 'UnableToLoadImage_Autoresponder_List';
							}
							$GLOBALS['Message'] .= $this->PrintWarning($warning_var, $autoresponder_img_warnings);
						}

						if (!$html_unsubscribelink_found) {
							$GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInHTMLContent');
						}

						if (!$text_unsubscribelink_found) {
							$GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInTextContent');
						}

						if ($subaction == 'save') {
							$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled_Save');
							$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);
							$this->EditAutoresponderStep4($result);
							break;
						}

						$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled');

						$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);

						$this->ManageAutoresponders($listid);
					break;

					case 'step4':
						$sessionauto = IEM::sessionGet('Autoresponders');

						$sessionauto['sendfromname'] = $_POST['sendfromname'];
						$sessionauto['sendfromemail'] = $_POST['sendfromemail'];
						$sessionauto['replytoemail'] = $_POST['replytoemail'];
						$sessionauto['bounceemail'] = $_POST['bounceemail'];

						$sessionauto['charset'] = $_POST['charset'];

						$sessionauto['format'] = $_POST['format'];
						$sessionauto['hoursaftersubscription'] = (int)$_POST['hoursaftersubscription'];
						$sessionauto['trackopens'] = (isset($_POST['trackopens'])) ? true : false;
						$sessionauto['tracklinks'] = (isset($_POST['tracklinks'])) ? true : false;
						$sessionauto['multipart'] = (isset($_POST['multipart'])) ? true : false;
						$sessionauto['embedimages'] = (isset($_POST['embedimages'])) ? true : false;

						$sessionauto['includeexisting'] = (isset($_POST['includeexisting'])) ? true : false;

						$sessionauto['to_lastname'] = 0;
						if (isset($_POST['to_lastname'])) {
							$sessionauto['to_lastname'] = (int)$_POST['to_lastname'];
						}

						$sessionauto['to_firstname'] = 0;
						if (isset($_POST['to_firstname'])) {
							$sessionauto['to_firstname'] = (int)$_POST['to_firstname'];
						}

						if (isset($_POST['TemplateID'])) {
							$sessionauto['TemplateID'] = $_POST['TemplateID'];
						}

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep4();

					break;

					case 'step3':
						$sessionauto = IEM::sessionGet('Autoresponders');
						$sessionauto['name'] = $_POST['name'];
						$sessionauto['searchcriteria'] = array(
							'emailaddress' => '',
							'format' => '-1',
							'confirmed' => '1',
							'search_options' => array(),
							'customfields' => array()
						);

						if ($_POST['ShowFilteringOptions'] == 1) {
							$sessionauto['searchcriteria']['emailaddress'] = $_POST['emailaddress'];
							$sessionauto['searchcriteria']['format'] = $_POST['format'];
							$sessionauto['searchcriteria']['confirmed'] = $_POST['confirmed'];

							$search_options = (isset($_POST['Search_Options'])) ? $_POST['Search_Options'] : array();
							$sessionauto['searchcriteria']['search_options'] = $search_options;

							$customfields = (isset($_POST['CustomFields'])) ? $_POST['CustomFields'] : array();
							$sessionauto['searchcriteria']['customfields'] = $customfields;

							foreach ($sessionauto['searchcriteria']['customfields'] as $fieldid => $fieldvalue) {
								if (!$fieldvalue) {
									unset($sessionauto['searchcriteria']['customfields'][$fieldid]);
									continue;
								}
							}

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

								$sessionauto['searchcriteria']['link'] = $_POST['linkid'];
							}

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

								$sessionauto['searchcriteria']['newsletter'] = $_POST['newsletterid'];
							}
						}

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep3();
					break;

					case 'step2':
						$listid = 0;
						if (isset($_POST['list'])) {
							$listid = (int)$_POST['list'];
						}

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

						$auto = array('list' => $listid);

						IEM::sessionSet('Autoresponders', $auto);

						$this->EditAutoresponderStep1();
					break;

					default:
						IEM::sessionRemove('Autoresponders');
						$this->ChooseCreateList();
				}
			break;

			default:
				$this->SetCurrentPage(1);
				$this->ChooseList('Autoresponders', 'step2');
			break;
		}

		if (!in_array($action, $this->SuppressHeaderFooter)) {
			$this->PrintFooter($popup);
		}
	}
Esempio n. 2
0
 public function Admin_Action_Edit()
 {
     $this->Admin_Action_PreConfig();
     $me = self::LoadSelf();
     $formId = (int) IEM::requestGetGET('formId');
     // if a form id was given, load the corresponding form
     $surveysApi = $this->getApi();
     $this->_checkSurveyAccess($formId);
     $formId = $surveysApi->getId();
     if (!empty($formId)) {
         $widgetTemplates = array();
         $widgetapi = $this->getSpecificApi('widgets');
         $surveys_widgets = $surveysApi->getWidgets($formId);
         foreach ($surveys_widgets as $widget) {
             $widgetapi->SetId($widget['id']);
             $me->template_system->Assign('randomId', 'widget_' . md5(microtime()));
             $me->template_system->Assign('widget', $widget);
             $me->template_system->Assign('widgetFields', $widgetapi->getFields());
             $me->template_system->Assign('widgetFieldOther', $widgetapi->getOtherField());
             $widgetTemplates[] = $me->template_system->ParseTemplate('widget.' . $widget['type'], true);
         }
         $me->template_system->Assign('widgetTemplates', $widgetTemplates);
     } else {
         // now die here..
         FlashMessage(GetLang('Addon_Surveys_InvalidSurveyID'), SS_FLASH_MSG_ERROR);
         // default checkbox state
         $surveysApi->email_feedback = 1;
         // default action after submitting a form
         $surveysApi->after_submit = 'show_message';
         // the default message to be shown
         $surveysApi->show_message = GetLang('Addon_surveys_Settings_ShowMessage');
         // the default uri to be shown
         $surveysApi->show_uri = GetLang('Addon_surveys_Settings_ShowUri');
         // the default error message to be shown
         $surveysApi->error_message = GetLang('Addon_surveys_Settings_ErrorMessage');
         // the default error message to be shown
         $surveysApi->submit_button_text = GetLang('Addon_surveys_Settings_Submit');
     }
     // assign default form email
     if (!$surveysApi->Get('email')) {
         $surveysApi->email = $survey->emailaddress;
     }
     // assign survey and widget data
     $form_data = $surveysApi->GetData();
     foreach ($form_data as &$form_val) {
         $form_val = htmlspecialchars($form_val);
     }
     $me->template_system->Assign('Heading', GetLang('Addon_surveys_Heading_Edit'));
     $me->template_system->Assign('Intro', GetLang('Addon_surveys_Edit_Intro'));
     $me->template_system->Assign('FlashMessages', GetFlashMessages(), false);
     $me->template_system->Assign('form', $form_data);
     $me->template_system->ParseTemplate('survey_form');
 }
Esempio n. 3
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. 4
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;
		}
	}
	/**
	* 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
	}
Esempio n. 6
0
     }
     unset($tempUser);
 }
 // Include the 'page' we're working with and process it.
 // This is getting the page class from functions directory.
 // Starting from version 5.6, the page structure has been gradually moved.
 if ($newPage === false) {
     require_once SENDSTUDIO_FUNCTION_DIRECTORY . "/{$page}.php";
     $system = new $page();
     $system->Process();
     unset($system);
     // This is the new page structure
 } else {
     require_once IEM_PATH . "/pages/{$newPage}.class.php";
     $tempClassName = "page_{$newPage}";
     $tempAction = 'page_' . preg_replace('/[^\\w]/', '_', IEM::requestGetGET('action', 'index'));
     $tempPageObject = new $tempClassName();
     // Check if "action" exists
     if (!is_callable(array($tempPageObject, $tempAction))) {
         // page_index will alwas exists (albeit only returning a FALSE)
         $tempAction = 'page_index';
     }
     // Call the function specified by "action" parameter
     $tempOutput = $tempPageObject->{$tempAction}();
     // TODO other return value have no effect at the moment.
     // Currently it only prints out a string
     if (is_string($tempOutput)) {
         echo $tempOutput;
     }
     // Call the page class destructor if it wants to cleanup anything
     unset($tempPageObject);
 /**
  * Enter description here...
  *
  * @return Void Does not return anything
  * @todo phpdoc
  */
 private function IEM_DefaultVariables()
 {
     static $variables = null;
     if (is_null($variables)) {
         $IEM = array('User' => GetUser(), 'ApplicationTitle' => GetLang('ApplicationTitle'), 'PageTitle' => GetLang('PageTitle'), 'CurrentPage' => IEM::requestGetGET('Page', IEM::requestGetGET('page', '')), 'ApplicationLogoImage' => APPLICATION_LOGO_IMAGE, 'ApplicationFavicon' => APPLICATION_FAVICON, 'InfoTips' => IEM::enableInfoTipsGet());
         list($IEM['LicenseError'], $IEM['LicenseMessage']) = sesion_start();
         IEM::sessionSet('LicenseError', $IEM['LicenseError']);
         if (!$IEM['LicenseError'] && isset($GLOBALS['ProductEdition'])) {
             $IEM['ApplicationTitle'] .= sprintf(GetLang('ApplicationTitleEdition'), $GLOBALS['ProductEdition']);
         }
         list($IEM['MenuLinks'], $IEM['TextLinks']) = $this->IEM_Menu();
         $variables = $IEM;
     }
     return $variables;
 }
	private function _handleSubmitAction()
	{
		// don't escape
		$template_dir = SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/templates';
		$this->_template = 	 GetTemplateSystem($template_dir);

		$this->_template->DefaultHtmlEscape = false;

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

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

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

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

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

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


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

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


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

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

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


				// make sure the required widget was even posted

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

							foreach ($values as $value) {

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

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

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




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


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



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

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

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

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

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

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

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

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

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

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

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

						foreach ($values as $value) {

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

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

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

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

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

					}
				}
			}

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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


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

			// perform file uploading

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

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

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

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

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

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

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

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

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

			default:
				// redirect back
				$this->redirectToReferer();
		}
	}
	/**
	 *
	 * @return unknown_type
	 * @todo phpdocs
	 */
	public function page_editGroup()
	{
		$id = IEM::requestGetGET('GroupID', 0, 'intval');

		$record = array();
		if (!empty($id)) {
			$record = API_USERGROUPS::getRecordByID($id);
		}

		$this->printEditor($record);
		return;
	}
Esempio n. 10
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. 11
0
	/**
	* Process
	* Works out where you are in the process and prints / processes the appropriate step.
	*
	* @see GetUser
	* @see User_API::HasAccess
	* @see PrintHeader
	* @see PopupWindows
	* @see PreviewWindow
	* @see ManageTemplates
	* @see EditTemplate
	* @see DisplayEditTemplate
	* @see ConvertContent
	* @see CreateTemplate
	*
	* @return Void Doesn't return anything. Handles processing and that's it.
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

		$action = strtolower(IEM::requestGetGET('Action', ''));
		$user = GetUser();

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

		// map the actions to the permissions required to do them
		$effective_permission = array(
			'' => null,
			'activate' => 'approve',
			'activateglobal' => 'global',
			'addtemplate' => 'create',
			'builtin' => 'builtin',
			'change' => 'edit',
			'complete' => 'view',
			'copy' => 'view',
			'create' => 'create',
			'deactivate' => 'approve',
			'deactivateglobal' => 'global',
			'edit' => 'edit',
			'manage' => null,
			'save' => 'edit',
			'step1' => 'view',
			'view' => 'view',
			'viewcompatibility' => null,
			);

		$access = false;

		if (!isset($_GET['id'])) {
			// we are not dealing with a particular template
			$access = $user->HasAccess('Templates', $effective_permission[$action]);
		} else if (!is_numeric($_GET['id'])) {
			// we are dealing with a particular built-in template
			$access = $user->HasAccess('Templates', 'builtin');
		} else {
			// we are dealing with a particular user template
			$id = intval($_GET['id']);
			if ($id == 0 && $action == 'create') {
				// we are saving/creating a new template
				$access = $user->HasAccess('Templates', $action);
			} else {
				$templates = array_keys($user->GetTemplates());
				if (in_array($id, $templates)) {
					// we at least have 'view' access
					if ($effective_permission[$action] == 'view') {
						$access = true;
					} else {
						$access = $this->_haveTemplateAccess($id, $effective_permission[$action]);
					}
				}
			}
		}

		$popup = (in_array($action, $this->PopupWindows)) ? true : false;
			if ($action != 'viewcompatibility') {
			$this->PrintHeader($popup);
		}

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

		switch ($action) {
			case 'viewcompatibility':
				$template_info = IEM::sessionGet('Templates'.$_GET['id']);

				$html = (isset($_POST['myDevEditControl_html'])) ? $_POST['myDevEditControl_html'] : false;
				$text = (isset($_POST['TextContent'])) ? $_POST['TextContent'] : false;
				$showBroken = isset($_REQUEST['ShowBroken']) && $_REQUEST['ShowBroken'] == 1;
				$details = array();
				$details['htmlcontent'] = $html;
				$details['textcontent'] = $text;
				$details['format'] = $template_info['Format'];

				$this->PreviewWindow($details, $showBroken);
				exit;
			break;

			case 'view':
				$details = array();
				$id = (isset($_GET['id'])) ? $_GET['id'] : 0;
				$type = strtolower(get_class($this));
				$template = $this->GetApi();
				if (is_numeric($id)) {
					if (!$template->Load($id)) {
						$details['textcontent'] = GetLang('UnableToLoadTemplate');
						$details['htmlcontent'] = '';
						$details['format'] = 't';
					} else {
						$details['htmlcontent'] = $template->GetBody('HTML');
						$details['textcontent'] = $template->GetBody('Text');
						$details['format'] = $template->format;
					}
				} else {
					$templatename = str_replace('servertemplate_', '', $id);

					$results = $template->ReadServerTemplate($templatename);
					if (!$results) {
						$details['textcontent'] = GetLang('UnableToLoadTemplateFromServer');
						$details['htmlcontent'] = '';
						$details['format'] = 't';
					} else {
						$details['htmlcontent'] = $results;
						$details['textcontent'] = '';
						$details['format'] = 'h';
					}
				}
				$this->PreviewWindow($details);
			break;

			case 'activate':
			case 'deactivate':
				$access = $user->HasAccess('Templates', 'approve');
				if (!$access) {
					$this->DenyAccess();
					break;
				}

				$id = (int)$_GET['id'];
				$templateapi = $this->GetApi();
				$templateapi->Load($id);

				$message = '';

				switch ($action) {
					case 'activate':
						$templateapi->Set('active', $user->Get('userid'));
						$GLOBALS['Success'] = GetLang('Template_ActivatedSuccessfully');
					break;
					case 'deactivate':
						$templateapi->Set('active', 0);
						if ($templateapi->IsGlobal()) {
							$GLOBALS['Error'] = GetLang('TemplateCannotBeInactiveAndGlobal');
							$message .= $this->ParseTemplate('ErrorMsg', true, false);
						}
						$GLOBALS['Success'] = GetLang('Template_DeactivatedSuccessfully');
				}
				$templateapi->Save();

				$message .= $this->ParseTemplate('SuccessMsg', true, false);
				$GLOBALS['Message'] = $message;

				$this->ManageTemplates();
			break;

			case 'activateglobal':
			case 'deactivateglobal':
				$access = $user->HasAccess('Templates', 'Global');
				if (!$access) {
					$this->DenyAccess();
					break;
				}

				$id = (int)$_GET['id'];
				$templateapi = $this->GetApi();
				$templateapi->Load($id);

				$message = '';

				switch ($action) {
					case 'activateglobal':
						$templateapi->Set('isglobal', $user->Get('userid'));
						$GLOBALS['Success'] = GetLang('Template_Global_ActivatedSuccessfully');
						if (!$templateapi->Active()) {
							$GLOBALS['Error'] = GetLang('TemplateCannotBeInactiveAndGlobal');
							$message .= $this->ParseTemplate('ErrorMsg', true, false);
						}
					break;
					case 'deactivateglobal':
						$templateapi->Set('isglobal', 0);
						$GLOBALS['Success'] = GetLang('Template_Global_DeactivatedSuccessfully');
					break;
				}
				$templateapi->Save();

				$message .= $this->ParseTemplate('SuccessMsg', true, false);
				$GLOBALS['Message'] = $message;

				$this->ManageTemplates();
			break;

			case 'delete':
				$templateid = (int)$_GET['id'];
				$access = $user->HasAccess('Templates', 'Delete');
				if ($access) {
					$this->DeleteTemplates(array($templateid));
				} else {
					$this->DenyAccess();
				}
			break;

			case 'change':
				$subaction = strtolower($_POST['ChangeType']);
				$templatelist = $_POST['templates'];

				switch ($subaction) {
					case 'delete':
						$access = $user->HasAccess('Templates', 'Delete');
						if ($access) {
							$this->DeleteTemplates($templatelist);
						} else {
							$this->DenyAccess();
						}
					break;

					case 'activate':
					case 'deactivate':
						$access = $user->HasAccess('Templates', 'Approve');
						if ($access) {
							$this->ActionTemplates($templatelist, $subaction);
						} else {
							$this->DenyAccess();
						}
					break;

					case 'global':
					case 'disableglobal':
						$access = $user->HasAccess('Templates', 'Global');
						if ($access) {
							$this->ActionTemplates($templatelist, $subaction);
						} else {
							$this->DenyAccess();
						}
					break;
				}
			break;

			case 'copy':
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$api = $this->GetApi();
				list($result, $newid, $files_copied) = $api->Copy($id);
				if (!$result) {
					$GLOBALS['Error'] = GetLang('TemplateCopyFail');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				} else {
					$changed = false;
					// check the permissions.
					// if we can't make it global, disable this aspect of it.
					if (!$user->HasAccess('Templates', 'Global')) {
						$changed = true;
						$api->Set('isglobal', 0);
					}

					// if we can't approve templates, then make sure we disable it.
					if (!$user->HasAccess('Templates', 'Approve')) {
						$changed = true;
						$api->Set('active', 0);
					}

					if ($changed) {
						$api->Save();
					}
					$GLOBALS['Message'] = $this->PrintSuccess('TemplateCopySuccess');
					if (!$files_copied) {
						$GLOBALS['Error'] = GetLang('TemplateFilesCopyFail');
						$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
					}
				}

				$user->LoadPermissions($user->userid);
				$user->GrantTemplateAccess($newid);
				$user->SavePermissions();

				$this->ManageTemplates();
			break;

			case 'edit':
				$template = $this->GetApi();

				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$template->Load($id);

				$subaction = (isset($_GET['SubAction'])) ? strtolower($_GET['SubAction']) : '';
				switch ($subaction) {
					case 'step2':
						$edittemplate = array('id' => $id);

						$checkfields = array('Name', 'Format');
						$valid = true; $errors = array();
						foreach ($checkfields as $p => $field) {
							if ($_POST[$field] == '') {
								$valid = false;
								$errors[] = GetLang('Template'.$field.'IsNotValid');
								break;
							} else {
								$value = $_POST[$field];
								$edittemplate[$field] = $value;
							}
						}

						if (!$valid) {
							$GLOBALS['Error'] = GetLang('UnableToUpdateTemplate') . '<br/>- ' . implode('<br/>- ',$errors);
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							$this->EditTemplate($id);
							break;
						}

						IEM::sessionSet('Templates'.$id, $edittemplate);
						$this->DisplayEditTemplate($id);
					break;

					case 'save':
					case 'complete':
						$session_template = IEM::sessionGet('Templates'.$id);

						if (isset($_POST['TextContent'])) {
							$template->SetBody('Text', $_POST['TextContent']);
							$textcontent = $_POST['TextContent'];
						}

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

							/**
							 * This is an effort not to overwrite the eixsting HTML contents
							 * if there isn't any contents in it (DevEdit will have '<html><body></body></html>' as a minimum
							 * that will be passed to here)
							 */
							if (trim($htmlcontent) == '') {
								$GLOBALS['Error'] = GetLang('UnableToUpdateTemplate');
								$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
								$this->DisplayEditTemplate($id);
								break;
							}

							$template->SetBody('HTML', $_POST['myDevEditControl_html']);
						}

						foreach (array('Name', 'Format') as $p => $area) {
							$template->Set(strtolower($area), $session_template[$area]);
						}

						$template->Set('active', 0);
						if (($user->HasAccess('Templates', 'Approve', $id)) ||
                                                     $template->ownerid == $user->userid) {
							if (isset($_POST['active'])) {
								$template->Set('active', $user->Get('userid'));
							}
						}

						$template->Set('isglobal', 0);

						if ($user->HasAccess('Templates', 'Global') && isset($_POST['isglobal'])) {
							$template->Set('isglobal', 1);
						}

						$dest = strtolower(get_class($this));
						$movefiles_result = $this->MoveFiles($dest, $id);
						if ($movefiles_result) {
							if (isset($textcontent)) {
								$textcontent = $this->ConvertContent($textcontent, $dest, $id);
								$template->SetBody('Text', $textcontent);
							}
							if (isset($htmlcontent)) {
								$htmlcontent = $this->ConvertContent($htmlcontent, $dest, $id);
								$template->SetBody('HTML', $htmlcontent);
							}
						}

						$result = $template->Save();

						if (!$result) {
							$GLOBALS['Error'] = GetLang('UnableToUpdateTemplate');
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							$this->ManageTemplates();
							break;
						} else {
							$GLOBALS['Message'] = $this->PrintSuccess('TemplateUpdated');

							if (!$template->Active() && isset($_POST['isglobal'])) {
								$GLOBALS['Error'] = GetLang('TemplateCannotBeInactiveAndGlobal');
								$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
							}
						}
						($subaction == 'save') ? $this->DisplayEditTemplate($id) : $this->ManageTemplates();
					break;

					default:
					case 'step1':
						$this->EditTemplate($id);
					break;
				}
			break;
			case 'create':
				$subaction = (isset($_GET['SubAction'])) ? strtolower($_GET['SubAction']) : '';
				switch ($subaction) {
					case 'step2':
						$server_template = false;
						if (isset($_POST['TemplateID'])) {
							$server_template = $_POST['TemplateID'];
						}

						$newtemplate = array();
						$checkfields = array('Name', 'Format');
						$valid = true; $errors = array();
						foreach ($checkfields as $p => $field) {
							if ($_POST[$field] == '') {
								$valid = false;
								$errors[] = GetLang('Template'.$field.'IsNotValid');
								break;
							} else {
								$value = $_POST[$field];
								$newtemplate[$field] = $value;
							}
						}
						if (!$valid) {
							$GLOBALS['Error'] = GetLang('UnableToCreateTemplate') . '<br/>- ' . implode('<br/>- ',$errors);
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							$this->CreateTemplate();
							break;
						}
						IEM::sessionSet('Templates0', $newtemplate);
						$this->DisplayEditTemplate(0, $server_template);
					break;

					case 'save':
					case 'complete':
						$user = IEM::getCurrentUser();
						$session_template = IEM::sessionGet('Templates0');

						$newtemplate = $this->GetApi();

						if (isset($_POST['TextContent'])) {
							$textcontent = $_POST['TextContent'];
							$newtemplate->SetBody('Text', $textcontent);
						}
						if (isset($_POST['myDevEditControl_html'])) {
							$htmlcontent = $_POST['myDevEditControl_html'];
							$newtemplate->SetBody('HTML', $htmlcontent);
						}

						foreach (array('Name', 'Format') as $p => $area) {
							$newtemplate->Set(strtolower($area), $session_template[$area]);
						}

						$newtemplate->Set('active', 0);
						if ($user->HasAccess('Templates', 'Approve')) {
							if (isset($_POST['active'])) {
								$newtemplate->Set('active', $user->Get('userid'));
							}
						}

						$newtemplate->Set('isglobal', 0);

						if ($user->HasAccess('Templates', 'Global') && isset($_POST['isglobal'])) {
							$newtemplate->Set('isglobal', 1);
						}

						$newtemplate->ownerid = $user->userid;
						$result = $newtemplate->Create();
						IEM::sessionSet('Templates'.$result, IEM::sessionGet('Templates0'));

						if (!$result) {
							$GLOBALS['Error'] = GetLang('UnableToCreateTemplate');
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
							$this->ManageTemplates();
							break;

						}

						$GLOBALS['Message'] = $this->PrintSuccess('TemplateCreated');

						if (!$newtemplate->Active() && isset($_POST['isglobal'])) {
							$GLOBALS['Error'] = GetLang('TemplateCannotBeInactiveAndGlobal');
							$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
						}

						$dest = strtolower(get_class($this));
						$movefiles_result = $this->MoveFiles($dest, $result);
						if ($movefiles_result) {
							if (isset($textcontent)) {
								$textcontent = $this->ConvertContent($textcontent, $dest, $result);
								$newtemplate->SetBody('Text', $textcontent);
							}
							if (isset($htmlcontent)) {
								$htmlcontent = $this->ConvertContent($htmlcontent, $dest, $result);
								$newtemplate->SetBody('HTML', $htmlcontent);
							}
						}
						$newtemplate->Save();

						$user->LoadPermissions($user->userid);
						$user->GrantTemplateAccess($result);
						$user->SavePermissions();

						if ($subaction == 'save') {
							$this->DisplayEditTemplate($result);
						} else {
							$this->ManageTemplates();
						}
					break;

					default:
					$this->CreateTemplate();
				}
			break;

			case 'addtemplate':
				$template = $this->GetApi();
				$user = IEM::getCurrentUser();

				$valid = true; $errors = array();
				if (!$valid) {
					$GLOBALS['Error'] = GetLang('UnableToCreateTemplate') . '<br/>- ' . implode('<br/>- ',$errors);
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->CreateTemplate();
					break;
				}

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

				$create = $template->Create();
				if (!$create) {
					$GLOBALS['Error'] = GetLang('UnableToCreateTemplate');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->CreateTemplate();
				} else {
					$GLOBALS['Message'] = $this->PrintSuccess('TemplateCreated');
					$this->EditTemplate($create);
				}
			break;

			case 'builtin':
				$this->ManageBuiltInTemplates();
			break;

			default:
				$this->ManageTemplates();
			break;
		}
		$this->PrintFooter($popup);
	}
Esempio n. 12
0
	/**
	* GetPageName
	* Used in remembering each section's paging settings.
	*
	* @see GetPerPage
	* @see SetPerPage
	*
	* @return String The name of the page/section in lower case, e.g. 'subscribers' or 'unknown' if not found.
	*/
	function GetPageName()
	{
		$page = IEM::requestGetGET('Page', '');
		if (empty($page)) {
			$page = IEM::requestGetGET('page', 'unknown');
		} else {
			$page = strtolower($page);
		}

		$action = IEM::requestGetGET('Action', IEM::requestGetGET('action', false));

		if ($action == 'ProcessPaging' && isset($_GET['SubAction'])) {
			$action = strtolower($_GET['SubAction']);
		}

		if ($page == 'stats' && !$action) {
			$action = 'newsletters';
		}

		// see bugid:2195 for why we handle this special case with subscribers
		if ($page == 'stats' || ($page == 'subscribers' && $action == 'banned')) {
			$page .= '_'.$action;
		}

		return $page;
	}
	/**
	* EditSubscriber
	* Prints the 'edit subscriber' form 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 'edit' access to the list before anything else.
	* @param Int $subscriberid The subscriberid to edit.
	* @param Int $segmentid The segment the subscriber is on.
	* @param String $msgtype The heading to show when editing 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 edit form and that's it.
	*/
	function EditSubscriber($listid = 0, $subscriberid = 0, $segmentid = 0, $msgtype = 'Error', $msg = false)
	{
		$user = GetUser();
		$access = $user->HasAccess('Subscribers', 'Edit');
		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');

		/**
		 * 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);
				$GLOBALS['SegmentID'] = $segmentid;
			}
		/**
		 * -----
		 */

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

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

		// Log this to "User Activity Log"
		if (IEM::requestGetGET('Action', '', 'strtolower') != 'save') {
			IEM::logUserActivity($_SERVER['REQUEST_URI'], 'images/contacts_view.gif', $subscriberinfo['emailaddress']);
		}

		$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'];

		$confirmed = '';
		foreach (array('1' => 'Confirmed', '0' => 'Unconfirmed') as $confirmoption => $option) {
			$selected = ($confirmoption == $subscriberinfo['confirmed']) ? ' SELECTED' : '';
			$confirmed .= '<option value="' . $confirmoption . '"' . $selected . '>' . GetLang($option) . '</option>';
		}

		$GLOBALS['ConfirmedList'] = $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';
		}

		$status = '';
		foreach (array('a' => 'Active', 'u' => 'Unsubscribed', 'b' => 'Bounced') as $statusoption => $option) {
			$selected = ($statusoption == $subscriber_status) ? ' SELECTED' : '';
			$status .= '<option value="' . $statusoption . '"' . $selected . '>' . GetLang($option) . '</option>';
		}
		$GLOBALS['StatusList'] = $status;

		$listformat = $list_api->GetListFormat();

		switch ($listformat) {
			case 't':
				$format = '<option value="t" SELECTED>' . GetLang('Format_Text') . '</option>';
			break;
			case 'h':
				$format = '<option value="h" SELECTED>' . GetLang('Format_HTML') . '</option>';
			break;
			case 'b':
				$selected = '';

				if ($subscriberinfo['format'] == 'h') {
					$selected = ' SELECTED';
				}
				$format = '<option value="h"' . $selected . '>' . GetLang('Format_HTML') . '</option>';

				$selected = '';

				if ($subscriberinfo['format'] == 't') {
					$selected = ' SELECTED';
				}
				$format .= '<option value="t"' . $selected . '>' . GetLang('Format_Text') . '</option>';
			break;
		}

		$GLOBALS['FormatList'] = $format;

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

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

		if (!empty($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 = $this->GetApi('CustomFields');

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

				$subfield = $customfields_api->LoadSubField();
                                $subscriber_settings_old = $subscriber_settings;
                                $subscriber_settings = $realValue = $subfield->GetRealValue($subscriber_settings);

				switch ($customfield_info['fieldtype']) {
					case 'date':
						$optionlist = '';
						$date_info = array();
						if ($subscriber_settings) {
							$date_parts = explode('/', $subscriber_settings);
							$date_part_check = $date_parts[0] + $date_parts[1] + $date_parts[2];
							if($date_part_check != 0){
                                for ($i = 0; $i <= 2; $i++) {
                                    if(strtolower($subfield->Settings['Key'][$i]) == 'month'){  $date_info['mm'] = $date_parts[$i]; }
                                    if(strtolower($subfield->Settings['Key'][$i]) == 'day'){  $date_info['dd'] = $date_parts[$i]; }
                                    if(strtolower($subfield->Settings['Key'][$i]) == 'year'){  $date_info['yy'] = $date_parts[$i]; }
                                }
							}
						}
						$extra_javascript .= '
								field_'.$customfield_info['fieldid'].'_check = CheckDate("CustomFields['.$customfield_info['fieldid'].']");
								if (!field_'.$customfield_info['fieldid'].'_check) {
									alert("' . sprintf(GetLang('EnterValidDate'), htmlspecialchars($customfield_info['name'], ENT_QUOTES, SENDSTUDIO_CHARSET)) . '");
									return false;
								}
							';

						$template_name = 'Subscribers_View_CustomField_Date';

						$fieldsettings = unserialize($customfield_info['fieldsettings']);
						$GLOBALS['GoogleCalendarButton'] = '';
						$GLOBALS['DateJSON'] ='{}';

						if (strlen($subscriber_settings)) {
							$date = explode('/', $subscriber_settings);
							$datejson = array_combine(array_slice($fieldsettings['Key'], 0, 3), $date);

							$GLOBALS['DateJSON'] = GetJSON($datejson);
							$GLOBALS['GoogleCalendarParameters'] = ",true";
						}

						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);
						}

						$this->Display_CustomField($customfield_info, $date_info);
					break;

					case 'radiobutton':
						$fieldsettings = (is_array($customfield_info['fieldsettings'])) ? $customfield_info['fieldsettings'] : unserialize($customfield_info['fieldsettings']);

						$default_value = ($subscriber_settings) ? $subscriber_settings : '';

						$optionlist = '';

						$c = 1;
						foreach ($fieldsettings['Key'] as $pos => $key) {
							$selected = '';
							if ($key == $default_value) {
								$selected = ' CHECKED';
							}

							$label_id = htmlspecialchars('CustomFields_' . $customfield_info['fieldid'] . '_'.$key, ENT_QUOTES, SENDSTUDIO_CHARSET);

							$optionlist .= '<label for="'.$label_id.'"><input type="radio" id="'.$label_id.'" name="CustomFields[' . $customfield_info['fieldid'] . ']" value="' . htmlspecialchars($key, ENT_QUOTES, SENDSTUDIO_CHARSET) . '"' . $selected . '>' . htmlspecialchars($fieldsettings['Value'][$pos], ENT_QUOTES, SENDSTUDIO_CHARSET) . '</label>';
							if ($c % 4 == 0) {
								$optionlist .= '<br/>';
							}
							$c++;
						}

						if ($customfield_info['required']) {
							$extra_javascript .= '
								field_'.$customfield_info['fieldid'].'_check = CheckRadio("CustomFields_'.$customfield_info['fieldid'].'");

								if (!field_'.$customfield_info['fieldid'].'_check) {
									alert("' . sprintf(GetLang('ChooseValueForCustomField'), htmlspecialchars($customfield_info['name'], ENT_QUOTES, SENDSTUDIO_CHARSET)) . '");
									return false;
								}
							';
						}

					break;

					case 'dropdown':
						$fieldsettings = (is_array($customfield_info['fieldsettings'])) ? $customfield_info['fieldsettings'] : unserialize($customfield_info['fieldsettings']);
						$optionlist = '';

						$default_value = ($subscriber_settings_old) ? $subscriber_settings_old : '';

						$optionlist .= '<option value="">' . $customfield_info['defaultvalue'] . '</option>';

						foreach ($fieldsettings['Key'] as $pos => $key) {
							$selected = '';
							if ($key == $default_value) {
								$selected = ' SELECTED';
							}

							$optionlist .= '<option value="' . htmlspecialchars($key, ENT_QUOTES, SENDSTUDIO_CHARSET) . '"' . $selected . '>' . htmlspecialchars($fieldsettings['Value'][$pos], ENT_QUOTES, SENDSTUDIO_CHARSET) . '</option>';
						}

						if ($customfield_info['required']) {
							$extra_javascript .= '
								fld = document.getElementById("CustomFields['.$customfield_info['fieldid'].']");
								selIndex = fld.selectedIndex;
								if (selIndex < 1) {
									alert("'.sprintf(GetLang('ChooseOptionForCustomField'), htmlspecialchars($customfield_info['name'], ENT_QUOTES, SENDSTUDIO_CHARSET)) . '");
									fld.focus();
									return false;
								}
							';
						}

					break;

					case 'checkbox':
						$fieldsettings = (is_array($customfield_info['fieldsettings'])) ? $customfield_info['fieldsettings'] : unserialize($customfield_info['fieldsettings']);

						$default_values = (unserialize($subscriber_settings_old)) ? unserialize($subscriber_settings_old) : array();

						$optionlist = '';
						$c = 1;

						foreach ($fieldsettings['Key'] as $pos => $key) {
							$selected = '';
							if (in_array($key, $default_values)) {
								$selected = ' CHECKED';
							}

							$label = htmlspecialchars('CustomFields[' . $customfield_info['fieldid'] . '][' . $key . ']', ENT_QUOTES, SENDSTUDIO_CHARSET);

							$optionlist .= '<label for="' . $label . '"><input type="checkbox" name="CustomFields[' . $customfield_info['fieldid'] . '][' . $pos . ']" id="' . $label . '" value="' . htmlspecialchars($key, ENT_QUOTES, SENDSTUDIO_CHARSET) . '"' . $selected . '>' . htmlspecialchars($fieldsettings['Value'][$pos], ENT_QUOTES, SENDSTUDIO_CHARSET) . '</label>';
							if ($c % 4 == 0) {
								$optionlist .= '<br/>';
							}

							$c++;
						}

						if ($customfield_info['required']) {
							$extra_javascript .= '
								CheckboxCheck = CheckMultiple("CustomFields[' . $customfield_info['fieldid'] . ']", f);
								if (!CheckboxCheck) {
									alert("' . sprintf(GetLang('ChooseValueForCustomField'), htmlspecialchars($customfield_info['name'], ENT_QUOTES, SENDSTUDIO_CHARSET)) . '");
									return false;
								}
							';
						}

					break;

					default:
						if ($customfield_info['required']) {
							$extra_javascript .= '
								if (document.getElementById("CustomFields['.$customfield_info['fieldid'].']").value == "") {
									alert("' . sprintf(GetLang('EnterValueForCustomField'), htmlspecialchars($customfield_info['name'], ENT_QUOTES, SENDSTUDIO_CHARSET)) . '");
									document.getElementById("CustomFields['.$customfield_info['fieldid'].']").focus();
									return false;
								}
							';
						}
						$optionlist = '';
						$subscriber_settings = $subscriber_settings;
				}

				$GLOBALS['OptionList'] = $optionlist;

                $GLOBALS['DefaultValue'] = '';
                if ( $realValue || $realValue == 0){
                    $GLOBALS['DefaultValue'] = htmlspecialchars($realValue, ENT_QUOTES, SENDSTUDIO_CHARSET);
                }elseif( $customfield_info['required'] ){
                    $GLOBALS['DefaultValue'] = htmlspecialchars($subscriber_settings_old, ENT_QUOTES, SENDSTUDIO_CHARSET);
                }

				$GLOBALS['FieldName'] = htmlspecialchars($customfield_info['name'], ENT_QUOTES, SENDSTUDIO_CHARSET);
				$GLOBALS['CustomFieldID'] = $customfield_info['fieldid'];
				$customfield_display[] = $this->ParseTemplate('CustomField_Edit_' . $customfield_info['fieldtype'], true, false);
			}

			$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['ExtraJavascript'] = $extra_javascript;
		}

		$GLOBALS['listid'] = $listid;

		$GLOBALS['CustomDatepickerUI'] = $this->ParseTemplate('UI.DatePicker.Custom_IEM', true);

		$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['SubscriberEvents_Intro'] = GetLang('SubscriberEvents_Intro');
		if ($user->HasAccess('Subscribers','EventSave')) {
			$GLOBALS['SubscriberEvents_Intro'] .= GetLang('SubscriberEvents_Intro_AddEvent');
		}

		if (IEM::sessionGet('gcal_allday')) {
			$GLOBALS['GoogleCalendarAllDay'] = 'true';
		} else {
			$GLOBALS['GoogleCalendarAllDay'] = 'false';
		}
		if (strlen($user->googlecalendarusername) && strlen($user->googlecalendarpassword)) {
			$GLOBALS['GoogleCalendarEnabled'] = 'true';
		} else {
			$GLOBALS['GoogleCalendarEnabled'] = 'false';
		}

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

		$this->ParseTemplate('Subscribers_Edit_Step2');
	}
Esempio n. 14
0
	/**
	 * Process
	 * This handles working out what stage you are up to and so on with workflow.
	 * @return Void Does not return anything
	 *
	 * @uses GetUser()
	 * @uses User_API::HasAccess()
	 * @uses SendStudio_Functions::PrintHeader()
	 * @uses SendStudio_Functions::DenyAccess()
	 * @uses SendStudio_Functions::PrintFooter()
	 * @uses SendStudio_Functions::_getGETRequest()
	 * @uses TriggerEmails::_ajax()
	 * @uses TriggerEmails::_create()
	 * @uses TriggerEmails::_edit()
	 * @uses TriggerEmails::_copy()
	 * @uses TriggerEmails::_enable()
	 * @uses TriggerEmails::_disable()
	 * @uses TriggerEmails::_save()
	 * @uses TriggerEmails::_delete()
	 * @uses TriggerEmails::_bulkAction()
	 * @uses TriggerEmails::_manage()
	 */
	public function Process()
	{
		// ----- Define and sanitize "common" variables that is used by this function
			$user = GetUser();

			$reqAction		= IEM::requestGetGET('Action', '', 'strtolower');
			$response		= '';
			$parameters 	= array();

			$parameters['message']	= GetFlashMessages();
			$parameters['user']		= GetUser();
			$parameters['action']	= $reqAction;
		// ------


		// ----- Check basic permission
			$access = $user->HasAccess('triggeremails') && check('Triggermails');
			if (!$access) {
				$this->PrintHeader();
				$this->DenyAccess();
				$this->PrintFooter();
				return;
			}
		// ------

		if (!SENDSTUDIO_CRON_ENABLED || SENDSTUDIO_CRON_TRIGGEREMAILS_S <= 0 || SENDSTUDIO_CRON_TRIGGEREMAILS_P <= 0) {
			$parameters['message'] .= $this->PrintWarning('TriggerEmails_Manage_CRON_Alert');
		}

		switch ($reqAction) {
			// AJAX request
			case 'ajax':
				$response = $this->_ajax($parameters);
			break;

			// Show "create" form
			case 'create':
				$response = $this->_create($parameters);
			break;

			// Show "edit" form
			case 'edit':
				$response = $this->_edit($parameters);
			break;

			// Copy trigger record
			case 'copy':
				$response = $this->_copy($parameters);
			break;

			// Enable record
			case 'enable':
				$response = $this->_enable($parameters);
			break;

			// Disable record
			case 'disable':
				$response = $this->_disable($parameters);
			break;

			// Save trigger record (from "create"/"edit" form)
			case 'save':
				$response = $this->_save($parameters);
			break;

			// Delete trigger record
			case 'delete':
				$response = $this->_delete($parameters);
			break;

			// Handle bulk action
			case 'bulkaction':
				$response = $this->_bulkAction($parameters);
			break;

			case 'processpaging':
			default:
				$response = $this->_manage($parameters);
			break;
		}


		// ----- Print output
			$ajax = ($reqAction == 'ajax');

			if (!$ajax) {
				$this->PrintHeader();
			} else {
				header('Content-type: application/json');
			}

			echo $response;

			if (!$ajax) {
				$this->PrintFooter();
			}
		// -----
	}
Esempio n. 15
0
		/**
		 * _TriggerEmailsStats_View_Tab8
		 * "Tab 8" of the trigger email statistics
		 *
		 * @param Array $record An associative array of the trigger email statistic record
		 * @return Array Returns tab information that is used by TriggerEmailsStats_View method
		 *
		 * @see Stats::TriggerEmailsStats_View()
		 */
		function _TriggerEmailsStats_View_Tab8($record)
		{
			// ----- Sanitize and declare variables that is going to be used in this function
				$user 					= IEM::userGetCurrent();

				$pageRecordPP			= 0;
				$pageCurrentIndex		= IEM::requestGetGET('DisplayPagetriggerfailed', 1, 'intval');
				$calendarRestrictions	= array_key_exists('recipients', $this->CalendarRestrictions) ? $this->CalendarRestrictions['recipients'] : '';

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

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

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

			$tabinfo['intro'] = sprintf(GetLang('TriggerEmails_Stats_Failed_Intro'), $record['triggeremailsname']);

			// setup calendar
			$GLOBALS['TabID'] = '7';
			$this->SetupCalendar('Action=ProcessCalendar&SubAction=TriggerEmails&NextAction=View&tab=8&id=' . $record['triggeremailsid']);
			$tabinfo['calendar'] = $GLOBALS['Calendar'];
			unset($GLOBALS['TabID']);
			unset($GLOBALS['Calendar']);

			$tabinfo['record_count'] = intval($api->GetFailedList($record['triggeremailsid'], $pageCurrentIndex, $pageRecordPP, $calendarRestrictions, true));

			// Set up error message if no recipients has been found, do not proceed with the rest of the function
			if ($tabinfo['record_count'] == 0) {
				$tempMessage = 'TriggerEmails_Stats_Failed_Error_NoRecipientFound';

				if (!empty($calendarRestrictions)) {
					$tempMessage = 'TriggerEmails_Stats_Failed_Error_NoRecipientFound_CalendarProblem';
				}

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

				return $tabinfo;
			}

			// ----- Get "Record Per Page"
				if ($requestAction == 'processpaging') {
					$pageRecordPP = IEM::requestGetGET('PerPageDisplaytriggerfailed', 10, 'intval');
					if ($pageRecordPP == 0) {
						$pageRecordPP = 10;
					}
					$this->SetPerPage($pageRecordPP);
				}

				if ($pageRecordPP == 0) {
					$pageRecordPP = $this->GetPerPage();
				}
			// -----

			// ----- Get records from DB
				$tempStart = 0;
				if ($pageRecordPP != 'all') {
					$tempStart = ($pageCurrentIndex - 1) * $pageRecordPP;
				}

				$tabinfo['records'] = $api->GetFailedList($record['triggeremailsid'], $tempStart, $pageRecordPP, $calendarRestrictions, false, GetLang('TimeFormat'));
			// -----

			// ----- Calculate pagination, this is still using the older method of pagination
				$GLOBALS['PAGE'] = 'Stats&Action=TriggerEmails&SubAction=View&id=' . $record['triggeremailsid'] . '&tab=8';
				$GLOBALS['FormAction'] = 'Action=ProcessPaging&SubAction=TriggerEmails&NextAction=View&id=' . $record['triggeremailsid'] . '&tab=8';
				$GLOBALS['PPDisplayName'] = 'triggerfailed';

				$this->SetupPaging($tabinfo['record_count'], $pageCurrentIndex, $pageRecordPP);
				$tabinfo['pagination_top'] = $this->ParseTemplate('Paging', true);
				$tabinfo['pagination_bottom'] = $this->ParseTemplate('Paging_Bottom', true);

				unset($GLOBALS['PAGE']);
				unset($GLOBALS['FormAction']);
				unset($GLOBALS['PPDisplayName']);
			// -----

			return $tabinfo;
		}
Esempio n. 16
0
	$areas_to_check = array('M', 'C');
	foreach ($areas_to_check as $key) {
		$tempParts = IEM::requestGetGET($key, false);
		if ($tempParts === false) {
			$GLOBALS['DisplayMessage'] = GetLang('InvalidUnsubscribeURL');
			$sendstudio_functions->ParseTemplate('Default_Form_Message');
			exit();
		}

		$foundparts[strtolower($key)] = $tempParts;
	}
// -----


// ----- The following GET request are optional (depending on the request type itself)
	$parts_to_check = array('N', 'A', 'L');
	foreach ($parts_to_check as $each) {
		$tempParts = IEM::requestGetGET($each, false);
		if ($tempParts === false) {
			continue;
		}

		$foundparts[strtolower($each)] = intval($tempParts);
	}
// -----



$subscriber_id = intval($foundparts['m']);
$confirmcode = $foundparts['c'];