Пример #1
0
/**
 * CheckCronSchedule
 *
 * Checks whether a jobtype is allowed to run or not based on the settings saved by the admin user.
 * The settings api is loaded and checked to make sure
 * - the jobtype is valid (ie you are not making up a new 'jobtype')
 * - that it is time to run the job
 *
 * If it is time to run the job, then update the time that the job was last run so it can be checked again in the future.
 *
 * @param String $jobtype The type of job that we are checking
 *
 * @see Settings_API
 * @see Settings_API::Schedule
 * @see Settings_API::SetRunTime
 *
 * @return boolean Returns FALSE if the jobtype is invalid or it is not yet time to run, TRUE otherwise
 */
function CheckCronSchedule($jobtype = 'send')
{
    if (!class_exists('settings_api', false)) {
        require_once SENDSTUDIO_API_DIRECTORY . '/settings.php';
    }
    $settings_api = new Settings_API();
    $settings_api->Load();
    /**
     * Check we're looking for a valid type of job.
     * If we're not, return false and don't allow it to be run.
     */
    $scheduled_events = $settings_api->Get('Schedule');
    $allowed_jobtypes = array_keys($scheduled_events);
    if (!in_array($jobtype, $allowed_jobtypes)) {
        unset($settings_api);
        return false;
    }
    /**
     * By default, we don't allow sending to occur.
     */
    $allow_job = false;
    $last_send_time = $scheduled_events[$jobtype]['lastrun'];
    $next_send_time = 0;
    $option_name = 'SENDSTUDIO_CRON_' . strtoupper($jobtype);
    /**
     * Check the variable exists and is defined.
     * An addon could be in the 'schedule' array but not set up yet.
     * If that's the case, it can't be allowed to run.
     */
    if (!defined($option_name)) {
        unset($settings_api);
        return false;
    }
    $ss_jobtype = constant($option_name);
    /**
     * If the job is disabled, then don't run it.
     * It is possible for  triggeremails_p to hold 0 value, so exempt this particular job and continue with the process.
     */
    if ($ss_jobtype == 0 && $jobtype != 'triggeremails_p') {
        unset($settings_api);
        return false;
    }
    /**
     * if last_send_time is less than 0, we have not sent before.
     * If it's greater than 0, then we have sent before and we need to check the frequency.
     */
    if ($last_send_time > 0) {
        $next_send_time = $last_send_time + $ss_jobtype * 60 - 5;
    }
    $server_time = time();
    if ($server_time >= $next_send_time) {
        $allow_job = true;
        // Force triggeremails_p to run early in the morning around 12 AM.
        // Once forced, it will move the schedule to around 12 AM.
        // It does not really matter if the processing is run more than once in 24 hours period.
        // The only concern at the moment is that the process may take quite some time to complete.
    } elseif ($jobtype == 'triggeremails_p') {
        $early_morning = mktime(0, 0, 0, date('n'), date('j'), date('Y'));
        // if CRON have NOT been executed for 'triggeremails_p' today, then allow the job.
        if ($last_send_time < $early_morning) {
            $allow_job = true;
        }
    }
    if ($allow_job) {
        /**
         * Set the last run time to now so next time it runs it's remembered properly.
         */
        $settings_api->SetRunTime($jobtype);
    }
    unset($settings_api);
    return $allow_job;
}
	/**
	* InsertChartImage
	* Sets the variables to display a statistics chart
	*
	* @param String $chartname The variable name for the chart
	* @param String $data_url The URL the chart should get data from
	* @param Array $settings An array of settings for the chart
	*
	* @return Void Returns nothing, sets the variables for displaying the chart
	*/
	function InsertChartImage($chartname,$data_url,$settings = null)
	{
		$params = array();
		if (is_array($settings)) {
			foreach ($settings as $key => $val) {
				$params[] = urlencode($key) . "=" . urlencode($val);
			}
		}
		$params = implode('&amp;',$params);

		if (Settings_API::GDEnabled()) {
			$GLOBALS[$chartname] = '<img src="' . $data_url . ( $params ? '&amp;' . $params : '') . '&amp;GetAsImg=1" style="display: block;">';
		} else {
			$GLOBALS[$chartname] = '<p>(' . GetLang('GD_Not_Enabled') . ')</p>';
		}
	}
