Beispiel #1
0
/**
* FlashMessage
* Save a message in the session for the next time we display the page.
* This allows us to do a redirect back to the same page we were on so we don't have issues with hitting f5 and re-saving data.
* If a url is passed in, then it will try to do a redirect to that url after saving the message in the session.
* If headers have already been sent, then a javascript redirection is done instead of a header('Location: $url') type redirect.
*
* @param String $msg The message we will store. This needs to be the whole string/description, not the language variable.
* @param Int $msg_type The type of message we're going to show. This will be one of 4 states. This is used to work out which template to show the msg in.
* @param String $url If a url is passed to FlashMessage, then immediately after storing the message in the session, we'll redirect to that location. The url you pass in will be relative to the admin/ folder.
*
* @uses SS_FLASH_MSG_SUCCESS
* @uses SS_FLASH_MSG_ERROR
* @uses SS_FLASH_MSG_WARNING
* @uses SS_FLASH_MSG_INFO
* @see GetFlashMessages
*
* @return Void Doesn't return anything, the message (and it's details) are just stored in the session.
*/
function FlashMessage($msg='', $msg_type=SS_FLASH_MSG_SUCCESS, $url=null)
{
	$flash_messages = IEM::sessionGet('FlashMessages', false);
	if (!$flash_messages) {
		$flash_messages = array();
	}
	$flash_messages[] = array('message' => $msg, 'type' => $msg_type);
	IEM::sessionSet('FlashMessages', $flash_messages);

	if ($url !== null) {

		/**
		* If the url doesn't start with http (or https), put the full url at the start of it.
		* If it does start with http (or https), don't touch it.
		*/
		if (substr($url, 0, 4) !== 'http') {
			$url = SENDSTUDIO_APPLICATION_URL . '/admin/' . $url;
		}

		if (!headers_sent()) {
			header('Location: ' . $url);
			exit;
		}
		?>
		<script>
			window.location.href = '<?php echo $url; ?>';
		</script>
		<?php
		exit;
	}
}
 /**
  * Log user out of the system
  *
  * NOTE: If the $completeLogout parameter is NOT specified, the application
  * will NOT log out ALL users. The application will use the next user ID in the stack
  * (unless the stack is empty).
  *
  * @param boolean $completeLogout Whether or not to logout all users in the stack
  * @return boolean Returns TRUE if user is loggout successfuly, FALSE otherwise
  */
 public static final function userLogout($compleLogout = false)
 {
     if (empty(self::$_userStack)) {
         return false;
     }
     if ($compleLogout) {
         self::$_userStack = array();
     } else {
         array_pop(self::$_userStack);
     }
     self::userFlushCache();
     return IEM::sessionSet('__IEM_SYSTEM_CurrentUser_Stack', self::$_userStack);
 }
Beispiel #3
0
	/**
	* ShowStep_2
	* This actually runs an upgrade step and updates the status report (from step1) using javascript.
	* If a process fails, then this step immediately takes you to step 4 which prints out the error reports.
	*
	* @return Void Prints the page out, doesn't return it.
	*/
	function ShowStep_2()
	{
		$upgrades_failed = IEM::sessionGet('DatabaseUpgradesFailed');

		require_once(SENDSTUDIO_API_DIRECTORY . '/upgrade.php');

		$upgrade_api = new Upgrade_API();

		$running_upgrade = $upgrade_api->GetNextUpgrade();

		$total_steps = IEM::sessionGet('TotalSteps');
		$step_number = IEM::sessionGet('StepNumber');

		if (!is_null($running_upgrade) && !empty($running_upgrade)) {

			$msg = sprintf(GetLang('Upgrade_Running_StepXofY'), $this->FormatNumber($step_number), $this->FormatNumber($total_steps))." ({$running_upgrade}) ";

			$percent = ceil(($step_number / $total_steps) * 100);

			echo "<script>";
			echo "self.parent.UpdateStatus('".$msg."', '".$percent."');\n";
			echo "</script>";
			flush();

			$upgrade_result = $upgrade_api->RunUpgrade($running_upgrade);

			$upgrades_done[] = $running_upgrade;
			IEM::sessionSet('DatabaseUpgradesCompleted', $upgrades_done);

			if ($upgrade_result === true || $upgrade_result === false) {
				$upgrades_todo = IEM::sessionGet('UpgradesToRun', array());
				$version = array_keys($upgrades_todo);

				do {
					if (empty($version)) {
						$upgrades_todo = array();
						break;
					}

					if (empty($upgrades_todo[$version[0]])) {
						unset($upgrades_todo[$version[0]]);
						array_shift($version);
						continue;
					}

					array_shift($upgrades_todo[$version[0]]);
					break;
				} while(true);

				IEM::sessionSet('UpgradesToRun', $upgrades_todo);
			}

			if (!$upgrade_result) {
				$upgrades_failed[] = $upgrade_api->Get('error');
				IEM::sessionSet('DatabaseUpgradesFailed', $upgrades_failed);
				echo "<script>\n";
				echo "self.parent.ProcessFailed();";
				echo "</script>";
				exit;
			}

			IEM::sessionSet('StepNumber', ($step_number + 1));

			// Throw back to this same page to continue the upgrade process
			echo "<script>\n";
			echo "setTimeout(function() { window.location = 'index.php?Page=UpgradeNX&Step=2&random=" . uniqid('ss') . "'; }, 10);\n";
			echo "</script>";
			exit;
		} else {
                    $upgrades_failed[] = $upgrade_api->Get('error');
                    IEM::sessionSet('DatabaseUpgradesFailed', $upgrades_failed);
                    echo "<script>\n";
                    echo "self.parent.ProcessFailed();";
                    echo "</script>";
                    exit;                    
                }

		echo "<script>\n";
		echo "self.parent.ProcessFinished();";
		echo "</script>";
	}
Beispiel #4
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;
	}