Пример #3
0
	/**
	* Process
	* Does all the work.
	* Saves settings, Checks details, calls the API to save the actual settings and checks whether it worked or not.
	*
	* @see GetApi
	* @see API::Set
	* @see API::Save
	* @see GetLang
	* @see ParseTemplate
	* @see SendStudio_Functions::Process
	* @see SendTestPreview
	* @see Settings_API::CheckCron
	* @see Settings_API::UpdateCron
	*
	* @return Void Does all of the processing, doesn't return anything.
	*/
	function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : null;

		$user = GetUser();
		$access = $user->HasAccess('System', 'System');

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

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

		$LK = false;


		switch ($action) {
			case 'addons':

				// we need a subaction & addon name.
				if (!isset($_GET['SubAction'])) {
					return $this->ShowSettingsPage();
				}

				if (!isset($_GET['Addon'])) {
					return $this->ShowSettingsPage();
				}

				require_once(SENDSTUDIO_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR . 'interspire_addons.php');

				$post = array();
				if (!empty($_POST)) {
					$post = $_POST;
				}

				try {
					$allowed_sub_action = array('install', 'uninstall', 'enable', 'disable', 'upgrade', 'configure', 'savesettings');
					$subaction = $this->_getGETRequest('SubAction', '');

					if (!in_array(strtolower($subaction), $allowed_sub_action)) {
						FlashMessage(GetLang('Addon_Action_NotAllowed'), SS_FLASH_MSG_ERROR, 'index.php?Page=Settings&Tab=6');
						return;
					}

					$result = Interspire_Addons::Process($_GET['Addon'], $subaction, $post);
					if ($result === true) {
						FlashMessage(GetLang('Addon_Success_' . strtolower($_GET['SubAction'])), SS_FLASH_MSG_SUCCESS, 'index.php?Page=Settings&Tab=6');
						return;
					}
					if ($result === false || $result == null) {
						FlashMessage(GetLang('Addon_Failure_' . strtolower($_GET['SubAction'])), SS_FLASH_MSG_ERROR, 'index.php?Page=Settings&Tab=6');
						return;
					}
					echo $result;
				} catch (Exception $e) {
					$error = $e->GetMessage();
					FlashMessage($error, SS_FLASH_MSG_ERROR, 'index.php?Page=Settings&Tab=6');
				}
				return;
			break;

			case 'viewdisabled':
				$this->PrintHeader(true);
				$reporttype = (isset($_GET['Report'])) ? $_GET['Report'] : null;
				switch ($reporttype) {
					case 'autoresponder':
						$GLOBALS['Heading'] = GetLang('Autoresponders_Disabled_Heading');
						$GLOBALS['Intro'] = GetLang('Autoresponders_Disabled_Heading_Intro');

						$disabled_list = IEM::sessionGet('AutorespondersDisabled');

						$disabled_report = '';
						$var = GetLang('DisabledAutoresponder_Item');
						foreach ($disabled_list as $p => $details) {
							$disabled_report .= sprintf($var, $details['autorespondername'], $details['listname']) . "\n";
						}
					break;

					case 'newsletter':
						$GLOBALS['Heading'] = GetLang('Newsletters_Disabled_Heading');
						$GLOBALS['Intro'] = GetLang('Newsletters_Disabled_Heading_Intro');

						$disabled_list = IEM::sessionGet('NewslettersDisabled');

						$disabled_report = '';
						$var = GetLang('DisabledNewsletter_Item');
						foreach ($disabled_list as $p => $details) {
							$disabled_report .= sprintf($var, $details['newslettername']) . "\n";
						}
					break;
				}
				$GLOBALS['DisabledList'] = $disabled_report;
				$this->ParseTemplate('Settings_Disabled_Report');
				$this->PrintFooter(true);
			break;

			case 'systeminfo':
				$this->PrintHeader();
				$db = IEM::getDatabase();
				$GLOBALS['DatabaseVersion'] = $db->FetchOne('SELECT version() AS version');

				$GLOBALS['ProductVersion'] = GetLang('SENDSTUDIO_VERSION');
				$GLOBALS['ShowProd'] = empty($GLOBALS['ProductEdition']) ? 'none' : '';
				$charset = (isset($SENDSTUDIO_DEFAULTCHARSET)) ? $SENDSTUDIO_DEFAULTCHARSET : SENDSTUDIO_CHARSET;
				$GLOBALS['DefaultCharset'] = $charset;
				$GLOBALS['CharsetDescription'] = GetLang($charset);
				$GLOBALS['ServerTimeZone'] = SENDSTUDIO_SERVERTIMEZONE;
				$GLOBALS['ServerTimeZoneDescription'] = GetLang(SENDSTUDIO_SERVERTIMEZONE);
				$GLOBALS['ServerTime'] = date('r');
				$GLOBALS['PHPVersion'] = phpversion();
				$GLOBALS['ServerSoftware'] = htmlspecialchars($_SERVER["SERVER_SOFTWARE"], ENT_QUOTES, SENDSTUDIO_CHARSET);

				$GLOBALS['SafeModeEnabled'] = (SENDSTUDIO_SAFE_MODE) ? GetLang('Yes') : GetLang('No');

				$GLOBALS['ImapSupportFound'] = (function_exists('imap_open')) ? GetLang('Yes') : GetLang('No');

				$GLOBALS['CurlSupportFound'] = (function_exists('curl_init')) ? GetLang('Yes') : GetLang('No');

				$php_mods = $this->ParsePHPModules();

				$GLOBALS['GDVersion'] = GetLang('GD_NotDetected');
				if (Settings_API::GDEnabled() && $php_mods !== false) {
					$GLOBALS['GDVersion'] = $php_mods['gd']['GD Version'];
				}

				$GLOBALS['ModSecurity'] = GetLang('ModSecurity_Unknown');

				if (!is_numeric(strpos(php_sapi_name(), 'cgi')) && $php_mods !== false) {
					$apache_mods = $this->ParseApacheModules($php_mods);
					if (in_array('mod_security', $apache_mods)) {
						$GLOBALS['ModSecurity'] = GetLang('Yes');
					} else {
						$GLOBALS['ModSecurity'] = GetLang('No');
					}
				}
				$this->ParseTemplate('Settings_SystemInfo');
				$this->PrintFooter();
			break;

			case 'showinfo':
				$this->PrintHeader(true);
				phpinfo();
				$this->PrintFooter(true);
			break;

			case 'sendpreviewdisplay':
				$this->PrintHeader($popup);
				$this->SendTestPreviewDisplay('index.php?Page=Settings&Action=SendPreview', 'self.parent.getPreviewParameters()');
				$this->PrintFooter($popup);
			break;

			case 'sendsmtppreviewdisplay':
				$this->PrintHeader($popup);
				$this->SendTestPreviewDisplay('index.php?Page=Settings&Action=SendPreview', 'self.parent.getSMTPPreviewParameters()');
				$this->PrintFooter($popup);
			break;

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

			case 'testbouncedisplay':
				$this->PrintHeader($popup);
				$this->TestBounceSettingsDisplay();
				$this->PrintFooter($popup);
			break;

			case 'testbouncesettings':
				$this->TestBounceSettings();
			break;

			case 'save':
				if (empty($_POST)) {
					$this->ShowSettingsPage();
					break;
				}
				$api = $this->GetApi();
				$result = false;

				$errors = array();

				// Make sure that Contact email is filled in
				if (!isset($_POST['email_address']) || trim($_POST['email_address']) == '') {
					array_push($errors, GetLang('ErrorAlertMessage_BlankContactEmail'));
				}

				// Make sure that license key is filled in
				if (!isset($_POST['licensekey']) || trim($_POST['licensekey']) == '') {
					array_push($errors, GetLang('ErrorAlertMessage_BlankLicenseKey'));
				}

				// Make sure that application name is filled in
				if (!isset($_POST['lng_applicationtitle']) || trim($_POST['lng_applicationtitle']) == '') {
					array_push($errors, GetLang('ErrorAlertMessage_BlankApplicationName'));
				}

				$agencyId = get_agency_license_variables();
				if(!empty($agencyId['agencyid'])) {
					$temp = IEM::requestGetPOST('lng_accountupgrademessage', '', 'trim');
					if (empty($temp)) {
						array_push($errors, GetLang('ErrorAlertMessage_BlankAccountUpgradeMessage'));
					}

					$temp = IEM::requestGetPOST('lng_freetrial_expiry_login', '', 'trim');
					if (empty($temp)) {
						array_push($errors, GetLang('ErrorAlertMessage_BlankExpiredLogin'));
					}
				}

				if ($api && count($errors) == 0) {
					do {
						$settings = array();

						// fix up the database settings first.
						$all_areas = $api->Areas;

						$LK = (isset($_POST['licensekey'])) ? $_POST['licensekey'] : false;

						if (defined('APPLICATION_SHOW_WHITELABEL_MENU') && constant('APPLICATION_SHOW_WHITELABEL_MENU')) {
							foreach ($all_areas['whitelabel'] as $area) {
								$val = IEM::requestGetPOST(strtolower($area), false);

								$temp = strtolower($area);
								switch ($temp) {
									// Special case for handling logo image
									case 'application_logo_image':
										$val = IEM::requestGetPOST('existing_app_logo_image', false);

										if (isset($_FILES['Application_Logo_Image']) && !empty($_FILES['Application_Logo_Image']['name'])) {
											if ($_FILES['Application_Logo_Image']['error'] != 0 || !@is_uploaded_file($_FILES['Application_Logo_Image']['tmp_name'])) {
												array_push($errors, GetLang('ErrorAlertMessage_ErrorApplicationLogoImage'));
												break 3;
											}

											if (!$this->IsImageFile(strtolower($_FILES['Application_Logo_Image']['name']))){
												array_push($errors, GetLang('ErrorAlertMessage_InvalidNameApplicationLogoImage'));
												break 3;
											}

											$uploadedFile = strtolower(basename($_FILES['Application_Logo_Image']['name']));
											$uploadedFile = preg_replace('/.*(\..*)$/', 'applicationlogo${1}', $uploadedFile);

											if(move_uploaded_file($_FILES['Application_Logo_Image']['tmp_name'], (TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile))) {
												@chmod(TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile, 0666);
												$val = 'temp/' . $uploadedFile;
											}

											if (!$this->IsValidImageFile(TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile, $_FILES['Application_Logo_Image']['type'])){
												@unlink(TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile);
												array_push($errors, GetLang('ErrorAlertMessage_InvalidFormatApplicationLogoImage'));
												break 3;
											}
										}
									break;

									// Special case for handling favicon
									case 'application_favicon':
										$val = IEM::requestGetPOST('existing_app_favicon', false);

										if (isset($_FILES['Application_Favicon']) && !empty($_FILES['Application_Favicon']['name'])) {
											if ($_FILES['Application_Favicon']['error'] != 0 || !@is_uploaded_file($_FILES['Application_Favicon']['tmp_name'])) {
												array_push($errors, GetLang('ErrorAlertMessage_ErrorApplicationFavicon'));
												break 3;
											}

											if (!$this->IsIconFile(strtolower($_FILES['Application_Favicon']['name']))){
												array_push($errors, GetLang('ErrorAlertMessage_InvalidNameApplicationFavicon'));
												break 3;
											}

											$uploadedFile = 'favicon.ico';

											if(move_uploaded_file($_FILES['Application_Favicon']['tmp_name'], (TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile))) {
												@chmod(TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile, 0666);
												$val = 'temp/' . $uploadedFile;
											}

											if (!$this->IsValidIconFile(TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile, $_FILES['Application_Favicon']['type'])){
												@unlink(TEMP_DIRECTORY . DIRECTORY_SEPARATOR . $uploadedFile);
												array_push($errors, GetLang('ErrorAlertMessage_InvalidFormatApplicationFavicon'));
												break 3;
											}
										}
									break;
								}

								$settings[$area] = $val;
							}
						}

						foreach ($all_areas['config'] as $area) {

							if (isset($_POST[strtolower($area)])) {
								$val = $_POST[strtolower($area)];
							} else {
								$val = false;
							}

							if ($area == 'DATABASE_USER') {
								if (isset($_POST['database_u'])) {
									$val = $_POST['database_u'];
								}
							}

							if ($area == 'DATABASE_PASS') {
								if (isset($_POST['database_p'])) {
									$val = $_POST['database_p'];
								}
							}

							if ($area == 'APPLICATION_URL') {
								if (substr($val, -1) == '/') {
									$val = substr($val, 0, -1);
								}
							}
							$settings[$area] = $val;
						}

						unset($all_areas['config']);
						unset($all_areas['whitelabel']);

						// look after all of the other settings now.
						foreach ($all_areas as $p => $area) {
							if (isset($_POST[strtolower($area)])) {
								$val = $_POST[strtolower($area)];
							} else {
								$val = false;
							}

							if ($area == 'BOUNCE_AGREEDELETE' && isset($_POST['bounce_process'])) {
								$val = 1;
							}

							if ($area == 'TEXTFOOTER') {
								$val = strip_tags($val);
							}

							if ($area == 'SMTP_USERNAME') {
								if (isset($_POST['smtp_u'])) {
									$val = $_POST['smtp_u'];
								}
							}

							if ($area == 'SMTP_PASSWORD') {
								if (isset($_POST['smtp_p'])) {
									$val = $_POST['smtp_p'];
								}
								$val = base64_encode($val);
							}

							if ($area == 'BOUNCE_PASSWORD') {
								if (isset($_POST['bounce_password'])) {
									$val = $_POST['bounce_password'];
								}
								$val = base64_encode($val);
							}

							$settings[$area] = $val;
						}

						// ----- Settings that cannot be changed
							$settings['DEFAULTCHARSET'] = SENDSTUDIO_DEFAULTCHARSET;
							if (!empty($settings['DEFAULTCHARSET'])) {
								$settings['DEFAULTCHARSET'] = 'UTF-8';
							}
						// -----

						// ----- Security settings
							$settings['SECURITY_WRONG_LOGIN_WAIT'] = intval($settings['SECURITY_WRONG_LOGIN_WAIT']);
							$settings['SECURITY_WRONG_LOGIN_THRESHOLD_COUNT'] = intval($settings['SECURITY_WRONG_LOGIN_THRESHOLD_COUNT']);
							$settings['SECURITY_WRONG_LOGIN_THRESHOLD_DURATION'] = intval($settings['SECURITY_WRONG_LOGIN_THRESHOLD_DURATION']) * 60;
							$settings['SECURITY_BAN_DURATION'] = intval($settings['SECURITY_BAN_DURATION']) * 60;

							if (!isset($_POST['security_wrong_login_wait_enable'])) {
								$settings['SECURITY_WRONG_LOGIN_WAIT'] = 0;
							}

							if (!isset($_POST['security_wrong_login_threshold_enable'])) {
								$settings['SECURITY_WRONG_LOGIN_THRESHOLD_COUNT'] = 0;
							}
						// -----

						$api->Set('Settings', $settings);

						$result = $api->Save();

						// Save warnings
						if ($result) {
							$tempRequestWarningsEnabled = IEM::requestGetPOST('credit_percentage_warnings_enable', array());
							$tempRequestWarningLevels = IEM::requestGetPOST('credit_percentage_warnings_level', array());
							$tempRequestWarnigSubjects = IEM::requestGetPOST('credit_percentage_warnings_subject', array());
							$tempRequestWarningEmails = IEM::requestGetPOST('credit_percentage_warnings_text', array());

							if (!empty($tempRequestWarningsEnabled) && !empty($tempRequestWarningLevels) && !empty($tempRequestWarningEmails)) {
								$tempRecords = array();
								foreach ($tempRequestWarningLevels as $index => $level) {
									$tempRecords[] = array(
										'enabled' => in_array($index, $tempRequestWarningsEnabled),
										'creditlevel' => $level,
										'aspercentage' => '1', // FIXME at this stage, only monthly credits warnings are available
										'emailsubject' => (isset($tempRequestWarnigSubjects[$index]) ? $tempRequestWarnigSubjects[$index] : ''),
										'emailcontents' => (isset($tempRequestWarningEmails[$index]) ? $tempRequestWarningEmails[$index] : '')
									);
								}

								$result = $api->SaveCreditWarnings($tempRecords);
							} else {
								$result = $api->SaveCreditWarnings(array());
							}

							unset($tempRequestWarningsEnabled);
							unset($tempRequestWarningLevels);
							unset($tempRequestWarningEmails);
						}
					} while(false);
				}

				$tabNum = ($_POST['tab_num'] && intval($_POST['tab_num'])) ? intval($_POST['tab_num']) : 1 ;

				if ($result) {
					FlashMessage(GetLang('SettingsSaved'), SS_FLASH_MSG_SUCCESS, 'index.php?Page=Settings&Tab='.$tabNum);
				} else {
					foreach ($errors as $error) {
						FlashMessage($error, SS_FLASH_MSG_ERROR);
					}

					FlashMessage(GetLang('SettingsNotSaved'), SS_FLASH_MSG_ERROR, 'index.php?Page=Settings&Tab='.$tabNum);
				}
			break;

			default:
				$this->ShowSettingsPage();
			break;
		}
	}