Beispiel #5
0
 /**
  * saveResponseAction
  * Save the actual save response action
  *
  * @return void
  *
  */
 public function Admin_Action_SaveResponse()
 {
     $surveyId = (int) IEM::requestGetPOST('formId');
     // check permission here
     $this->_checkSurveyAccess($surveyId);
     $responseId = IEM::requestGetPOST('responseId');
     $responseNumber = IEM::requestGetPOST('responseNumber');
     $postWidgets = IEM::requestGetPOST('widget');
     $errors = 0;
     if ($postWidgets || $_FILES) {
         // 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) {
                         if ($field['value']) {
                             $postWidgets[$widgetId]['field'][$fieldId]['value'] = 'file_' . $field['value'];
                         }
                     }
                 }
             }
         }
         $survey_api = $this->getApi();
         $survey_api->Load($surveyId);
         $widgets = $survey_api->getWidgets();
         $widgetErrors = array();
         foreach ($widgets as $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'])) {
                             // get the value of an "other" field if it is one, otherwise just grab
                             // the normal value
                             if ($field['value'] == '__other__') {
                                 $isOther = true;
                                 $value = $field['other'];
                             } else {
                                 $value = $field['value'];
                             }
                             // make sure the value isn't blank
                             if (!$this->_validateIsBlank($value)) {
                                 $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++;
                 }
             }
             // validate file types
             if (isset($postWidgets[$widget['id']]) && $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('errorInvalidFileType'), $firstFileTypes, $lastFileType);
                     $errors++;
                 }
             }
         }
         // if there were errors, redirect back and display the errors
         if ($errors) {
             echo '<pre style="border: 1px solid red";><b style="color:RED;">YUDI_DEBUG:' . __FILE__ . ' ON LINE: ' . __LINE__ . '</b><br />';
             print_r($widgetErrors);
             echo '</pre>';
             die;
             // set the widget errors so we can retrieve them for the user
             IEM::sessionSet('survey.addon.widgetErrors', $widgetErrors);
             IEM::sessionSet('MessageText', GetLang('Addon_Surveys_saveResponseMessageError'));
             IEM::sessionSet('MessageType', MSG_ERROR);
         } else {
             // isntantiate a new response object
             $response_api = $this->getSpecificApi('responses');
             $response_api->Load($responseId);
             // delete the values in this response, since they will be added back in
             $response_api->deleteValues();
             // if the response was saved, then associate values to the response
             if ($response_api->Save()) {
                 $responseValue = $this->getSpecificApi('responsesvalue');
                 // 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) {
                         if (!isset($field['value'])) {
                             continue;
                         }
                         // foreign key for the response id
                         $responseValue->surveys_response_id = $responseId;
                         // 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 ($field['value'] == '__other__') {
                             $responseValue->value = $field['other'];
                             $responseValue->is_othervalue = 1;
                         } else {
                             $responseValue->file_value = "";
                             if (substr($field['value'], 0, 5) == "file_") {
                                 $value = str_replace("file_", "", $field['value']);
                                 $responseValue->file_value = md5($value);
                             }
                             $responseValue->value = $field['value'];
                         }
                         // save it
                         $responseValue->Save();
                     }
                 }
                 // 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) {
                                     $curDir = TEMP_DIRECTORY . DIRECTORY_SEPARATOR . 'surveys';
                                     $upBaseDir = $curDir . DIRECTORY_SEPARATOR . $surveyId;
                                     $upDir = $upBaseDir . DIRECTORY_SEPARATOR . $response_api->GetId();
                                     // if the main survey folder is not yet created then create it
                                     if (!is_dir($curDir)) {
                                         mkdir($curDir, 0755);
                                     }
                                     // if the base upload directory doesn't exist create it
                                     if (!is_dir($upBaseDir)) {
                                         mkdir($upBaseDir, 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);
                                 }
                             }
                         }
                     }
                 }
                 IEM::sessionSet('MessageText', GetLang('Addon_Surveys_saveResponseMessageSuccess'));
                 IEM::sessionSet('MessageType', SS_FLASH_MSG_SUCCESS);
             }
         }
     }
     // if view is set, then go to the view page for this response
     if (!$errors && IEM::requestGetPOST('view')) {
         if (IEM::requestGetPost('viewNext')) {
             $responseId = IEM::requestGetPost('viewNext');
         }
         header('Location: index.php?Page=Addons&Addon=surveys&Action=viewresponses&surveyId=' . $surveyId . '&responseId=' . $responseId);
         exit;
     }
     // redirect back to the edit page
     header('Location: index.php?Page=Addons&Addon=surveys&Action=editresponse&surveyId=' . $surveyId . '&responseId=' . $responseId);
     exit;
 }
	/**
	* Process
	* Executes functions for the page that was requested
	*
	* @return Void Returns nothing
	*/
	function Process()
	{
		$user = GetUser();

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


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

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

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

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

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

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

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

				$linksjson['linkclicks'] = $linkclicks;

				// Average Clicks
				$averageclicks = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						$this->ParseTemplate('Stats_Print_Header');

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

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

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

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

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

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

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

							$access = true;

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

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

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


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

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

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

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

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

													if (!$found_stats) {
														continue;
													}

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

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

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

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

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

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

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

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

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

												$sent_size = $summary['sendsize'];

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

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

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

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

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

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

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

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

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

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

												// Newsletter Summary Chart

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

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

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

												$GLOBALS['AutoresponderID'] = $autoresponderid;

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

										$domain_lines = array();

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

										$graph_details = array();

										$domain_display = '';

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

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

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

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

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


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

										$this->ParseTemplate('Stats_Summary_Perdomain');

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

											$GLOBALS['DisplayDomainList'] = $domain_display;

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

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

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

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

										$now = getdate();

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

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

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

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

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

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

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

										$this->ParseTemplate('Stats_Summary_Newsletter_Opens');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

										$this->ParseTemplate('Stats_Summary_Newsletter_Links');

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

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

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

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

									break; // click

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

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

										$this->ParseTemplate('stats_summary_newsletter_bounces');

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

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

									break; // bounce

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

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

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

										$now = getdate();

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

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

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

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

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

										$this->ParseTemplate('stats_summary_newsletter_unsubscribes');

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

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

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

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

									break; //unsubscribe

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

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

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

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

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

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

										$this->ParseTemplate('Stats_Summary_Newsletter_Forwards');

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

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

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

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

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

					break; // step2

					default: // step1

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

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

						switch ($statstype) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						$GLOBALS['PrintOptions'] = $print_options;

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

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

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

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

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

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

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

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

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

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

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

						$bounces = array();

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

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

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

					break; // newsletter_bounces

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

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

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

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

						$GLOBALS['Stats_Step3_Unsubscribes_List'] = $unsub_list;

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

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

						$GLOBALS['Stats_Step3_Forwards_List'] = $forward_list;

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

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

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

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

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

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

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

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

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

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

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

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

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

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

						$bounces = array();

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

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

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

					break; // triggeremails_bounces

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

						$statid = $token_data['statid'];

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

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

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

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

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

						$GLOBALS['Paging'] = $paging;

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

						$GLOBALS['Stats_Step3_Unsubscribes_List'] = $unsub_list;

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

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

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

						$statid = $token_data['statid'];

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

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

						$GLOBALS['Paging'] = $paging;

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

						$GLOBALS['Stats_Step3_Forwards_List'] = $forward_list;

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

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

					default:
					break;
				} // switch type
			break; //export
		} // switch selectaction
	}
	/**
	* Process
	* Does all of the work.
	* This handles processing of the functions. This includes adding, deleting, editing, associating with lists.
	*
	* @see EditCustomField
	* @see CreateCustomField_Step1
	* @see CreateCustomField_Step2
	* @see ManageCustomField_Lists
	* @see ManageCustomFields
	*
	* @return Void Doesn't return anything, just prints out the results.
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

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

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

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

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

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

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

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

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

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

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

				unset($api);

				$fieldapi->Load($fieldid);

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

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

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

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

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

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

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

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

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

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

                        $fieldapi->Save();

						$this->ManageCustomField_Lists($fieldid);

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

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

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

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

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

						$alloptions = $fieldapi->GetOptions();

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

							$newoptions[$fieldname] = $value;
						}

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

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

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

						$create = $fieldapi->Create();

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

					default:
						$this->CreateCustomField_Step1();
				}
			break;
			default:
				$this->ManageCustomFields();
		}
		$this->PrintFooter();
	}
	/**
	 * TestBounceSettingsDisplay
	 * Loads the template for the bounce test thickbox.
	 *
	 * @param Array $param Any parameters that needed to be passed to this function
	 *
	 * @return Void Doesn't return anything.
	 */
	private function TestBounceSettingsDisplay($param)
	{
		$test_bounce_details = array (
			'server' => $_GET['bounce_server'],
			'username' => $_GET['bounce_username'],
			'password' => $_GET['bounce_password'],
			'extra_settings' => $_GET['bounce_extrasettings'],
			'imap' => (isset($_GET['bounce_imap']) && $_GET['bounce_imap'] == 1) ? 1 : 0,
		);

		// Decrypt the password.
		$test_bounce_details['password'] = IEM::decrypt($test_bounce_details['password'], IEM::sessionGet('RandomToken'));

		IEM::sessionSet('TestBounceDetails', $test_bounce_details);

		$GLOBALS['Page'] = 'Lists';
		$this->LoadLanguageFile('Bounce');
		return $this->ParseTemplate('Bounce_Test_Window', true);
	}
	protected function printEditor($record = array())
	{
		$user               = IEM::userGetCurrent();
		$group              = new record_UserGroups($record);
		$permissionList     = $user->getProcessedPermissionList();
		$availableLists     = $user->GetLists();
		$availableSegments  = $user->GetSegmentList();
		$availableTemplates = $user->GetTemplates();
		$requestToken       = md5(mt_rand());

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

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

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

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

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

		$tpl->ParseTemplate('UsersGroups_Form');

		$this->PrintFooter();

		return;
	}
Beispiel #10
0
	/**
	* ManageSubscribers_Step2
	* Prints out the search forms to restrict the subscribers you want to see. This includes custom fields, format and so on.
	*
	* @param Int $listid Which list we are managing subscribers for.
	* @param Mixed $msg If there is a message (eg "no subscribers found"), it is passed in for display.
	*
	* @see GetApi
	* @see Lists_API::Load
	* @see Lists_API::GetListFormat
	* @see Lists_API::GetCustomFields
	* @see Search_Display_CustomField
	*
	* @return Void Doesn't return anything. Prints the search form and that's it.
	*/
	function ManageSubscribers_Step2($listid=0, $msg=false)
	{
		$user = GetUser();

		$user_lists = $user->GetLists();

		$access = $user->HasAccess('Subscribers', 'Manage');

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

		if ($msg) {
			$GLOBALS['Error'] = $msg;
			$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
		}

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

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

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

			// Make sure the IDs are numerics
			if (is_array($listid)) {
				$temp = array();
				foreach ($listid as $id) {
					array_push($temp, intval($id));
				}
				$listid = $temp;
			}
		}

		// Make sure that user can only select newsletter from his/her allowable list
		if (!$user->ListAdmin() && (is_numeric($listid) || is_array($listid))) {
			$allowableListIDs = array_keys($user_lists);
			if (is_array($listid)) {
				$listid = array_intersect($listid, $allowableListIDs);
			} else {
				$temp = in_array($listid, $allowableListIDs);
				if (!$temp) {
					$listid = null;
				}
			}

			if (empty($listid)) {
				if (!headers_sent()) {
					header('Location: index.php?Page=Subscribers&Action=Manage');
					exit;
				}
				?>
				<script>
					document.location.href = 'index.php?Page=Subscribers&Action=Manage';
				</script>
				<?php
				exit();
			}
		}

		$user = GetUser();
		$user_lists = $user->GetLists();

		if (is_numeric($listid)) {
			$listids = array($listid); // used to print visiblefields
			$listApi->Load($listid);
			$listname = $listApi->name;
			$GLOBALS['Heading'] = sprintf(GetLang('SubscribersManageSingleList'), htmlspecialchars($listname, ENT_QUOTES, SENDSTUDIO_CHARSET));
			$GLOBALS['List'] = $listid;
			$GLOBALS['DoNotShowFilteringOptionLabel'] = GetLang('SubscribersDoNotShowFilteringOptionsExplainOne');
			$GLOBALS['ShowFilteringOptionLabel'] = GetLang('SubscribersShowFilteringOptionsExplainOne');
		} else {
			if (!is_array($listid)) {
				$listids = array_keys($user_lists);
			} else {
				$listids = $listid;
			}
		}

		list($listids,$visiblefields,$visiblefields_list) = $this->GetVisibleFields($listid);

		if (is_array($listid)) {
			// Load list name for each of the selected mailing list
			$listnames = array();
			foreach ($user_lists as $id => $list_details) {
				array_push($listnames, $list_details['name']);
			}

			$GLOBALS['Heading'] = sprintf(GetLang('SubscribersManageMultipleList'), htmlspecialchars("'".implode("', '", $listnames)."'", ENT_QUOTES, SENDSTUDIO_CHARSET));
			$GLOBALS['List'] = implode('&Lists[]=',$listid);
			$GLOBALS['DoNotShowFilteringOptionLabel'] = GetLang('SubscribersDoNotShowFilteringOptionsExplain');
			$GLOBALS['ShowFilteringOptionLabel'] = GetLang('SubscribersShowFilteringOptionsExplain');
		} else {
			$GLOBALS['Heading'] = GetLang('SubscribersManageAnyList');
			$GLOBALS['List'] = $listid;
			$GLOBALS['DoNotShowFilteringOptionLabel'] = GetLang('SubscribersDoNotShowFilteringOptionsExplain');
			$GLOBALS['ShowFilteringOptionLabel'] = GetLang('SubscribersShowFilteringOptionsExplain');
		}

		$GLOBALS['VisibleFields'] = '';
		$CustomFieldsApi = $this->GetApi('CustomFields');

		foreach ($this->BuiltinFields as $key => $name) {
			$GLOBALS['VisibleFields'] .= '<option value="' . $key . '"';

			if (in_array($key,$visiblefields)) {
				$GLOBALS['VisibleFields'] .= ' selected="selected"';
			}

			$GLOBALS['VisibleFields'] .= '>' . htmlspecialchars(GetLang($name),ENT_QUOTES, SENDSTUDIO_CHARSET) . '</option>';
		}

		$fieldslisted = array();
		foreach ($listids as $listidTemp) {
			$customfields = $listApi->GetCustomFields($listidTemp);
			foreach ($customfields as $key => $details) {
				if (in_array($details['fieldid'],$fieldslisted)) {
					continue;
				}

				$GLOBALS['VisibleFields'] .= '<option value="' . $details['fieldid'] . '"';

				if (in_array($details['fieldid'],$visiblefields)) {
					$GLOBALS['VisibleFields'] .= ' selected="selected"';
				}

				$GLOBALS['VisibleFields'] .= '>' . htmlspecialchars($details['name'],ENT_QUOTES, SENDSTUDIO_CHARSET) . '</option>';

				$fieldslisted[] = $details['fieldid'];
			}
		}

		$GLOBALS['VisibleFieldsInfo'] = $this->ParseTemplate('subscriber_manage_step2_visiblefields',true);

		$GLOBALS['FormAction'] = 'Manage';

		$format_either = '<option value="-1">' . GetLang('Either_Format') . '</option>';
		$format_html = '<option value="h">' . GetLang('Format_HTML') . '</option>';
		$format_text = '<option value="t">' . GetLang('Format_Text') . '</option>';

		if (is_numeric($listid)) {
			$listformat = $listApi->GetListFormat();
			switch ($listformat) {
				case 'h':
					$format = $format_html;
				break;
				case 't':
					$format = $format_text;
				break;
				default:
					$format = $format_either . $format_html . $format_text;
			}
		} else {
			$format = $format_either . $format_html . $format_text;
		}

		IEM::sessionRemove('LinksForList');
		if (is_numeric($listid)) {
			IEM::sessionSet('LinksForList', $listid);
		}

		$GLOBALS['ClickedLinkOptions'] = $this->ShowLinksClickedOptions();

		$GLOBALS['OpenedNewsletterOptions'] = $this->ShowOpenedNewsletterOptions();

		$GLOBALS['FormatList'] = $format;

		$this->PrintSubscribeDate();

		/**
		 * Print custom fields options if applicable
		 */
			if (is_numeric($listid)) {
				$customfields = $listApi->GetCustomFields($listid);

				if (!empty($customfields)) {
					$customfield_display = $this->ParseTemplate('Subscriber_Manage_Step2_CustomFields', true, false);
					foreach ($customfields as $pos => $customfield_info) {
						$manage_display = $this->Search_Display_CustomField($customfield_info);
						$customfield_display .= $manage_display;
					}
					$GLOBALS['CustomFieldInfo'] = $customfield_display;
				}
			}
		/**
		 * -----
		 */

		$this->ParseTemplate('Subscriber_Manage_Step2');

		if (sizeof(array_keys($user_lists)) == 1) {
			return;
		}

		if (isset($_GET['Reset'])) {
			return;
		}

		if (!$msg && (isset($_POST['ShowFilteringOptions']) && $_POST['ShowFilteringOptions'] == 2)) {
			?>
			<script>
				document.forms[0].submit();
			</script>
			<?php
			exit();
		}
	}
	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();
		}
	}
	/**
	* RunUpgrade
	* Runs the query for the upgrade process
	* and returns the result from the query.
	* The calling function looks for a true or false result
	*
	* @return Mixed Returns true if the condition is already met (eg the column already exists).
	*  Returns false if the database query can't be run.
	*  Returns the resource from the query (which is then checked to be true).
	*/
	function RunUpgrade()
	{
		$tablePrefix = SENDSTUDIO_TABLEPREFIX;

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

		$user = IEM::getCurrentUser();

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

			$template->Load($templateid);

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

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

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

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

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

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

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

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

		// we don't really need to get/set the stuff here.. we could use references.
		// if we do though, it segfaults! so we get and then set the contents.
		$session_template = IEM::sessionGet('Templates'.$templateid);
		$session_template['id'] = (int)$templateid;
		$session_template['contents'] = $templatecontents;
		IEM::sessionSet('Templates'.$templateid, $session_template);
		$editor = $this->FetchEditor('Templates'.$templateid);
		$GLOBALS['Editor'] = $editor;
		$this->ParseTemplate('Template_Form_Step2');
	}
	/**
	* Process
	* This processes the ajax requests.
	* There are only two types of request - importfile and importurl.
	*
	* If it's importfile, it will display the 'fileupload' iframe again, and also process the file if there was one uploaded. It base 64 encodes the data to pass to javascript, this saves having to worry about newlines, quotes and so on. The javascript decodes it itself, then calls the DoImport function in the includes/js/javascript.js file.
	*
	* If it's importurl, it simply calls GetPageContents and returns that.
	*
	* @see GetPageContents
	*
	* @return Void Doesn't return anything, simply prints out the results.
	*/
	function Process()
	{
		// make sure they are logged in appropriately.
		if (!IEM::getCurrentUser()) {
			return;
		}

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

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

		$user = GetUser();

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

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

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

					$this->LoadLanguageFile('autoresponders');

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

					$userid = $user->userid;

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

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

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

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

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

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

				case 'importnewsletters':
					$listid = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						echo $page;
					}
				break;

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

					$lines = array();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

					$tpl = GetTemplateSystem();
					$tpl->Assign('SessionName', IEM::SESSION_NAME);
					$tpl->Assign('Pagination', $paging);
					$tpl->Assign('SessionID', IEM::sessionID());
					echo $tpl->ParseTemplate('Image_Manager_Sub');
				break;
			}
		}
	}