Пример #4
0
	/**
	 * ShowStep_4
	 * @return Void Returns nothing
	 */
	function ShowStep_4()
	{
		$upgrade_errors = IEM::sessionGet('DatabaseUpgradesFailed');

		if (!empty($upgrade_errors)) {
			?>
				<table cellspacing="0" cellpadding="0" width="95%" align="center">
					<tr>
						<td class="Heading1">Step 3: Upgrade Errors</TD>
					</tr>
					<tr>
						<td class="Text">
							<br/>There were problems upgrading your database.<br/><br/>
							<textarea cols="100" rows="5" onfocus="this.select();"><?php
								foreach ($upgrade_errors as $p => $upgrade_problem) {
									echo $upgrade_problem . "\n";
								}
							?></textarea>
							<br/>
						</TD>
					</TR>
				</TABLE>
			<?php
			return;
		}

		$backup_file = IEM::sessionGet('BackupFile');
		if ($backup_file) {
			$backup_files = list_files(TEMP_DIRECTORY);
			foreach ($backup_files as $p => $backupfile) {
				if (strpos($backupfile, 'system_backup.'.date('m-d-Y').'.txt') !== false) {
					unlink(TEMP_DIRECTORY . '/' . $backupfile);
				}
			}
		}

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

		$settings_api = new Settings_API(false);

		$settings = array();
		// hardcode this in, for this upgrade it's always going to be mysql.
		$settings['DATABASE_TYPE'] = 'mysql';
		$settings['DATABASE_USER'] = $GLOBALS['DBUSER'];
		$settings['DATABASE_PASS'] = $GLOBALS['DBPASS'];
		$settings['DATABASE_HOST'] = $GLOBALS['DBHOST'];
		$settings['DATABASE_NAME'] = $GLOBALS['DBNAME'];
		$settings['TABLEPREFIX'] = $GLOBALS['TABLEPREFIX'];

		$settings['LICENSEKEY'] = $GLOBALS['LicenseKey'];

		$settings['APPLICATION_URL'] = substr($GLOBALS['ROOTURL'], 0, -1);

		$settings['CRON_ENABLED'] = $GLOBALS['ServerSending'];

		$timezone = date('O');
		if ($timezone == '+0000') {
			$timezone = 'GMT';
		} else {
			$minutes = substr($timezone, -2);
			$timezone = 'GMT' . substr_replace($timezone, ':' . $minutes, -2);
		}

		$settings['SERVERTIMEZONE'] = str_replace(array('GMT-0', 'GMT+0'), array('GMT-', 'GMT+'), $timezone);

		$settings['DEFAULTCHARSET'] = $this->default_charset;

		$empty_settings = array('SMTP_SERVER', 'SMTP_USERNAME', 'SMTP_PASSWORD', 'HTMLFOOTER', 'TEXTFOOTER', 'EMAIL_ADDRESS', 'BOUNCE_ADDRESS', 'BOUNCE_SERVER', 'BOUNCE_USERNAME', 'BOUNCE_PASSWORD', 'BOUNCE_EXTRASETTINGS');
		foreach ($empty_settings as $k => $set) {
			$settings[$set] = '';
		}

		$zero_settings = array('SMTP_PORT', 'FORCE_UNSUBLINK', 'MAXHOURLYRATE', 'MAXOVERSIZE', 'IPTRACKING', 'BOUNCE_IMAP');
		foreach ($zero_settings as $k => $set) {
			$settings[$set] = '0';
		}

		$settings['MAX_IMAGEWIDTH'] = 700;
		$settings['MAX_IMAGEHEIGHT'] = 400;

		$settings_api->Set('Settings', $settings);

		define('SENDSTUDIO_DATABASE_TYPE', 'mysql');
		define('SENDSTUDIO_DATABASE_HOST', $GLOBALS['DBHOST']);
		define('SENDSTUDIO_DATABASE_USER', $GLOBALS['DBUSER']);
		define('SENDSTUDIO_DATABASE_PASS', $GLOBALS['DBPASS']);
		define('SENDSTUDIO_DATABASE_NAME', $GLOBALS['DBNAME']);
		define('SENDSTUDIO_TABLEPREFIX', $GLOBALS['TABLEPREFIX']);

		if (!defined('SENDSTUDIO_DEFAULTCHARSET')) {
			define('SENDSTUDIO_DEFAULTCHARSET', $this->default_charset);
		}

		if (!class_exists('MySQLDb', false)) {
			require_once(IEM_PATH . '/ext/database/mysql.php');
		}
		$db_type = 'MySQLDb';
		$db = new $db_type();

		$connection = $db->Connect(SENDSTUDIO_DATABASE_HOST, SENDSTUDIO_DATABASE_USER, SENDSTUDIO_DATABASE_PASS, SENDSTUDIO_DATABASE_NAME);

		$settings_api->Db = &$db;

		$settings_api->Save();

		?>
			<table cellspacing="0" cellpadding="0" width="95%" align="center">
				<tr>
					<td class="Heading1">Step 4: Upgrade Complete</TD>
				</tr>
				<TR>
					<TD class="Text"><br/><br/></TD>
				</TR>
				<TR>
					<TD>
						<table class="Panel" border="0" cellpadding="2" cellspacing="0" width="100%">
							<tr class="Heading3">
								<td colspan="2">
									&nbsp;&nbsp;Important Notes. Please Read.
								</td>
							</tr>
							<tr>
								<td>
									&nbsp;
								</td>
								<td style="padding:10px">
									<br/>The upgrade wizard has been completed successfully. You can log in <a href="<?php echo $_SERVER['PHP_SELF']; ?>">here</a> - your login details have not changed.<br>It's very important that you read the notes below, so please do that now:<br/><br/>
									<ul>
										<li>The default character set is set to 'ISO-8859-1'. If you need to change this, you will need to edit your admin/includes/config.php file to change it to 'UTF-8'.</li>
										<li>Sendstudio now supports timezones. Please check the settings page and confirm the server timezone. Please also check the timezone for each user and adjust it accordingly, they have all been set to GMT.</li>
										<li>Information (such as the date a person unsubscribed) was not stored, so the upgrade had to "guess" when this happened and set all of that information to today's date.</li>
										<li>Existing autoresponder statistics are not accurate. Information about who was sent which type of autoresponder was previously not recorded. That is, whether a subscriber was sent the html version or the text version.</li>
										<li>Users &amp; settings have a lot of new options.</li>
										<li>Custom fields have been associated with all of a users mailing list. Please check these associations.</li>
										<li>All forms have been set to 'Classic White (Default)', please adjust as necessary.</li>
										<li>You may need to clear your browsers cache to see the new images and buttons.</li>
									</ul>
								</td>
							</tr>
						</table>
					</TD>
				</TR>
			</TABLE>
		<?php
	}