Beispiel #15
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;
		}
	}
Beispiel #16
0
function checksize($tyzeveh4, $cckoceji, $noxosi23)
{
	if ($cckoceji === "true") {
		return;
	}
	if (!$noxosi23) {
		return;
	}
	$enozirek = f0pen();
	if (!$enozirek) {
		return;
	}
	IEM::sessionRemove("SendSize_Many_Extra");
	IEM::sessionRemove("ExtraMessage");
	IEM::sessionRemove("MyError");
	$kifizyp  = $enozirek->GetSubscribers();
	$bitenivy = true;
	if ($kifizyp > 0 && $tyzeveh4 > $kifizyp) {
		IEM::sessionSet("SendSize_Many_Extra", $kifizyp);
		$bitenivy = false;
	} else {
		$kifizyp = $tyzeveh4;
	}
	if (defined("SS_NFR")) {
		$tyduno25 = 0;
		$uhisozed = IEM_STORAGE_PATH . "/.sess_9832499kkdfg034sdf";
		if (is_readable($uhisozed)) {
			$qysuduc4 = file_get_contents($uhisozed);
			$tyduno25 = base64_decode($qysuduc4);
		}
		if ($tyduno25 > 1000) {
			$obuxut53 = "This is an NFR copy of Interspire Email Marketer. You are only allowed to send up to 1,000 emails using this copy.\n\nFor further details, please see your NFR agreement.";
			IEM::sessionSet("ExtraMessage", "<script>$(document).ready(function() {alert('" . $obuxut53 . "'); document.location.href='index.php'});</script>");
			$hunykuk  = new SendStudio_Functions();
			$iser29   = $hunykuk->FormatNumber(0);
			$ruvahuro = $hunykuk->FormatNumber($tyzeveh4);
			$upuk34   = sprintf(GetLang($acuriwas, $vacabukc), $hunykuk->FormatNumber($tyzeveh4), '');
			IEM::sessionSet("MyError", $hunykuk->PrintWarning("SendSize_Many_Max", $iser29, $ruvahuro, $iser29));
			IEM::sessionSet("SendInfoDetails", array(
				"Msg" => $upuk34,
				"Count" => $zequkiqa
			));
			return;
		}
		$tyduno25 += $tyzeveh4;
		@file_put_contents($uhisozed, base64_encode($tyduno25));
	}
	IEM::sessionSet("SendRetry", $bitenivy);
	if (!class_exists("Sendstudio_Functions", false)) {
		require_once dirname(__FILE__) . "/sendstudio_functions.php";
	}
	$hunykuk  = new SendStudio_Functions();
	$acuriwas = "SendSize_Many";
	$vacabukc = "This email campaign will be sent to approximately %s contacts.";
	$xavededu = '';
	$zequkiqa = min($kifizyp, $tyzeveh4);
	if (!$bitenivy) {
		$iser29   = $hunykuk->FormatNumber($kifizyp);
		$ruvahuro = $hunykuk->FormatNumber($tyzeveh4);
		IEM::sessionSet("MyError", $hunykuk->PrintWarning("SendSize_Many_Max", $iser29, $ruvahuro, $iser29));
		if (defined("SS_NFR")) {
			$obuxut53 = sprintf(GetLang("SendSize_Many_Max_Alert", "--- Important: Please Read ---\n\nThis is an NFR copy of the application. This limit your sending to a maximum of %s emails. You are trying to send %s emails, so only the first %s emails will be sent."), $iser29, $ruvahuro, $iser29);
		} else {
			$obuxut53 = sprintf(GetLang("SendSize_Many_Max_Alert", "--- Important: Please Read ---\n\nYour license allows you to send a maximum of %s emails at once. You are trying to send %s emails, so only the first %s emails will be sent.\n\nTo send more emails, please upgrade. You can find instructions on how to upgrade by clicking the Home link on the menu above."), $iser29, $ruvahuro, $iser29);
		}
		IEM::sessionSet("ExtraMessage", "<script>$(document).ready(function() {alert('" . $obuxut53 . "');});</script>");
	}
	$upuk34 = sprintf(GetLang($acuriwas, $vacabukc), $hunykuk->FormatNumber($zequkiqa), $xavededu);
	IEM::sessionSet("SendInfoDetails", array(
		"Msg" => $upuk34,
		"Count" => $zequkiqa
	));
}
Beispiel #17
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 ManageForms
	* @see EditForm
	* @see CreateForm
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

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

		$secondary_actions = array('preview', 'gethtml', 'view', 'finish', 'step2', 'step3', 'step4', 'step5', 'manage', 'processpaging');
		if (in_array($action, $secondary_actions)) {
			$access = $user->HasAccess('Forms');
		} else {
			$access = $user->HasAccess('Forms', $action);
		}

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

		/**
		 * Check user permission to see whether or not they have access to the autoresponder
		 */
			$tempAPI = null;
			$tempCheckActions = array('view', 'copy', 'delete', 'edit', 'gethtml');
			$tempID = null;

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

			if (!is_null($tempID)) {
				$_GET['id'] = $tempID;
				$_POST['forms'] = $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 (!$popup && !$access) {
			$this->DenyAccess();
			return;
		}

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

		switch ($action) {
			case 'preview':
				$formapi = $this->GetApi();

				$design = (isset($_POST['FormDesign'])) ? $_POST['FormDesign'] : false;
				$formtype = (isset($_POST['FormType'])) ? $_POST['FormType'] : false;

				$chooseformat = (isset($_POST['SubscriberChooseFormat'])) ? $_POST['SubscriberChooseFormat'] : false;

				$changeformat = false;
				if ($formtype == 'm') {
					if (isset($_POST['SubscriberChangeFormat'])) {
						$changeformat = true;
					}
				}

				$lists = array();
				if (isset($_POST['IncludeLists'])) {
					$lists = $_POST['IncludeLists'];
				}
				if (!is_array($lists)) {
					$lists = array($lists);
				}
				$formapi->Set('lists', $lists);

				$field_order = array();
				if (isset($_POST['hidden_fieldorder'])) {
					$order = explode(';', $_POST['hidden_fieldorder']);
					foreach ($order as $order_pos => $order_field) {
						if (!$order_field) {
							continue;
						}
						$field_order[] = $order_field;
					}
				}

				$usecaptcha = false;
				if (isset($_POST['UseCaptcha']) && in_array($formtype, array('s', 'u', 'm'))) {
					$usecaptcha = true;
				}

				$formapi->Set('customfields', $field_order);

				$formapi->Set('design', $design);
				$formapi->Set('formtype', $formtype);
				$formapi->Set('chooseformat', $chooseformat);
				$formapi->Set('changeformat', $changeformat);
				$formapi->Set('usecaptcha', $usecaptcha);

				$html = $formapi->GetHTML(true);
				echo $html;
				exit();
			break;

			case 'gethtml':
				$this->GetFormHTML();
			break;

			case 'view':
				$this->PrintHeader(true);
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : false;

				$formapi = $this->GetApi();
				$loaded = $formapi->Load($id);

				if (!$id || !$loaded) {
					$GLOBALS['Error'] = GetLang('NoSuchForm');
					$html = $this->ParseTemplate('ErrorMsg', true, false);
				} else {
					// Log this to "User Activity Log"
					$logURL = SENDSTUDIO_APPLICATION_URL . '/admin/index.php?Page=' . __CLASS__ . '&Action=Edit&id=' . $_GET['id'];
					IEM::logUserActivity($logURL, 'images/forms_view.gif', $formapi->name);

					$formtype = $formapi->Get('formtype');
					// if it's a 'm'odify-details form or 'f'riend form,
					// get the user modified html instead of the built in html.
					if (in_array($formtype, array('m', 'f'))) {
						$html = $formapi->Get('formhtml');

					} else {
						$html = $formapi->GetHTML(true);
					
					}
				}
				header('Content-type: text/html; charset="' . SENDSTUDIO_CHARSET . '"');
				print '<html><head><meta http-equiv="Content-Type" content="text/html; charset='.SENDSTUDIO_CHARSET.'"></head><body>';
				echo $html;
				print '</body></html>';
				exit();
			break;

			case 'copy':
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$api = $this->GetApi();
				$result = $api->Copy($id);
				if (!$result) {
					$GLOBALS['Error'] = GetLang('FormCopyFail');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				} else {
					$GLOBALS['Message'] = $this->PrintSuccess('FormCopySuccess');
				}
				$this->ManageForms();
			break;

			case 'delete':
				$formlist = (isset($_POST['forms'])) ? $_POST['forms'] : array();

				if (isset($_GET['id'])) {
					$formlist = $_GET['id'];
				}

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

				$formlist = array_map('intval', $formlist);

				$this->RemoveForms($formlist);
			break;

			case 'finish':
				$session_form = IEM::sessionGet('Form');

				if (!$session_form) {
					$this->ManageForms();
					break;
				}

				$errorpage = array();
				$errorpage['html'] = $_POST['errorhtml_html'];
				if ($_POST['userrorhtmlurl'] == '1') {
					$errorpage['url'] = $_POST['errorpageurl'];
				} else {
					$errorpage['url'] = 'http://';
				}

				foreach (array('ThanksPage', 'ErrorPage', 'ConfirmPage') as $p => $pagename) {
					if (!isset($session_form['Pages'][$pagename])) {
						$session_form['Pages'][$pagename] = array();
					}
				}

				$formapi = $this->GetApi();

				if (isset($session_form['FormID']) && $session_form['FormID'] > 0) {
					$formapi->Load($session_form['FormID']);

					/**
					* If the email text for the confirm page is empty, most likely we've changed the form from requiring a confirmation to not requiring one.
					* In that case, we'll get what the page was before so we can at least fill it in if the form is changed back.
					*/
					if (empty($session_form['Pages']['ConfirmPage']['emailtext'])) {
						$confirm_page = $formapi->GetPage('ConfirmPage');

						foreach (array('html', 'url', 'sendfromname', 'sendfromemail', 'replytoemail', 'bounceemail', 'emailsubject', 'emailhtml', 'emailtext') as $k => $area) {
							$session_form['Pages']['ConfirmPage'][$area] = $confirm_page[$area];
						}
					}

					/**
					* We then do the same for the thanks page.
					*/
					if (empty($session_form['Pages']['ThanksPage']['emailtext'])) {
						$thanks_page = $formapi->GetPage('ThanksPage');

						foreach (array('sendfromname', 'sendfromemail', 'replytoemail', 'bounceemail', 'emailsubject', 'emailhtml', 'emailtext') as $k => $area) {
							$session_form['Pages']['ThanksPage'][$area] = $thanks_page[$area];
						}
					}
				}

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

				$session_form['Pages']['ErrorPage'] = $errorpage;

				$formapi->Set('formtype', $session_form['FormType']);
				$formapi->Set('pages', $session_form['Pages']);
				$formapi->Set('lists', $session_form['IncludeLists']);
				$formapi->Set('customfields', $session_form['CustomFields']);
				$formapi->Set('name', $session_form['FormName']);
				$formapi->Set('design', $session_form['FormDesign']);
				$formapi->Set('chooseformat', $session_form['SubscriberChooseFormat']);
				$formapi->Set('changeformat', $session_form['SubscriberChangeFormat']);

				$formapi->Set('requireconfirm', $session_form['RequireConfirmation']);
				$formapi->Set('sendthanks', $session_form['SendThanks']);

				$formapi->Set('fieldorder', $session_form['CustomFieldsOrder']);

				$formapi->Set('contactform', $session_form['ContactForm']);

				$formapi->Set('usecaptcha', $session_form['UseCaptcha']);

				$formapi->Set('formhtml', $formhtml);

				if (isset($session_form['FormID']) && $session_form['FormID'] > 0) {
					$result = $formapi->Save();

					if (!$result) {
						$GLOBALS['Error'] = GetLang('UnableToUpdateForm');
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					} else {
						$GLOBALS['Message'] = $this->PrintSuccess('FormUpdated');
					}
				} else {
					$formapi->ownerid = $user->userid;
					$result = $formapi->Create();

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

				if (in_array($formapi->formtype, array('s', 'u'))) {
					$this->GetFormHTML($formapi);
				} else {
					$this->ManageForms();
				}
			break;

			case 'step5':
				$session_form = IEM::sessionGet('Form');
				$sendfriendsettings = array();
				$sendfriendsettings['emailhtml'] = $_POST['myDevEditControl_html'];
				$sendfriendsettings['emailtext'] = $_POST['TextContent'];

				$thankssettings = array();
				$thankssettings['html'] = $_POST['thankspage_html_html'];
				$thankssettings['url'] = $_POST['thankspageurl'];

				$session_form['Pages']['SendFriendPage'] = $sendfriendsettings;
				$session_form['Pages']['ThanksPage'] = $thankssettings;
				IEM::sessionSet('Form', $session_form);

				$this->ShowFinalStep();
			break;

			case 'step4':
				$session_form = IEM::sessionGet('Form');
				$thankssettings = array();
				if ($session_form['SendThanks']) {
					$thankssettings['sendfromname'] = $_POST['sendfromname'];
					$thankssettings['sendfromemail'] = $_POST['sendfromemail'];
					$thankssettings['replytoemail'] = $_POST['replytoemail'];
					$thankssettings['bounceemail'] = $_POST['bounceemail'];
					$thankssettings['emailsubject'] = $_POST['thankssubject'];
					$thankssettings['emailhtml'] = $_POST['thanksemail_html_html'];
					$thankssettings['emailtext'] = $_POST['TextContent'];
				}

				$thankssettings['html'] = $_POST['thankspage_html_html'];
				if ($_POST['usethankspageurl'] == '1') {
					$thankssettings['url'] = $_POST['thankspageurl'];
				} else {
					$thankssettings['url'] = 'http://';
				}

				$session_form['Pages']['ThanksPage'] = $thankssettings;
				IEM::sessionSet('Form', $session_form);

				$this->ShowFinalStep();
			break;

			case 'step3':
				$session_form = IEM::sessionGet('Form');
				$confirmsettings = array();
				$confirmsettings['html'] = $_POST['confirmhtml_html'];
				if ($_POST['useconfirmpageurl'] == '1') {
					$confirmsettings['url'] = $_POST['confirmpageurl'];
				} else {
					$confirmsettings['url'] = 'http://';
				}
				$confirmsettings['sendfromname'] = $_POST['sendfromname'];
				$confirmsettings['sendfromemail'] = $_POST['sendfromemail'];
				$confirmsettings['replytoemail'] = $_POST['replytoemail'];
				$confirmsettings['bounceemail'] = $_POST['bounceemail'];
				$confirmsettings['emailsubject'] = $_POST['confirmsubject'];
				$confirmsettings['emailhtml'] = $_POST['confirmemail_html_html'];
				$confirmsettings['emailtext'] = $_POST['TextContent'];

				$session_form['Pages']['ConfirmPage'] = $confirmsettings;
				IEM::sessionSet('Form', $session_form);

				if ($session_form['SendThanks']) {
					$this->ShowThanksStep();
				}

				$this->ShowThanksHTML();

			break;

			case 'step2':
				$session_form = array();

				$optional_fields = array();

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

					$session_form['ContactForm'] = false;
					$session_form['UseCaptcha'] = false;

					switch ($formtype) {
						case 'u':
							$checkfields = array('FormName', 'FormDesign', 'FormType', 'IncludeLists');
							$optional_fields = array('RequireConfirmation', 'SendThanks', 'UseCaptcha');
							$session_form['SubscriberChangeFormat'] = false;
							$session_form['SubscriberChooseFormat'] = '';
						break;

						case 'm':
							$session_form['RequireConfirmation'] = false;
							$session_form['SendThanks'] = false;
							$checkfields = array('FormName', 'FormDesign', 'FormType', 'IncludeLists');
							$optional_fields = array('SubscriberChangeFormat', 'UseCaptcha');
							$session_form['SubscriberChooseFormat'] = '';
						break;

						case 'f':
							$session_form['RequireConfirmation'] = false;
							$session_form['SendThanks'] = false;
							$session_form['IncludeLists'] = array();
							$session_form['SubscriberChangeFormat'] = false;
							$session_form['SubscriberChooseFormat'] = '';

							$checkfields = array('FormName', 'FormDesign', 'FormType');
						break;

						default:
							$session_form['SubscriberChangeFormat'] = false;
							$optional_fields = array('ContactForm', 'RequireConfirmation', 'SendThanks', 'UseCaptcha');
							$checkfields = array('FormName', 'FormDesign', 'FormType', 'SubscriberChooseFormat', 'IncludeLists');
					}
				}

				$valid = true; $errors = array();
				foreach ($checkfields as $p => $field) {
					if (!isset($_POST[$field])) {
						$valid = false;
						$errors[] = GetLang('Form'.$field.'IsNotValid');
						break;
					}
					if (!is_array($_POST[$field])) {
						if ($_POST[$field] == '') {
							$valid = false;
							$errors[] = GetLang('Form'.$field.'IsNotValid');
							break;
						} else {
							$value = $_POST[$field];
							$session_form[$field] = $value;
						}
					} else {
						if (empty($_POST[$field])) {
							$valid = false;
							$errors[] = GetLang('Form'.$field.'IsNotValid');
							break;
						} else {
							$session_form[$field] = $_POST[$field];
						}
					}
				}

				foreach ($optional_fields as $p => $field) {
					if (isset($_POST[$field])) {
						$session_form[$field] = $_POST[$field];
					} else {
						$session_form[$field] = false;
					}
				}

				if (isset($_GET['id'])) {
					$session_form['FormID'] = (int)$_GET['id'];
				}

				if (!$valid) {
					if (!isset($session_form['FormID'])) {
						$id = 0;
						$GLOBALS['Error'] = GetLang('UnableToCreateForm') . '<br/>- ' . implode('<br/>- ',$errors);
					} else {
						$id = $session_form['FormID'];
						$GLOBALS['Error'] = GetLang('UnableToUpdateForm') . '<br/>- ' . implode('<br/>- ',$errors);
					}
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->Form_Step1($id);
					break;
				}

				$session_form['CustomFieldsOrder'] = array();
				if (isset($_POST['hidden_fieldorder'])) {
					$order = explode(';', $_POST['hidden_fieldorder']);
					foreach ($order as $order_pos => $order_field) {
						if (!$order_field) {
							continue;
						}
						$session_form['CustomFieldsOrder'][] = $order_field;
					}
				}

				$session_form['CustomFields'] = array();

				$ftypes = array('s','m');
				if (in_array($session_form['FormType'], $ftypes)) {
					foreach ($session_form['CustomFieldsOrder'] as $each) {
						if (is_numeric($each)) {
							array_push($session_form['CustomFields'], $each);
						}
					}
				}

				IEM::sessionSet('Form', $session_form);

				if ($session_form['FormType'] == 'f') {
					$this->ShowFriendStep();
					$this->ShowThanksHTML('Step5');
					break;
				}

				if ($session_form['RequireConfirmation'] == '1') {
					$this->ShowConfirmationStep();
					break;
				}

				if ($session_form['SendThanks'] == '1') {
					$this->ShowThanksStep();
				}

				if (isset($session_form['FormID']) && $session_form['FormID'] > 0) {
					$GLOBALS['CancelButton'] = GetLang('EditFormCancelButton');
					$GLOBALS['Heading'] = GetLang('EditForm');
					$GLOBALS['Intro'] = GetLang('ThanksPageIntro_Edit');
					if ($session_form['FormType'] == 'm' || $session_form['SendThanks'] != 1) {
						$GLOBALS['Intro'] = GetLang('ThanksPageIntro_Edit_NoEmail');
					}
				} else {
					$GLOBALS['CancelButton'] = GetLang('CreateFormCancelButton');
					$GLOBALS['Heading'] = GetLang('CreateForm');
					$GLOBALS['Intro'] = GetLang('ThanksPageIntro');
					if ($session_form['FormType'] == 'm' || $session_form['SendThanks'] != 1) {
						$GLOBALS['Intro'] = GetLang('ThanksPageIntro_NoEmail');
					}
				}

				$this->ShowThanksHTML();
			break;

			case 'edit':
				IEM::sessionRemove('Form');
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$this->Form_Step1($id);
			break;

			case 'create':
				IEM::sessionRemove('Form');
				$this->Form_Step1();
			break;

			default:
				$this->ManageForms();
		}

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

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

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

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

		header('Content-type: text/javascript');
		
		die($output);
	}