Пример #5
0
define('IEM_CRON_JOB', true);

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

// CRON needs to run under CLI mode
define('IEM_CLI_MODE', true);

// Include the base init file.
require_once (dirname(dirname(__FILE__)) . '/index.php');

// Include settings API class
require_once IEM_PUBLIC_PATH . '/functions/api/settings.php';

// If database need upgrading, do not proceed.
$settings_api = new Settings_API();
if ($settings_api->NeedDatabaseUpgrade()) {
	exit;
}
unset($settings_api);

// Try to set unlimted time limit
if (!SENDSTUDIO_SAFE_MODE && strpos(SENDSTUDIO_DISABLED_FUNCTIONS, 'set_time_limit') === false) {
	set_time_limit(0);
}

// Sendstudio isn't set up? Quit.
if (!defined('SENDSTUDIO_IS_SETUP') || !SENDSTUDIO_IS_SETUP) {
	exit;
}
 /**
  * SaveDefaultSettings
  * Saves the default settings into the database.
  * Note that the database and required system settings must be set up before this is called.
  *
  * @return Array The first element is an error code indicating success (0) or failure (> 0). The second element is an error string.
  */
 public function SaveDefaultSettings()
 {
     if (!$this->CheckRequiredFields()) {
         return array(self::SETTINGS_MISSING, 'All required settings must be loaded first.');
     }
     if (!$this->_db) {
         return array(self::DB_MISSING, 'Database connection must be established first.');
     }
     require_once SENDSTUDIO_API_DIRECTORY . '/settings.php';
     $settings_api = new Settings_API(false);
     $settings = $this->_settings;
     $settings['DATABASE_UTF8PATCH'] = '1';
     $settings['SERVERTIMEZONE'] = self::GetTimezone();
     $settings['DEFAULTCHARSET'] = 'UTF-8';
     $settings['SMTP_PORT'] = '25';
     $settings['IPTRACKING'] = '1';
     $settings['MAXHOURLYRATE'] = '0';
     $settings['ALLOW_ATTACHMENTS'] = '1';
     $settings['USEMULTIPLEUNSUBSCRIBE'] = '0';
     $settings['CONTACTCANMODIFYEMAIL'] = '0';
     $settings['FORCE_UNSUBLINK'] = '0';
     $settings['MAXOVERSIZE'] = '0';
     $settings['MAX_IMAGEWIDTH'] = '700';
     $settings['MAX_IMAGEHEIGHT'] = '400';
     $settings['BOUNCE_IMAP'] = '0';
     $settings['ALLOW_EMBEDIMAGES'] = '1';
     $settings['ATTACHMENT_SIZE'] = '2048';
     $settings['CRON_ENABLED'] = '0';
     $settings['CRON_SEND'] = '5';
     $settings['CRON_AUTORESPONDER'] = '10';
     $settings['CRON_BOUNCE'] = '60';
     $settings['EMAILSIZE_WARNING'] = '500';
     $settings['EMAILSIZE_MAXIMUM'] = '2048';
     $settings['RESEND_MAXIMUM'] = '3';
     $settings['CREDIT_INCLUDE_AUTORESPONDERS'] = '1';
     $settings['CREDIT_INCLUDE_TRIGGERS'] = '1';
     $settings['CREDIT_WARNINGS'] = '0';
     $settings_api->Set('Settings', $settings);
     // set the table prefix constant for the API to work
     define('SENDSTUDIO_TABLEPREFIX', $this->_db->TablePrefix);
     $settings_api->Db =& $this->_db;
     $settings_api->Save();
     $username = $_POST['admin_username'];
     $usernameToken = API_USERS::generateUniqueToken($username);
     $password = API_USERS::generatePasswordHash($_POST['admin_password'], $usernameToken);
     // Set the admin user's settings
     $query = 'UPDATE [|PREFIX|]users SET ';
     $query .= " usertimezone='" . $this->_db->Quote($settings['SERVERTIMEZONE']) . "', ";
     $query .= " emailaddress='" . $this->_db->Quote($settings['EMAIL_ADDRESS']) . "', ";
     $query .= " textfooter='" . $this->_db->Quote(GetLang('Default_Global_Text_Footer')) . "', ";
     $query .= " htmlfooter='" . $this->_db->Quote(GetLang('Default_Global_HTML_Footer')) . "', ";
     $query .= " unique_token='" . $this->_db->Quote($usernameToken) . "', ";
     $query .= " username='******', ";
     $query .= " password='******'  ";
     $query .= ' WHERE userid=1';
     $result = $this->_db->Query($query);
     if (!$result) {
         return array(self::DB_QUERY_ERROR, $this->_db->GetErrorMsg());
     }
     return array(self::SUCCESS, null);
 }
Пример #7
0
 /**
  * Evaluate credit warning conditions
  *
  * This method will evaluate credit warnings for a particular user.
  * It will dispatch warning emails accrodingly.
  *
  * @param record_Users|integer $user User record object or user ID
  * @return boolean Returns TRUE if successful, FALSE otherwise
  *
  * @todo fixed credits does not have warnings yet
  */
 public static function creditEvaluateWarnings($user)
 {
     $userobject = null;
     $warnings = null;
     $this_month = mktime(0, 0, 0, date('n'), 1, date('Y'));
     $credit_left = null;
     // ----- PRE
     if ($user instanceof record_Users) {
         $userobject = $user;
     } else {
         $userobject = self::getRecordByID($user);
     }
     if (empty($userobject)) {
         trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- User is not specified', E_USER_NOTICE);
         return false;
     }
     // -----
     // Credit warnings are not enabled
     if (!SENDSTUDIO_CREDIT_WARNINGS) {
         return true;
     }
     require_once IEM_PUBLIC_PATH . '/functions/api/settings.php';
     $tempSettingsAPI = new Settings_API();
     $warnings = $tempSettingsAPI->GetCreditWarningsSettings();
     // Does not hany any warnings setup? Well... we can't continue then.
     if (empty($warnings)) {
         return true;
     }
     $credit_left = self::creditAvailableTotal($userobject);
     //unlimited credit
     if ($credit_left === true) {
         return true;
     }
     $whichlevel = self::creditWhichWarning($userobject, $credit_left, $warnings);
     // If $whichlevel contains FALSE, that means there was something wrong
     // when trying to figure out which warning level it should send out.
     if ($whichlevel === false) {
         return true;
     }
     $userGroup = API_USERGROUPS::getRecordById($userobject->groupid);
     if (!isset($userGroup['limit_emailspermonth'])) {
         return false;
     }
     $userobject_permonth = (int) $userGroup['limit_emailspermonth'];
     $fixed = self::creditAvailableFixed($userobject);
     $monthly = self::creditAvailableThisMonth($userobject);
     if ($fixed === true) {
         $userobject_permonth = $monthly;
     } elseif ($monthly === true) {
         $userobject_permonth = $fixed;
     }
     if (!empty($whichlevel)) {
         $tempNames = explode(' ', $userobject->fullname);
         $tempLastName = array_pop($tempNames);
         $tempFirstName = implode(' ', $tempNames);
         $available_custom_fields_key = array('%%user_fullname%%', '%%user_firstname%%', '%%user_lastname%%', '%%credit_total%%', '%%credit_remains%%', '%%credit_remains_precentage%%', '%%credit_used%%', '%%credit_used_percentage%%');
         $available_custom_fields_value = array($userobject->fullname, $tempFirstName, $tempLastName, $userobject_permonth, intval($userobject_permonth * ($credit_left / 100)), intval($credit_left), intval($userobject_permonth * ((100 - $credit_left) / 100)), intval(100 - $credit_left));
         $email_contents = str_replace($available_custom_fields_key, $available_custom_fields_value, $whichlevel['emailcontents']);
         $email_subject = str_replace($available_custom_fields_key, $available_custom_fields_value, $whichlevel['emailsubject']);
         // ----- We found which warnings it is that we want to send out
         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 ($userobject->smtpserver) {
             $emailapi->SetSmtp($userobject->smtpserver, $userobject->smtpusername, $userobject->smtppassword, $userobject->smtpport);
         }
         $emailapi->ClearRecipients();
         $emailapi->ForgetEmail();
         $emailapi->Set('forcechecks', false);
         $emailapi->AddRecipient($userobject->emailaddress, $userobject->fullname, 't');
         $emailapi->Set('FromName', false);
         $emailapi->Set('FromAddress', defined('SENDSTUDIO_EMAIL_ADDRESS') ? SENDSTUDIO_EMAIL_ADDRESS : $userobject->emailaddress);
         $emailapi->Set('BounceAddress', SENDSTUDIO_EMAIL_ADDRESS);
         $emailapi->Set('CharSet', SENDSTUDIO_CHARSET);
         $emailapi->Set('Subject', $email_subject);
         $emailapi->AddBody('text', $email_contents);
         $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;
         }
         // -----
         // ----- Update user record
         $db = IEM::getDatabase();
         $status = $db->Query("UPDATE [|PREFIX|]users SET credit_warning_time = {$this_month}, credit_warning_percentage = {$whichlevel['creditlevel']} WHERE userid = {$userobject->userid}");
         // Update user object in session
         // FIXME, we really need to make a special getter/setter for this
         $current_user = IEM::getCurrentUser();
         if ($current_user && $current_user->userid == $userobject->userid) {
             $current_user->credit_warning_time = $this_month;
             $current_user->credit_warning_percentage = $whichlevel['creditlevel'];
         }
         // -----
     }
     return true;
 }