Beispiel #19
0
	/**
	 * CreateBackup
	 * @return Void Returns nothing
	 */
	function CreateBackup()
	{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			$this->PrintFooter(true);

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

			$tableProcessed++;

			break;
		}

		IEM::sessionSet('DatabaseTables_Done', $tables_done);
		IEM::sessionSet('DatabaseTables_BackupErrors', $backup_errors);
		?>
			<script>
				setTimeout('window.location="index.php?Page=Upgrade&Action=CreateBackup"', 1);
			</script>
		<?php
	}
 /**
  * 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;
 }
	/**
	* Process
	* Works out what you're trying to do and takes appropriate action. Validates data where needed.
	*
	* @param String $action Action to perform. This is usually 'step1', 'step2', 'step3' etc. This gets passed in by the Subscribers::Process function.
	*
	* @see Subscribers::Process
	* @see GetApi
	* @see Subscribers_API::IsSubscriberOnList
	* @see Subscribers_API::AddToList
	* @see Subscribers_API::SaveSubscriberCustomField
	* @see Lists_API::GetCustomFields
	* @see CustomFields_API::IsRequired
	* @see CustomFields_API::ValidData
	* @see CustomFields_API::GetFieldName
	* @see AddSubscriber_Step2
	*
	* @return Void Prints out the step, doesn't return anything.
	*/
	function Process($action=null)
	{

		switch (strtolower($action)) {
			case 'step2':
				$listid = (isset($_POST['list'])) ? (int)$_POST['list'] : $_GET['list'];
				$this->AddSubscriber_Step2($listid);
			break;

			case 'saveadd':
			case 'save':
				$user = GetUser();

				$listid = (isset($_GET['list'])) ? (int)$_GET['list'] : 0;

				if (!$user->HasAccess('Subscribers', 'Add')) {
					$this->DenyAccess();
					return;
				}

				$user_lists = $user->GetLists();

				/**
				 * Check if user have access to the list
				 */
					if (!array($user_lists) || empty($user_lists)) {
						$this->DenyAccess();
						return;
					}

					$temp = array_keys($user_lists);
					if (!in_array($listid, $temp)) {
						$this->DenyAccess();
						return;
					}
				/**
				 * -----
				 */

				$subscriber = $this->GetApi('Subscribers');

				$email = IEM::requestGetPOST('emailaddress', '', 'trim');
				if (empty($email) || !$subscriber->ValidEmail($email)) {
					$GLOBALS['Error'] = sprintf(GetLang('SubscriberAddFail_InvalidEmailAddress'), htmlspecialchars($email));
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->AddSubscriber_Step2($listid);
					break;
				}

				$duplicate = $subscriber->IsSubscriberOnList($_POST['emailaddress'], $listid);

				if ($duplicate) {
					$unsubscribed_check = $subscriber->IsUnSubscriber(false, $listid, $duplicate);
					if ($unsubscribed_check) {
						$GLOBALS['Error'] = sprintf(GetLang('SubscriberAddFail_Unsubscribed'), $_POST['emailaddress']);
					} else {
						$GLOBALS['Error'] = sprintf(GetLang('SubscriberAddFail_Duplicate'), $_POST['emailaddress']);
					}
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->AddSubscriber_Step2($listid);
					break;
				}

				list($banned, $msg) = $subscriber->IsBannedSubscriber($_POST['emailaddress'], $listid, false);
				if ($banned) {
					$GLOBALS['Error'] = sprintf(GetLang('SubscriberAddFail_Banned'), $_POST['emailaddress']);
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->AddSubscriber_Step2($listid);
					break;
				}

				$ListApi = $this->GetApi('Lists');
				$ListApi->Load($listid);
				$ListCustomFields = $ListApi->GetCustomFields($listid);

				$customfield_errors = array();

				foreach (array('emailaddress', 'format', 'confirmed') as $p => $area) {
					$subscriber->Set($area, $_POST[$area]);
				}
				$CustomFieldsValid = true;
				foreach ($ListCustomFields as $pos => $data) {
					$CustomFieldApi = $this->GetApi('CustomFields');
					$fieldid = $data['fieldid'];
					$CustomFieldApi->Load($fieldid);
					$postdata = (isset($_POST['CustomFields'][$fieldid])) ? $_POST['CustomFields'][$fieldid] : '';

					if (!isset($_POST['CustomFields'][$fieldid]) && !$CustomFieldApi->IsRequired()) {
						unset($CustomFieldApi);
						continue;
					}

					if ($CustomFieldApi->IsRequired()) {
						if (!$postdata) {
							$ftype = $CustomFieldApi->Get('fieldtype');
							switch ($ftype) {
								case 'text':
								case 'number':
									$errormsg = 'SubscriberAddFail_EmptyData_EnterData';
								break;

								case 'dropdown':
								case 'radiobutton':
								case 'checkbox':
								case 'date':
									$errormsg = 'SubscriberAddFail_EmptyData_ChooseOption';
								break;
							}

							$customfield_errors[] = sprintf(GetLang($errormsg), $CustomFieldApi->GetFieldName());

							unset($CustomFieldApi);

							continue;
						}
					}

					if (!$CustomFieldApi->ValidData($postdata)) {
						$customfield_errors[] = sprintf(GetLang('SubscriberAddFail_InvalidData'), $CustomFieldApi->GetFieldName());

						unset($CustomFieldApi);
						continue;
					}
					unset($CustomFieldApi);
				}

				if (!empty($customfield_errors)) {
					$GLOBALS['Error'] = implode('<br/>', $customfield_errors);
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->AddSubscriber_Step2($listid);
					break;
				}

				$subscriberid = $subscriber->AddToList($_POST['emailaddress'], $listid);
				$GLOBALS['Message'] = $this->PrintSuccess('SubscriberAddSuccessful');
				$GLOBALS['list'] = $listid;

				// go through each custom field and save the info.
				foreach ($ListCustomFields as $pos => $data) {
					$fieldid = $data['fieldid'];
					$postdata = (isset($_POST['CustomFields'][$fieldid])) ? $_POST['CustomFields'][$fieldid] : '';
					$subscriber->SaveSubscriberCustomField($subscriberid, $fieldid, $postdata);
				}

				if ($action == 'saveadd' || sizeof($user_lists) == 1) {
					$this->AddSubscriber_Step2($listid, true);
				} else {
					IEM::sessionSet('AddSubscriberMessage', $ListApi->Get('name'));
					?>
					<script>
						window.location = 'index.php?Page=Subscribers&Action=Add';
					</script>
					<?php
					exit();
				}
			break;

			default:
				$user = GetUser();
				$lists = $user->GetLists();

				// If only one list available, go directly to step 2
				if (count($lists) == 1) {
					$listid = array_pop(array_keys($lists));
					$this->AddSubscriber_Step2($listid);
				} else {
					$this->ChooseList('add', 'step2');
				}
			break;
		}
	}
Beispiel #22
0
	/**
	* ExportSubscribers_Step4
	* Prints out the export header (if required) and creates the export file. This is the last step before exports happen.
	*
	* @see GetApi
	* @see CustomFields_API::Load
	* @see CustomFields_API::GetFieldName
	*
	* @return Void Prints out the form, doesn't return anything.
	*/
	function ExportSubscribers_Step4()
	{
		$exportinfo = IEM::sessionGet('ExportInfo');

		$exportsettings = array();
		$exportsettings['Headers'] = $_POST['includeheader'];
		$exportsettings['FieldSeparator'] = $_POST['fieldseparator'];
		$exportsettings['FieldEnclosedBy'] = $_POST['fieldenclosedby'];
		$exportsettings['FieldOptions'] = $_POST['fieldoption'];
		$exportsettings['FileType'] = trim($_POST['filetype']);

		if (!in_array($exportsettings['FileType'], array('csv', 'xml'))) {
			$exportsettings['FileType'] = 'csv';
		}

		$exportinfo['ExportFile'] = 'export-'. md5(uniqid(rand(), true) . SENDSTUDIO_LICENSEKEY) . '.' . $exportsettings['FileType'];
		touch(TEMP_DIRECTORY . '/' . $exportinfo['ExportFile']);
		chmod(TEMP_DIRECTORY . '/' . $exportinfo['ExportFile'], 0644);

		$exportinfo['Settings'] = $exportsettings;
		IEM::sessionSet('ExportInfo', $exportinfo);

		$queuesize = $exportinfo['QueueSize'];

		if ($queuesize == 1) {
			$GLOBALS['SubscribersReport'] = GetLang('ExportSummary_FoundOne');
		} else {
			$GLOBALS['SubscribersReport'] = sprintf(GetLang('ExportSummary_FoundMany'), $this->FormatNumber($queuesize));
		}

		$exportfile = $exportinfo['ExportFile'];

		if (is_file(TEMP_DIRECTORY . '/'. $exportinfo['ExportFile'])) {
			unlink(TEMP_DIRECTORY . '/'. $exportinfo['ExportFile']);
		}

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

		if ($exportsettings['Headers']) {
			$parts = array();
			foreach ($exportsettings['FieldOptions'] as $pos => $type) {
				switch (strtolower($type)) {
					case 'n':
						continue;
					break;
					case 'e':
						$parts[] = GetLang('EmailAddress');
					break;
					case 'f':
						$parts[] = GetLang('Format');
					break;
					case 'c':
						$parts[] = GetLang('Confirmed');
					break;
					case 'dmy':
						$parts[] = GetLang('SubscribeDate_DMY');
					break;
					case 'mdy':
						$parts[] = GetLang('SubscribeDate_MDY');
					break;
					case 'ymd':
						$parts[] = GetLang('SubscribeDate_YMD');
					break;
					case 'i':
						$parts[] = GetLang('SubscriberIPAddress');
					break;
					case 'btime':
						$parts[] = GetLang('SubscriberBounceTime');
					break;
					case 'btype':
						$parts[] = GetLang('SubscriberBounceType');
					break;

					default:
						if (is_numeric($type)) {
							$customfields_Api->Load($type);
							$parts[] = $customfields_Api->GetFieldName();
						}
				}
			}

			switch($exportsettings['FileType']) {
				case 'xml':
					$line = '<?xml version="1.0" encoding="UTF-8"?>'."\n".
							'<export>'."\n".
							"\t".'<version>'.IEM::VERSION.'</version>'."\n".
							"\t".'<type>subscribers</type>'."\n".
							"\t".'<fields>'."\n";

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

					$line .= "\t".'</fields>'."\n";
				break;

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

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

			$fp = fopen(TEMP_DIRECTORY . '/' . $exportinfo['ExportFile'], 'a');
			fputs($fp, $line, strlen($line));
			fclose($fp);
		}

		$this->ParseTemplate('Subscribers_Export_Step4');
	}
 /**
  * Show_Send_Step_30
  * This shows a summary report of the split test campaign
  * after a user has paused the campaign
  * and they want to resume sending it
  *
  * It shows:
  * - which lists/segments it will be sent to
  * - the split test name
  * - which campaigns it will send
  *
  * and a "resume" button.
  *
  * If cron is enabled, then it will mark the job as "waiting" to send again in the database,
  * set a flash message and redirect the user back to the "manage split tests" page.
  *
  * @uses GetApi
  * @uses Splittest_API::Load
  * @uses Jobs_API::LoadJob
  * @uses CheckCronEnabled
  * @uses Splittest_Send_API::ResumeJob
  */
 public function Show_Send_Step_30()
 {
     $splitid = 0;
     if (isset($_GET['id'])) {
         $splitid = (int) $_GET['id'];
     }
     $api = $this->GetApi();
     $split_campaign_details = $api->Load($splitid);
     if (empty($split_campaign_details)) {
         FlashMessage(GetLang('Addon_splittest_Send_InvalidSplitTest'), SS_FLASH_MSG_ERROR, $this->admin_url);
         return;
     }
     $jobid = 0;
     if (isset($split_campaign_details['jobid'])) {
         $jobid = (int) $split_campaign_details['jobid'];
     }
     require_once SENDSTUDIO_API_DIRECTORY . '/jobs.php';
     $jobApi = new Jobs_API();
     $job = $jobApi->LoadJob($jobid);
     if (empty($job)) {
         FlashMessage(GetLang('Addon_splittest_Send_InvalidSplitTest'), SS_FLASH_MSG_ERROR, $this->admin_url);
         return;
     }
     /**
      * If we're sending via cron,
      * then mark the job as "waiting" to send again
      * and then show an appropriate message.
      */
     if (self::CheckCronEnabled()) {
         $send_api = $this->GetApi('SplitTest_Send');
         $resumed = $send_api->ResumeJob($jobid, $splitid);
         if ($resumed) {
             FlashMessage(GetLang('Addon_splittest_Send_Resumed_Success'), SS_FLASH_MSG_SUCCESS, $this->admin_url);
         } else {
             FlashMessage(GetLang('Addon_splittest_Send_Resumed_Failure'), SS_FLASH_MSG_ERROR, $this->admin_url);
         }
         return;
     }
     $sendingCampaigns = array();
     $send_details['newsletters'] = array();
     foreach ($split_campaign_details['splittest_campaigns'] as $campaignid => $campaignname) {
         $sendingCampaigns[$campaignid] = htmlspecialchars($campaignname, ENT_QUOTES, SENDSTUDIO_CHARSET);
         $send_details['newsletters'][] = $campaignid;
     }
     $send_list = array();
     switch ($job['jobdetails']['sendingto']['sendtype']) {
         case 'list':
             require_once SENDSTUDIO_API_DIRECTORY . '/lists.php';
             $list_api = new Lists_API();
             foreach ($job['jobdetails']['sendingto']['sendids'] as $listid) {
                 $list_api->Load($listid);
                 $send_list[] = htmlspecialchars($list_api->Get('name'), ENT_QUOTES, SENDSTUDIO_CHARSET);
             }
             $this->template_system->Assign('SendingToLists', true);
             break;
         case 'segment':
             require_once SENDSTUDIO_API_DIRECTORY . '/segment.php';
             $segment_api = new Segment_API();
             foreach ($job['jobdetails']['sendingto']['sendids'] as $segmentid) {
                 $segment_api->Load($segmentid);
                 $send_list[] = htmlspecialchars($segment_api->Get('segmentname'), ENT_QUOTES, SENDSTUDIO_CHARSET);
             }
             $this->template_system->Assign('SendingToSegments', true);
             break;
     }
     /**
      * Set everything in the session ready to go.
      */
     $job['jobdetails']['Job'] = $job['jobid'];
     IEM::sessionSet('SplitTestSendDetails', $job['jobdetails']);
     /**
      * Work out how many more emails there are to send.
      */
     $send_size = $job['jobdetails']['sendinfo']['sendsize_left'];
     if ($send_size == 1) {
         $send_size_msg = GetLang('Addon_splittest_Send_Step3_Size_One');
     } else {
         $send_size_msg = sprintf(GetLang('Addon_splittest_Send_Step3_Size_Many'), $this->PrintNumber($send_size));
     }
     $this->template_system->Assign('SendingToNumberOfContacts', $send_size_msg);
     $this->template_system->Assign('sendingCampaigns', $sendingCampaigns);
     $this->template_system->Assign('sendLists', $send_list);
     $this->template_system->Assign('AdminUrl', $this->admin_url, false);
     $this->template_system->ParseTemplate('send_step3');
 }
Beispiel #24
0
	/**
	* SetSecret
	*
	* Sets the session variable to the current secret code
	*
	* @return unknown
	*/
	function SetSecret()
	{
		IEM::sessionRemove('CaptchaCode');

		$new_code = $this->GetSecret();

		// set new secret to the session
		IEM::sessionSet('CaptchaCode', $new_code);
	}
	/**
	 * _SaveCustomFields
	 * Loops through the imported custom fields for a subscribers and saves them.
	 *
	 * @param Object $SubscriberApi The Subscriber API with the existing subscriber details loaded.
	 * @param Int $subscriberid The ID of the existing or new subscriber.
	 * @param Array $customfields An array of imported custom field IDs and values.
	 * @param String $email The email address trying to be imported.
	 * @param Array $importresults The running tally of import results.
	 *
	 * @uses Subscribers_API::SaveSubscriberCustomField
	 *
	 * @return Boolean True if the custom field settings were saved succesfully, otherwise false.
	 */
	function _SaveCustomFields($SubscriberApi, $subscriberid, $customfields, $email, $importresults)
	{
		$info = '';
		foreach ($customfields as $fieldid => $fielddata) {
			if (!$SubscriberApi->SaveSubscriberCustomField($subscriberid, $fieldid, $fielddata)) {
				// This fix is for PostgreSQL (see bugid:2548).
				// If saving here failed it probably means the character set data is invalid for
				// the database. This also means we may not be able to successfully output the
				// bad data in the 'more information' box, so we'll just use the email address to
				// identify the record.
				$subf = $this->_customfields_loaded[$fieldid];
				$info .= $email . ' ' . sprintf(GetLang('InvalidCustomFieldData'), $subf->GetFieldName());
				$importresults['bads']++;
				$importresults['baddata'][] = $info;
				IEM::sessionSet('ImportResults', $importresults);
				return false;
			}
		}
		return true;
	}
Beispiel #26
0
	/**
	 * TestBounceSettingsDisplay
	 * This sets session variables for showing the 'test bounce account' details
	 * It then passes control to the 'TestBounceSettings' method which actually tests the details.
	 *
	 * @see TestBounceSettings
	 *
	 * @return Void Doesn't return anything. Sets session variables then prints the window which actually tests the account details.
	 */
	function TestBounceSettingsDisplay()
	{
		$test_bounce_details = array (
			'server' => $_GET['Bounce_Server'],
			'username' => $_GET['Bounce_Username'],
			'password' => base64_encode($_GET['Bounce_Password']),
			'extra_settings' => $_GET['Bounce_ExtraSettings'],
			'imap' => (isset($_GET['bounce_imap']) && $_GET['bounce_imap'] == 1) ? 1 : 0,
		);
		IEM::sessionSet('TestBounceDetails', $test_bounce_details);

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

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

		$this->DisplayCronWarning();

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

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

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

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

		} else {

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

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

		$GLOBALS['PreviewID'] = $autoresponderid;

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

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

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

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

		$session_autoresponder['contents'] = $autorespondercontents;

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

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

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

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

		$tpl->ParseTemplate('Autoresponder_Form_Step4');
	}
	/**
	 * GetNextUpgrade
	 * @return String Returns TRUE if successful, FALSE otherwise
	 */
	function GetNextUpgrade()
	{
		$upgrades_done = IEM::sessionGet('DatabaseUpgradesCompleted');

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

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

		$versions = array_keys($upgrades_todo);

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

		$version = $versions[0];

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

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

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

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

			$version = $versions[0];

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

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

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

		require_once($file);

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

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

        $user = GetUser();

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

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

        $tpl = GetTemplateSystem();


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

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

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

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

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

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

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

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

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

        $tpl->ParseTemplate('Newsletter_Form_Step2');
    }
Beispiel #30
0
 /**
  * Admin_Action_Finished
  * This is the final status report.
  *
  * @see Admin_Action_Default
  * @see Admin_Action_ShowPopup
  *
  * @return Void Prints out the report, doesn't return anything.
  */
 public function Admin_Action_Finished()
 {
     $repaired = (bool) $this->_getGETRequest('Repair', false);
     $tables_status = IEM::sessionGet($this->addon_id . '_TablesStatus');
     list($num_problems, $problem_tables, $problems) = $this->SummariseProblems($tables_status);
     if ($repaired) {
         FlashMessage(GetLang('Addon_dbcheck_Repaired'), SS_FLASH_MSG_SUCCESS);
     } elseif ($num_problems) {
         $error_msg = sprintf(GetLang('Addon_dbcheck_Problems'), $num_problems);
         FlashMessage($error_msg, SS_FLASH_MSG_ERROR);
     } else {
         FlashMessage(GetLang('Addon_dbcheck_NoProblems'), SS_FLASH_MSG_SUCCESS);
     }
     $report = self::GenerateReport($tables_status);
     IEM::sessionSet($this->addon_id . '_TablesReport', $report);
     IEM::sessionSet($this->addon_id . '_TablesToCheck', $problem_tables);
     IEM::sessionSet($this->addon_id . '_StepNumber', 1);
     IEM::sessionSet($this->addon_id . '_TotalSteps', count($problem_tables));
     $flash_messages = GetFlashMessages();
     $this->template_system->Assign('repaired', $repaired);
     $this->template_system->Assign('problems', $problems);
     $this->template_system->Assign('num_problems', $num_problems);
     $this->template_system->Assign('admin_url', $this->admin_url);
     $this->template_system->Assign('report', $report);
     $this->template_system->Assign('flash_messages', $flash_messages);
     $this->template_system->ParseTemplate('final_report');
 }