Пример #8
0
	/**
	 * Save credit warning into database
	 *
	 * NOTE: warning record structure is as follow
	 * - enabled => character 1 or 0
	 * - creditlevel => integer
	 * - aspercentage => character 1 or 0
	 * - emailcontents => string
	 *
	 * @param array $warnings An array of warnings record that needed to be saved to the database (See note for record structure)
	 * @return boolean Returns TRUE if successful, FALSE otherwise
	 *
	 * FIXME better way of saving warnings. This might probably invlove refactoring Settings_API class
	 */
	function SaveCreditWarnings($warnings)
	{
		$db = IEM::getDatabase();

		$db->StartTransaction();

		$status = $db->Query("DELETE FROM [|PREFIX|]settings_credit_warnings");
		if (!$status) {
			$db->RollbackTransaction();
			trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Unable to clear old warning messages: ' . $db->Error(), E_USER_NOTICE);
			return false;
		}

		$levelSpecified = array();
		$sqlValues = array();
		foreach ($warnings as $warning) {
			$tempEnabled = ((array_key_exists('enabled', $warning) && $warning['enabled'] == 1) ? '1' : '0'); // Default to 0
			$tempCreditLevel = intval(array_key_exists('creditlevel', $warning) ? $warning['creditlevel'] : '0'); // Default to 0
			$tempAsPercentage = ((!array_key_exists('aspercentage', $warning) || $warning['aspercentage'] != 1) ? '0' : '1'); // Default to 1
			$tempEmailSubject = (array_key_exists('emailsubject', $warning) ? $db->Quote(trim($warning['emailsubject'])) : ''); // Default to empty
			$tempEmailContents = (array_key_exists('emailcontents', $warning) ? $db->Quote(trim($warning['emailcontents'])) : ''); // Default to empty

			if (empty($tempEmailSubject) || empty($tempEmailContents)) {
				$db->RollbackTransaction();
				trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- emailcontents and emailsubject cannot be empty', E_USER_NOTICE);
				return false;
			}

			if (in_array($tempCreditLevel, $levelSpecified)) {
				$db->RollbackTransaction();
				trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Credit level cannot be choosen more than once', E_USER_NOTICE);
				return false;
			}

			$sqlValues[] = "'{$tempEnabled}', {$tempCreditLevel}, '{$tempAsPercentage}', '{$tempEmailSubject}', '{$tempEmailContents}'";
		}

		if (!empty($sqlValues)) {
			$status = $db->Query("
				INSERT INTO [|PREFIX|]settings_credit_warnings (enabled, creditlevel, aspercentage, emailsubject, emailcontents)
				VALUES (" . implode('),(', $sqlValues) . ")
			");
			if (!$status) {
				$db->RollbackTransaction();
				trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Cannot save record to database: ' . $db->Error(), E_USER_NOTICE);
				return false;
			}
		}

		$db->CommitTransaction();

		// Need to refresh cache...
		self::$_creditWarningMessages = $warnings;

		return true;
	}
Пример #9
0
 /**
  * InsertChartImage
  * Sets the variables to display a statistics chart.
  *
  * @param String $chartname The variable name for the chart.
  * @param String $data_url The URL the chart should get data from.
  * @param Array $settings An array of settings for the chart.
  *
  * @return Void Returns nothing, sets the variables for displaying the chart.
  */
 private static function InsertChartImage($chartname, $data_url, $settings = null, $subaction)
 {
     // If this page is for print we'll return an image rather than embedding the flash player
     if ($subaction == 'print') {
         $params = array();
         if (is_array($settings)) {
             foreach ($settings as $key => $val) {
                 $params[] = urlencode($key) . "=" . urlencode($val);
             }
         }
         if (self::hasNoData($data_url)) {
             return '';
         }
         $params = implode('&amp;', $params);
         if (Settings_API::GDEnabled()) {
             return '<img src="' . $data_url . ($params ? '&amp;' . $params : '') . '&amp;GetAsImg=1" style="display: block;" />';
         } else {
             return '<p>(' . GetLang('GD_Not_Enabled') . ')</p>';
         }
     } else {
         $base_url = SENDSTUDIO_APPLICATION_URL . '/admin/';
         $transparent = true;
         $chartType = 'column';
         return InsertChart($chartType, $data_url, array('graph_title' => $settings['graph_title']), $transparent, $base_url);
     }
 }