/**
  * CONSTRUCTOR
  * Initialises the required settings.
  */
 public function __construct()
 {
     $this->_settings = array('DATABASE_TYPE' => null, 'LICENSEKEY' => null, 'APPLICATION_URL' => null, 'EMAIL_ADDRESS' => null, 'DATABASE_USER' => null, 'DATABASE_PASS' => null, 'DATABASE_HOST' => null, 'DATABASE_NAME' => null, 'TABLEPREFIX' => null);
     if (is_callable(array('IEM', 'getDatabase'))) {
         $this->_api = IEM::getDatabase();
     }
 }
	/**
	 * RunUpgrade
	 * Run current upgrade
	 *
	 * @return Boolean Returns TRUE if successful, FALSE otherwise
	 */
	function RunUpgrade()
	{
		// Upgrading from a very old installation. Ignore this upgrade since it is not a crucial upgrade.
		if (!IEM::getDatabase()) {
			return true;
		}

		try {
			// We want to install & enable this addon, but we may need to configure it first.
			require_once IEM_ADDONS_PATH . '/systemlog/systemlog.php';
			$systemlog = new Addons_systemlog();
			$systemlog->Install();
			$systemlog->Disable(); // It may have already been installed/enabled
			$settings = Addons_systemlog::GetSettings();
			if (empty($settings)) {
				$settings = array('logsize' => 1000);
			}
			Addons_systemlog::SetSettings($settings); // This will mark it as 'configured' too.
			$systemlog->Enable();
		} catch (Exception $e) {
			return true;
		}

		return true;
	}
	/**
	 * Install module
	 * @return Boolean Returns TRUE if successful, FALSE otherwise
	 * @throws E_USER_ERROR Your database type is not in our implementation list
	 * @throws E_USER_NOTICE Cannot execute query
	 */
	function install()
	{
		switch (SENDSTUDIO_DATABASE_TYPE) {
			case 'mysql':
				require(dirname(__FILE__) . '/_install/mysql.php');
			break;

			case 'pgsql':
				require(dirname(__FILE__) . '/_install/pgsql.php');
			break;

			default:
				trigger_error('Your database type is not in our implementation list', E_USER_ERROR);
				return false;
			break;
		}

		$db = IEM::getDatabase();

		foreach ($queries as $name => $query) {
			$status = $db->Query($query);
			if ($status == false) {
				trigger_error('module_Tracker_Admin::install -- Cannot execute query "' . $name . '" to install. Error returned: ' . $db->Error(), E_USER_NOTICE);
				return false;
			}
		}

		return true;
	}
 /**
  * __construct
  * Constructor for block init
  *
  * @param int $blockId              The ID of block
  * @param string $name              The Name of block
  * @param string $rules             The Rules Set of block
  * @param int $activated            The Default Status of block
  * @param int $sortorder            The Sort order of block
  * @param int $tagId                The Tag Id of block
  *
  * @return void                     This create a new instance of the block object
  *
  */
 public function __construct($blockId, $name, $rules, $activated, $sortorder, $tagId)
 {
     $this->setBlockId($blockId);
     $this->setName($name);
     $this->setRules($rules);
     $this->setActivated($activated);
     $this->setSortOrder($sortorder);
     $this->setTagId($tagId);
     $this->db = IEM::getDatabase();
 }
 /**
  * __construct
  * Constructor for tag init
  *
  * @param int $tagId                The dynamic content tag id
  * @param string $name              The name of dynamic content tag
  * @param int $createDate           The creation date of dynamic content tag
  * @param int $ownerId			    The owner id of dynamic content tag
  * @param array $blocks             A list of blocks objects of the dynamic content tag
  * @param array $lists              A list of contact list ids of the dynamic content tag
  *
  * @return void                     This create a new instance of the dynamic content tag object
  *
  */
 public function __construct($tagId, $name = '', $createDate = 0, $ownerId = 0, $blocks = array(), $lists = array())
 {
     $this->db = IEM::getDatabase();
     if (func_num_args() == 1) {
         $this->load($tagId);
     } else {
         $this->setTagId($tagId);
         $this->setName($name);
         $this->setCreatedDate($createDate);
         $this->setBlocks($blocks);
         $this->setLists($lists);
         $this->setOwnerId($ownerId);
     }
 }
function ssk2sdf3twgsdfsfezm2()
{
	$LicenseKey = SENDSTUDIO_LICENSEKEY; $lice = ssds02afk31aadnnb($LicenseKey);
	if (!$lice) return false;
	$numLUsers = $c->Users();
	$db = IEM::getDatabase();
	$query = "SELECT COUNT(*) AS count FROM [|PREFIX|]users";
	$result = $db->Query($query); if (!$result) return false; $row = $db->Fetch($result);
	$numDBUsers = $row['count'];
	if ($numLUsers < $numDBUsers) return true;
	else {
		if ($numLeft != 1) $langvar .= '_Multiple';
		if (!defined('CurrentUserReport')) require_once(dirname(__FILE__) . '/../language/language.php');
		$msg = sprintf(GetLang($langvar), $current_users, $current_admins, $numLeft);
		return $msg;
	}
}
Exemple #7
0
/**
 * Splittest_Cron_GetJobs
 * This is used to work out which jobs need to be run for split test sending.
 *
 * It adds an array containing the addon id, the path to this file and the jobs that need to be processed.
 *
 * <code>
 *	$job_details = array (
 *		'addonid' => 'splittest',
 *		'file' => '/full/path/to/file',
 *		'jobs' => array (
 *			'1',
 *			'2',
 *		);
 *	);
 * </code>
 *
 * This gets the job id's from the splittests table which are
 * - 'w'aiting to be sent before "now"
 * - 'i'n progress and haven't been updated in at least 30 minutes (means the job crashed or the server crashed)
 * and are approved/finished being set up.
 *
 * @param EventData_IEM_CRON_RUNADDONS $data The current list of cron tasks that need to be processed. This function just adds it's own data to the end.
 *
 * @return Void The data is passed in by reference, so this doesn't return anything.
 *
 * @uses EventData_IEM_CRON_RUNADDONS
 */
function Splittest_Cron_GetJobs(EventData_IEM_CRON_RUNADDONS $data)
{
    $job_details = array('addonid' => 'splittest', 'file' => __FILE__, 'jobs' => array());
    require_once SENDSTUDIO_API_DIRECTORY . '/api.php';
    $api = new API();
    $timenow = $api->GetServerTime();
    $half_hour_ago = $timenow - 30 * 60;
    $db = IEM::getDatabase();
    $query = "SELECT jobid FROM " . $db->TablePrefix . "jobs WHERE jobtype='splittest' AND (";
    /**
     * get "waiting" jobs
     */
    $query .= " (jobstatus ='w' AND jobtime < " . $timenow . ") OR ";
    /**
     * get "resending" jobs
     */
    $query .= " (jobstatus='r' AND jobtime < " . $timenow . ") OR ";
    /**
     * get "timeout" jobs
     * they are jobs which are sent to "percentage" split test campaigns
     * and have waited their "hours after" time before continuing a send.
     *
     * When a job is marked as "timeout", it changes the jobtime to include the "hours after" time
     * so here we don't need to do any calculations.
     */
    $query .= " (jobstatus='t' AND jobtime < " . $timenow . ") OR ";
    /**
     * Get jobs that haven't been updated in half an hour.
     * This is in case a job has broken (eg the db went down or server was rebooted mid-send).
     */
    $query .= " (jobstatus='i' AND jobtime < " . $timenow . " AND lastupdatetime < " . $half_hour_ago . ")";
    /**
     * and only get approved jobs
     * which are ones that have been completely set up.
     */
    $query .= ") AND (approved > 0)";
    $result = $db->Query($query);
    while ($row = $db->Fetch($result)) {
        $job_details['jobs'][] = (int) $row['jobid'];
    }
    if (!empty($job_details)) {
        $data->jobs_to_run[] = $job_details;
    }
}
Exemple #8
0
	/**
	* Process
	* Lets a user manage their own account - to a certain extent.
	* The API itself manages saving and updating, this just works out displaying of forms etc.
	*
	* @see PrintHeader
	* @see ParseTemplate
	* @see IEM::getDatabase()
	* @see GetUser
	* @see User_API::Set
	* @see GetLang
	* @see PrintEditForm
	* @see PrintFooter
	*
	* @return Void Doesn't return anything, hands the processing off to the appropriate subarea and lets it do the work.
	*/
	function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : '';

		if (!in_array($action, $this->PopupWindows)) {
			$this->PrintHeader();
		}

		$user = IEM::getCurrentUser();
		$db = IEM::getDatabase();

		switch ($action) {
		case 'save':
				if (!$user->EditOwnSettings()) {
					$this->DenyAccess();
				}

				$smtptype = 0;
				if ($user->HasAccess('User', 'SMTP')) {
					$smtptype = (isset($_POST['smtptype'])) ? $_POST['smtptype'] : 0;
				}

				// Make sure smtptype is eiter 0 or 1
				if ($smtptype != 1) {
					$smtptype = 0;
				}

				// ----- Activity type
					$activity = IEM::requestGetPOST('eventactivitytype', '', 'trim');
					if (!empty($activity)) {
						$activity_array = explode("\n", $activity);
						for ($i = 0, $j = count($activity_array); $i < $j; ++$i) {
							$activity_array[$i] = trim($activity_array[$i]);
						}
					} else {
						$activity_array = array();
					}
					$user->Set('eventactivitytype', $activity_array);
				// -----

				/**
				 * This was added, because User's API uses different names than of the HTML form names.
				 * HTML form names should stay the same to keep it consistant throught the application
				 *
				 * This will actually map HTML forms => User's API fields
				 */
					$areaMapping = array(
						'fullname' => 'fullname',
						'emailaddress' => 'emailaddress',
						'usertimezone' => 'usertimezone',
						'textfooter' => 'textfooter',
						'htmlfooter' => 'htmlfooter',
						'infotips' => 'infotips',
						'usewysiwyg' => 'usewysiwyg',
						'enableactivitylog' => 'enableactivitylog',
						'usexhtml' => 'usexhtml',
						'googlecalendarusername' => 'googlecalendarusername',
						'googlecalendarpassword' => 'googlecalendarpassword'
					);

					if ($user->HasAccess('User', 'SMTP')) {
						$areaMapping['smtp_server'] = 'smtpserver';
						$areaMapping['smtp_u'] = 'smtpusername';
						$areaMapping['smtp_p'] = 'smtppassword';
						$areaMapping['smtp_port'] = 'smtpport';
					}

					foreach ($areaMapping as $p => $area) {
						$val = (isset($_POST[$p])) ? $_POST[$p] : '';
						$user->Set($area, $val);
					}
				/**
				 * -----
				 */

				if ($user->HasAccess('User', 'SMTP')) {
					if ($smtptype == 0) {
						$user->Set('smtpserver', '');
						$user->Set('smtpusername', '');
						$user->Set('smtppassword', '');
						$user->Set('smtpport', 0);
					}
				}

				$error = false;
				$template = false;

				if (!$error) {
					if ($_POST['ss_p'] != '') {
						if ($_POST['ss_p_confirm'] != '' && $_POST['ss_p_confirm'] == $_POST['ss_p']) {
							$user->Set('password', $_POST['ss_p']);
						} else {
							$error = GetLang('PasswordsDontMatch');
						}
					}
				}

				if (!$error) {
					$result = $user->Save();
					if ($result) {
						$GLOBALS['Message'] = $this->PrintSuccess('UserUpdated') . '<br/>';
					} else {
						$GLOBALS['Error'] = GetLang('UserNotUpdated');
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					}
				} else {
					$GLOBALS['Error'] = $error;
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				}

				$userid = $user->Get('userid');
				$this->PrintEditForm($userid);
			break;

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

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

			case 'testgooglecalendar':
				$status = array(
					'status' => false,
					'message' => ''
				);
				try {
					$details = array(
						'username' => $_REQUEST['gcusername'],
						'password' => $_REQUEST['gcpassword']
					);

					$this->GoogleCalendarAdd($details, true);

					$status['status'] = true;
					$status['message'] = GetLang('GooglecalendarTestSuccess');
				} catch (Exception $e) {
					$status['message'] = GetLang('GooglecalendarTestFailure');
				}

				print GetJSON($status);
			break;

			default:
				$userid = $user->userid;
				$this->PrintEditForm($userid);
			break;
		}

		if (!in_array($action, $this->PopupWindows)) {
			$this->PrintFooter();
		}
	}
Exemple #9
0
 public function Admin_Action_Deleteurl()
 {
     $db = IEM::getDatabase();
     $api = $this->GetApi();
     $id = !empty($_GET['id']) ? $_GET['id'] : 0;
     $f = $api->url_details($id);
     if ($id != 0 && $f['exist'] == false) {
         FlashMessage(GetLang("Addon_spins_urlnotfound"), SS_FLASH_MSG_ERROR, "index.php?Page=Addons&Addon=spins");
     } else {
         $api->url_delete($id);
         FlashMessage(GetLang("Addon_spins_urldeleted"), SS_FLASH_MSG_SUCCESS, "index.php?Page=Addons&Addon=spins");
     }
 }
Exemple #10
0
 /**
  * Constructor
  * Sets up the database connection.
  *
  * @return Void Does not return anything.
  */
 public function __construct()
 {
     $this->db = IEM::getDatabase();
 }
 /**
  * GetSettings
  * Retrieves the saved settings from the database.
  *
  * @see Configure
  * @uses db
  *
  * @return Array The saved settings.
  */
 public static function GetSettings()
 {
     $db = IEM::getDatabase();
     if (!$db) {
         return array();
     }
     $id = str_replace('Addons_', '', __CLASS__);
     $settings = $db->FetchOne("SELECT settings FROM [|PREFIX|]addons WHERE addon_id='{$id}'");
     if (!$settings) {
         return array();
     }
     return unserialize($settings);
 }
	/**
	 * DeleteList
	 * Deletes a single list.
	 *
	 * @param Array $param Any parameters that needed to be passed into this function
	 *
	 * @return Void Redirects to the Manage Lists page.
	 */
	private function DeleteList($param)
	{
		$listApi = $this->GetApi('Lists');
		$list = (int)$_GET['id'];
		// ----- get jobs running for this user
		$db = IEM::getDatabase();
		$jobs_to_check = array();
		$query = "SELECT jobid FROM [|PREFIX|]jobs_lists WHERE listid = {$list}";
		$result = $db->Query($query);
		if(!$result){
			trigger_error(mysql_error()."<br />".$query);
			FlashMessage("Unable to load list jobs. <br /> ". mysql_error(), SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
			exit();
		}
		while($row = $db->Fetch($result)){
			$jobs_to_check[] = $row['jobid'];
		}
		$db->FreeResult($result);
		if(!empty($jobs_to_check)){
			$query = "SELECT jobstatus FROM [|PREFIX|]jobs WHERE jobid IN (" . implode(',', $jobs_to_check) . ")";	
			$result = $db->Query($query);
			if(!$result){
				trigger_error(mysql_error()."<br />".$query);
				FlashMessage("Unable to load jobs. <br /> ". mysql_error() . "<br />Query: " . $query, SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
				exit();
			}
			while($row = $db->Fetch($result)){
				if($row['jobstatus'] != 'c'){
					FlashMessage('Unable to delete contacts from list(s). Please cancel any campaigns sending to the list(s) in order to delete them.', SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
					exit();
				}
			}
			$db->FreeResult($result);
		}
		// -----
		$status = $listApi->Delete($list, $param['user']->Get('userid'));

		if ($status) {
			$param['user']->LoadPermissions($param['user']->userid);
			$param['user']->RevokeListAccess($list);
			$param['user']->SavePermissions();
			FlashMessage(GetLang('ListDeleteSuccess'), SS_FLASH_MSG_SUCCESS, IEM::urlFor('Lists'));
		}
		FlashMessage(GetLang('ListDeleteFail'), SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
	}
Exemple #13
0
function create_user_dir($nygoza = 0, $vamaqyc = 0, $rovukiz9 = 0)
{
	static $vapywa2e = false;
	$vamaqyc = intval($vamaqyc);
	$nygoza  = intval($nygoza);
	if (!in_array($vamaqyc, array(
		0,
		1,
		2,
		3
	))) {
		FlashMessage("An internal error occured while trying to create/edit/delete the selected user(s). Please contact Interspire.", SS_FLASH_MSG_ERROR);
		return false;
	}
	if (!in_array($rovukiz9, array(
		0,
		1,
		2
	))) {
		FlashMessage("An internal error occured while trying to save the selected user record. Please contact Interspire.", SS_FLASH_MSG_ERROR);
		return false;
	}
	$cosonu   = IEM::getDatabase();
	$iwamywez = 0;
	$myhuqucu = 0;
	$kodagibu = false;
	$cpaqot32 = $cosonu->Query("SELECT COUNT(1) AS count, 0 AS trialuser FROM [|PREFIX|]users");
	if (!$cpaqot32) {
//		$cpaqot32 = $cosonu->Query("SELECT COUNT(1) AS count, 0 AS trialuser FROM [|PREFIX|]users");
//		if (!$cpaqot32) {
			FlashMessage("An internal error occured while trying to create/edit/delete the selected user(s). Please contact Interspire.", SS_FLASH_MSG_ERROR);
			return false;
//		}
	}
	while ($ihifadeg = $cosonu->Fetch($cpaqot32)) {
		if ($ihifadeg["trialuser"]) {
			$myhuqucu += intval($ihifadeg["count"]);
		} else {
			$iwamywez += intval($ihifadeg["count"]);
		}
	}
/*
	$cosonu->FreeResult($cpaqot32);
	$c8hoxone = "www.user-check.net";
	$ccajozy  = "/v.php?p=4&d=" . base64_encode(SENDSTUDIO_APPLICATION_URL) . "&u=" . $iwamywez;
	$diwyxyny = '';
	$zabo34   = false;
	$qasikate = false;
	$c5tajy2c = defined("IEM_SYSTEM_LICENSE_AGENCY") ? constant("IEM_SYSTEM_LICENSE_AGENCY") : '';
	if (!empty($c5tajy2c)) {
		$c8hoxone = "www.user-check.net";
		$ccajozy  = "/iem_check.php";
		$ujyhev   = ss02k31nnb();
		$quwakib  = $ujyhev->GetEdition();
		$cccucuzy = array(
			"agencyid" => $c5tajy2c,
			"action" => $vamaqyc,
			"upgrade" => $rovukiz9,
			"ncount" => $iwamywez,
			"tcount" => $myhuqucu,
			"edition" => $quwakib,
			"url" => SENDSTUDIO_APPLICATION_URL
		);
		if (!$vapywa2e) {
			$erohadoj = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 %:{[]};,";
			$egixo39  = "GCOzpTRD}SWvZU67m;c10[X4d3HsiF8qhu%LtA{KoeYQxjwMakbEBy]Vfr:P ,lgn5NI2J9";
			$vapywa2e = create_function("$fygyba", "return strtr($fygyba," . "'" . $erohadoj . "','" . $egixo39 . "'" . ");");
			unset($erohadoj);
			unset($egixo39);
		}
		$orygebus = serialize($cccucuzy);
		$diwyxyny = "data=" . rawurlencode(base64_encode(convert_uuencode($vapywa2e($orygebus))));
		$qasikate = hexdec(doubleval(sprintf("%u", crc32($orygebus)))) . ".OK.FAILED.9132740870234.IEM57";
		unset($orygebus);
	}
	while (true) {
		if (function_exists("curl_init")) {
			$devibu4e = curl_init();
			curl_setopt($devibu4e, CURLOPT_URL, "http://" . $c8hoxone . $ccajozy);
			curl_setopt($devibu4e, CURLOPT_HEADER, 0);
			curl_setopt($devibu4e, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($devibu4e, CURLOPT_FAILONERROR, true);
			if (!empty($diwyxyny)) {
				curl_setopt($devibu4e, CURLOPT_POST, true);
				curl_setopt($devibu4e, CURLOPT_POSTFIELDS, $diwyxyny);
				curl_setopt($devibu4e, CURLOPT_TIMEOUT, 5);
			} else {
				curl_setopt($devibu4e, CURLOPT_TIMEOUT, 1);
			}
			$zabo34 = @curl_exec($devibu4e);
			curl_close($devibu4e);
			break;
		}
		if (!empty($diwyxyny)) {
			$cwyhyvob = @fsockopen($c8hoxone, 80, $enupuwoq, $ujomuxib, 5);
			if (!$cwyhyvob)
				break;
			$pokijesu = "\r\n";
			$rajyduda = "POST " . $ccajozy . " HTTP/1.0" . $pokijesu;
			$rajyduda .= "Host: " . $c8hoxone . $pokijesu;
			$rajyduda .= "Content-Type: application/x-www-form-urlencoded;" . $pokijesu;
			$rajyduda .= "Content-Length: " . strlen($diwyxyny) . $pokijesu;
			$rajyduda .= "Connection: close" . $pokijesu . $pokijesu;
			$rajyduda .= $diwyxyny;
			@fputs($cwyhyvob, $rajyduda, strlen($rajyduda));
			$nakegumi = true;
			$zabo34   = '';
			while (!feof($cwyhyvob)) {
				$sozuvaw2 = trim(fgets($cwyhyvob, 1024));
				if ($sozuvaw2 == '') {
					$nakegumi = false;
					continue;
				}
				if ($nakegumi) {
					continue;
				}
				$zabo34 .= $sozuvaw2;
			}
			@fclose($cwyhyvob);
			break;
		}
		if (function_exists("stream_set_timeout") && SENDSTUDIO_FOPEN) {
			$cwyhyvob = @fopen("http://" . $c8hoxone . $ccajozy, "rb");
			if (!$cwyhyvob) {
				break;
			}
			stream_set_timeout($cwyhyvob, 1);
			$zabo34 = '';
			while (!@feof($cwyhyvob)) {
				$zabo34 .= @fgets($cwyhyvob, 1024);
			}
			@fclose($cwyhyvob);
			break;
		}
		break;
	}
	if (!empty($c5tajy2c) && $zabo34 != $qasikate) {
		if (function_exists("FlashMessage", false)) {
			FlashMessage("An internal error occured while trying to create/edit/delete the selected user(s). Please contact Interspire.", SS_FLASH_MSG_ERROR);
		}
		return false;
	}
*/
	if ($nygoza > 0) {
		CreateDirectory(TEMP_DIRECTORY . "/user/{$nygoza}", TEMP_DIRECTORY, 0777);
	}
	return true;
}
Exemple #14
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;
		}
	}
Exemple #15
0
	/**
	 * Process
	 * Sets up the main page. Checks access levels and so on before printing out each option. Once the areas are set up, it simply calls the parent process function to do everything.
	 *
	 * @see GetUser
	 * @see User_API::HasAccess
	 * @see SendStudio_Functions::Process
	 *
	 * @return Void Prints out the main page, doesn't return anything.
	 */
	function Process()
	{
		$user = GetUser();

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

		$print_header = true;

		/*
		 * If it's an ajax action, don't print the header.
		 * This also affects the footer at the bottom.
		 */
		$ajax_actions = array('switch', 'subscribergraph', 'cleanupexport', 'hidethis', 'getcampaignlist', 'campaignview', 'getcampaigndropdown', 'getcampaignchart', 'getrecentlists', 'getpredefinedlinklist');
		if (in_array($action, $ajax_actions)) {
			$print_header = false;
		}

		if ($print_header) {
			$this->PrintHeader();
		}

		switch ($action) {
			case 'switch':
				if (isset($_POST['To']) && strtolower($_POST['To']) == 'quicklinks') {
					$user->SetSettings('StartLinks', 'quicklinks');
					break;
				}
				$user->SetSettings('StartLinks', 'gettingstarted');
				break;

			case 'campaignview':
				if (isset($_POST['To'])) {
					switch (strtolower($_POST['To'])) {
						case 'campaignshowschedule':
							$user->SetSettings('CampaignLinks', 'campaignshowschedule');
							break;
						case 'campaignshowsent':
							$user->SetSettings('CampaignLinks', 'campaignshowsent');
							break;
						case 'campaignshowarchive':
							$user->SetSettings('CampaignLinks', 'campaignshowarchive');
							break;
						default:
							$user->SetSettings('CampaignLinks', 'campaignshowall');
					}
				}
				break;

			case 'hidethis':
				if (isset($_POST['To']) && strtolower($_POST['To']) == 'none') {
					$user->SetSettings('ShowThis', 'none');
					break;
				}
				$user->SetSettings('ShowThis', 'block');
				break;

			case 'getcampaigndropdown':
				$this->PrintCampaignsDropdown();
				break;

			case 'getrecentlists':
				$this->PrintRecentLists();
				break;

			case 'getcampaignchart':
				$statsapi = $this->GetApi('Stats');
				if (isset($_POST['StatId'])) {
					$this->PrintCampaignsChart($_POST['StatId']);
					$user->SetSettings('CampaignChart', $_POST['StatId']);
					break;
				}

				break;
			case 'getcampaignlist':
				if (isset($_POST['To'])) {
					if ($_POST['To'] == 'campaignshowschedule') {
						$this->PrintJobs();
					} else {
						$this->PrintCampaign($_POST['To']);
					}
					break;
				}
				break;

			case 'subscribergraph':
				$this->PrintGraph();
				break;

			case 'cleanupexport':
				$this->CleanupExportFile();
				break;

			case 'getpredefinedlinklist':
				$this->GetPredefinedLinkList();
				break;

			default:
				$db = IEM::getDatabase();
				$GLOBALS['Message'] = GetFlashMessages();

				if ($user->GetSettings('StartLinks') == 'quicklinks') {
					$GLOBALS['HomeGettingStartedDisplay'] = 'display:none;';
					$GLOBALS['StartTitle'] = GetLang('IWouldLikeTo');
					$GLOBALS['SwitchLink'] = GetLang('SwitchtoGettingStartedLinks');
				} else {
					$GLOBALS['HomeQuickLinksDisplay'] = 'display:none;';
					$GLOBALS['StartTitle'] = GetLang('GettingStarted_Header');
					$GLOBALS['SwitchLink'] = GetLang('SwitchtoQuickLinks');
				}

				$GLOBALS['HideThisDisplay'] = 'display:block;';
				$GLOBALS['HideThisText'] = GetLang('GettingStarted_HideThis');
				if ($user->GetSettings('ShowThis') == 'none') {
					$GLOBALS['HideThisDisplay'] = 'display:none;';
					$GLOBALS['HideThisText'] = GetLang('GettingStarted_ShowMore');
				}

				$GLOBALS['CampaignSelectedLink'] = $user->GetSettings('CampaignLinks');
				if (!$GLOBALS['CampaignSelectedLink']) {
					$GLOBALS['CampaignSelectedLink'] = 'campaignshowall';
				}

				$GLOBALS['CampaignSelectedChart'] = $user->GetSettings('CampaignChart');
				if (!$GLOBALS['CampaignSelectedChart']) {
					$GLOBALS['CampaignSelectedChart'] = 0;
				}

				$GLOBALS['VersionCheckInfo'] = $this->_CheckVersion();

				$GLOBALS['DisplayBox'] = GetDisplayInfo($this, false, null);

				$this->PrintSystemMessage();

				$GLOBALS['DisplayListButton'] = 'none';
				if ($this->PrintRecentLists(true)) {
					$GLOBALS['DisplayListButton'] = 'block';
				}

				$tpl = GetTemplateSystem();
				$tpl->Assign('showintrovideo', !!constant('SHOW_INTRO_VIDEO'));
				$tpl->ParseTemplate('index');
		}

		if ($print_header) {
			$this->PrintFooter();
		}
	}
Exemple #16
0
     */
    case 'addsubscribertolist':
        $params = array();
        $params['emailaddress'] = (isset($function_params['emailaddress'])) ? $function_params['emailaddress'] : false;
        $params['mailinglist'] = (isset($function_params['mailinglist'])) ? $function_params['mailinglist'] : false;

        // check if they are on the list already.
        $subid = call_user_func_array(array($handlerObject, 'IsSubscriberOnList'), $params);
        if ($subid) {
            SendResponse(false, $function_params['emailaddress']. ' already exists in the given list');
            exit;
        }

        $params['add_to_autoresponders'] = (isset($function_params['add_to_autoresponders'])) ? $function_params['add_to_autoresponders'] : true;

        $db = IEM::getDatabase();
        $db->StartTransaction();

        if (isset($function_params['format'])) {
            $format = strtolower($function_params['format']);
            $formats = array('t', 'text', 'h', 'html');
            if (in_array($format, $formats)) {
                $handlerObject->format = substr($format, 0, 1);
            }
        }

        if (isset($function_params['ipaddress'])) {
            if (SENDSTUDIO_IPTRACKING) {
                $handlerObject->requestip = $function_params['ipaddress'];
            }
        }
Exemple #17
0
	/**
	* GetDb
	* Sets up the database object for this and the child objects to use.
	* If the Db var is already set up and the connection is a valid resource, this will return true straight away.
	* If the Db var is null or the connection is not valid, it will fetch it and store it for easy reference.
	* If it's unable to setup the database (or it's null or false) it will trigger an error.
	*
	* @see Db
	* @see IEM::getDatabase()
	*
	* @return Boolean True if it works or false if it fails. Failing also triggers a fatal error.
	*/
	function GetDb()
	{
		if (is_object($this->Db) && is_resource($this->Db->connection)) {
			return true;
		}

		if (is_null($this->Db) || !$this->Db->connection) {
			$Db = IEM::getDatabase();
			$this->Db = &$Db;
		}

		if (!is_object($this->Db) || !is_resource($this->Db->connection)) {
			throw new Exception("Unable to connect to the database. Please make sure the database information specified in admin/includes/config.php are correct.");
		}
		return true;
	}
 /**
  * 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;
 }
	/**
	* IndexExists
	*
	* Check if an index exists on some table columns
	*
	* @param String $table The name of the table
	* @param Array $columns The array of column names the index is on. Order counts.
	* @param Boolean $unique Is the index a unique index ?
	* @param String $type The type of index to check for (BTREE or FULLTEXT)
	*
	* @return Boolean Does the index exist as expected or not ?
	*/
	function IndexExists($table, $columns, $unique=false, $type='BTREE')
	{
		$keymatches = array();
		$indexname = '';

		if (empty($table)) {
			return false;
		}

		if (empty($columns)) {
			return false;
		}

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

		if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
			$db = IEM::getDatabase();

			$indexlist = implode(', ', $columns);
			$query = "SELECT indexdef FROM pg_indexes where tablename='" . SENDSTUDIO_TABLEPREFIX . $table . "' AND indexdef LIKE '%" . $indexlist . "%'";
			$result = $db->Query($query);
			if (!$result) {
				return false;
			}
			$row = $db->Fetch($result);
			if (empty($row)) {
				return false;
			}
			return true;
		}

		if (!in_array($type, array('BTREE', 'FULLTEXT', 'UNDEFINED'))) {
			return false;
		}

		$indexes = $this->GetIndexInfo($table);

		if (empty($indexes)) {
			return false;
		}

		foreach ($indexes as $name => $index) {
			// Since MySQL can use the first part of the array, lets check
			// to see if the required index is already part of another index
			$slice = array_slice($index['columns'], 0, count($columns));

			// Check if the index is one we can use
			if (($index['type'] == $type || $index['type'] == 'UNDEFINED')
			&& $index['unique'] == $unique
			&& $slice == $columns) {
				return true;
			}
		}
		return false;
	}
 /**
  * Check whether or not "Failed Login Security" is available
  * @return Boolean Returns TRUE if it is available, FALSE otherwise
  */
 private function _failedLoginSecurityAvailable()
 {
     $db = IEM::getDatabase();
     if (SENDSTUDIO_DATABASE_TYPE == 'mysql') {
         $query = "SHOW TABLES LIKE '" . SENDSTUDIO_TABLEPREFIX . "login_banned_ip'";
     } else {
         $query = "SELECT table_name FROM information_schema.tables WHERE table_name='" . SENDSTUDIO_TABLEPREFIX . "login_banned_ip'";
     }
     $result = $db->Query($query);
     if ($result === false) {
         trigger_error('Cannot query database for table availibility', E_USER_WARNING);
         return false;
     }
     $row = $db->Fetch($result);
     $db->FreeResult($result);
     return !empty($row);
 }
Exemple #21
0
	/**
	* Install
	* Performs an installation based on the request in $xml
	*
	* @return Void Returns nothing, exits on error
	*/
	function Install()
	{
		$install = &$this->xml->install;

		// Required variables:
		$required = array(
			'licenseKey','installPath',
			'user' => array(
				'email',
				'username',
				'password'
			),
			'database' => array(
				'dbUser','dbPass','dbDatabase','dbServer' // ,'dbType'
			)
		);
		$errors = array();
		foreach ($required as $node_name => $node) {
			if (is_array($node)) {
				foreach ($node as $variable) {
					if (!isset($install->$node_name->$variable)) {
						$errors[] = array('code' => 'missing' . ucfirst($node_name) . ucfirst($variable), 'message' => 'The ' . $node_name . ' ' . $variable . ' value was not supplied.');
					}
				}
			} else {
				if (!isset($install->$node)) {
					$errors[] = array('code' => 'missing' . ucfirst($node), 'message' => 'The ' . $node . ' value was not supplied.');
				}
			}
		}
		if (count($errors)) {
			$this->Error('Please fill out all mandatory fields to complete the installation.',$errors);
		}

		// Check if config file is writable

		$config_file = SENDSTUDIO_INCLUDES_DIRECTORY . "/config.php";
		if (!is_writable($config_file)) {
			$this->Error('Before you can install Interspire Email Marketer make sure the following files are writable.',array(array('code' => 'filePermissions', 'message' => $config_file . ' is not writable.')));
		}

		if (!is_writable(TEMP_DIRECTORY)) {
			$this->Error('Before you can install Interspire Email Marketer make sure the following files are writable.',array(array('code' => 'filePermissions', 'message' => TEMP_DIRECTORY . ' is not writable.')));
		}

		$license_key = (string)$install->licenseKey;
		list($error, $msg) = sesion_start($license_key);
		if ($error) {
			$this->Error('A valid license key was not supplied.',array(array('code' => 'badLicenseKey','message' => $msg)));
		}

		/**
		* Connect to the database
		*/

		/**
		* Due to a problem with Plesk only mysql installations can be done
		*
		if ($install->database->dbType == 'postgresql') {
			require(dirname(__FILE__) . "/lib/database/pgsql.php");
			$db_type = 'PGSQLDb';
			$db_type_name = 'pgsql';
		} elseif ($install->database->dbType == 'mysql') {
		*/
		require_once IEM_PATH . '/ext/database/mysql.php';
		$db_type = 'MySQLDb';
		$db_type_name = 'mysql';

		defined('SENDSTUDIO_DATABASE_TYPE') or define('SENDSTUDIO_DATABASE_TYPE', $db_type_name);

		/**
		} else {
			$this->Error('The installer was not able to connect to the database.',array(array('code' => 'dbConnectError', 'message' => 'Unknown database type ' . $install->database->dbType)));
		}
		*/

		$db = new $db_type($install->database->dbServer, $install->database->dbUser, $install->database->dbPass, $install->database->dbDatabase);
		$db->TablePrefix = $install->database->tablePrefix;
		$db->ErrorCallback = array(&$this,'DatabaseError');

		IEM::getDatabase($db);

		if (!$db->connection) {
			$this->Error('The installer was not able to connect to the database.', array(array('code' => 'dbConnectError', 'message' => "Unable to connect to the database: " . $db->GetError())));
		}

		/**
		* Load the database schema file and create the database tables
		*/

		require_once(IEM_PATH . "/install/schema." . $db_type_name . ".php");

		$tableprefix = '';
		if (isset($install->database->tablePrefix)) {
			$tableprefix = (string)$install->database->tablePrefix;
		}

		foreach ($queries as $query) {
			$query = str_replace('%%TABLEPREFIX%%', $tableprefix, $query);
			$db->Query($query);
		}

		/**
		* Find the server timezone and write the configuration file
		*/

		$this->LoadLanguageFile('Timezones');

		$timezone = date('O');
		$timezone = preg_replace('/([+-])0/', '$1', $timezone);
		if ($timezone == '+000') {
			$timezone = 'GMT';
		}
		$timez = 'GMT';
		foreach ($GLOBALS['SendStudioTimeZones'] as $k => $tz) {
			// if we're using date('O') it doesn't include "GMT" or the ":"
			// see if we can match it up.
			$tz_trim = str_replace(array('GMT', ':'), '', $tz);
			if ($tz_trim == $timezone) {
				$timez = $tz;
				break;
			}
		}

		if (!defined('SENDSTUDIO_SERVERTIMEZONE')) {
			define('SENDSTUDIO_SERVERTIMEZONE', $timez);
		}
		define('SENDSTUDIO_TABLEPREFIX', $tableprefix);

		ob_start();

		$settings_api = $this->GetApi('Settings');

		$settings_details = array();

		$settings_details['DATABASE_UTF8PATCH'] = '1';
		$settings_details['DATABASE_TYPE'] = $db_type_name;
		$settings_details['DATABASE_USER'] = (string)$install->database->dbUser;
		$settings_details['DATABASE_PASS'] = (string)$install->database->dbPass;
		$settings_details['DATABASE_HOST'] = (string)$install->database->dbServer;
		$settings_details['DATABASE_NAME'] = (string)$install->database->dbDatabase;
		$settings_details['TABLEPREFIX'] = $tableprefix;
		$settings_details['LICENSEKEY'] = (string)$install->licenseKey;
		$settings_details['APPLICATION_URL'] = (string)$install->installPath;
		$settings_details['SERVERTIMEZONE'] = $timez;
		$settings_details['DEFAULTCHARSET'] = 'UTF-8';
		$settings_details['EMAIL_ADDRESS'] = (string)$install->user->email;

		// now for the default settings.
		$settings_details['SMTP_PORT'] = '25';

		$settings_details['IPTRACKING'] = '1';

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

		$settings_details['BOUNCE_IMAP'] = '0';

		$settings_details['ALLOW_EMBEDIMAGES'] = '1';

		$settings_details['ATTACHMENT_SIZE'] = '2048';

		$settings_details['CRON_SEND'] = '5';
		$settings_details['CRON_AUTORESPONDER'] = '10';
		$settings_details['CRON_BOUNCE'] = '60';

		$settings_details['EMAILSIZE_WARNING'] = '500';
		$settings_details['EMAILSIZE_MAXIMUM'] = '2048';

		$settings_details['RESEND_MAXIMUM'] = '3';

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

		$settings_api->Db = &$db;
		$settings_api->Save();

		// ----- Update the default user account
			$username     = $install->user->username;
			$unique_token = API_USERS::generateUniqueToken($username);
			$new_password = API_USERS::generatePasswordHash($install->user->password, $unique_token);

			$tempServerTimeZone = $db->Quote($settings_details['SERVERTIMEZONE']);
			$tempEmailAddress = $db->Quote(strval($install->user->email));
			$tempUniqueToken = $db->Quote($unique_token);
			$tempUsername = $db->Quote($username);
			$tempPassword = $db->Quote($new_password);
			$tempHTMLFooter = $db->Quote(GetLang('Default_Global_HTML_Footer', ''));
			$tempTEXTFooter = $db->Quote(GetLang('Default_Global_Text_Footer', ''));

			$query = "
				UPDATE {$tableprefix}users
				SET unique_token = '{$tempUniqueToken}',
					usertimezone = '{$tempServerTimeZone}',
					emailaddress ='{$tempEmailAddress}',
					textfooter ='{$tempTEXTFooter}',
					htmlfooter ='{$tempHTMLFooter}',
					username = '******',
					password ='******'
				WHERE userid = 1
			";

			$db->Query($query);

			unset($tempTEXTFooter);
			unset($tempHTMLFooter);
			unset($tempPassword);
			unset($tempUniqueToken);
			unset($tempEmailAddress);
			unset($tempServerTimeZone);

			unset($new_password);
			unset($unique_token);
		// -----

		ob_end_clean();

		/**
		* Installation is finished
		*/

		$this->PrintHeader();
		?>
			<status>OK</status>
			<installPath><?php echo $install->installPath; ?></installPath>
			<user>
				<username>admin</username>
				<password><?php echo $install->user->password; ?></password>
			</user>
		<?php
		$this->PrintFooter();
		return;
	}
 /**
  * Checks to see if the application has any upgrades that need to be run.
  *
  * @return bool
  */
 public static final function hasUpgrade()
 {
     $db = IEM::getDatabase();
     // if there is no database yet, return false
     if (!$db) {
         return false;
     }
     $res = $db->Query('SELECT * FROM [|PREFIX|]settings;');
     if (!$res) {
         return false;
     }
     $settings = $db->Fetch($res);
     $newVersion = (int) self::DATABASE_VERSION;
     $oldVersion = (int) $settings['database_version'];
     return $newVersion > $oldVersion;
 }
Exemple #23
0
/**
* GetLogSystem
* Gets the log system set up with the appropriate options ready for the error handler to use.
*
* @uses IEM::getDatabase()
* @uses Interspire_Log
* @see set_error_handler
*/
function GetLogSystem()
{
    static $logsystem = null;
    if (is_null($logsystem)) {
        if (!class_exists('Interspire_Log', false)) {
            $logsystem = false;
            return false;
        }
        $logsystem = new Interspire_Log(true, false);
        $db = IEM::getDatabase();
        $logsystem->SetLogTypes(array('sql', 'php'));
        $logsystem->SetDb($db);
        $logsystem->SetSeverities('all');
        $logsystem->SetGeneralLogSize(5000);
    }
    return $logsystem;
}
 /**
  * Retrieves the amount of credit used in total by the current user.
  * 
  * @return int
  */
 public function getUsedCredit()
 {
     $db = IEM::getDatabase();
     $query = "\n\t\t\t\tSELECT\n\t\t\t\t\t\tSUM(htmlrecipients+textrecipients+multipartrecipients)\n\t\t\t\tFROM\n\t\t\t\t\t\t[|PREFIX|]stats_newsletters\n\t\t\t\tWHERE\n\t\t\t\t\t\tsentby  = {$this->userid} AND\n\t\t\t\t\t\tstarttime != 0\n\t\t";
     $result = $db->Query($query);
     if (!$result) {
         trigger_error(mysql_error(), E_USER_WARNING);
     }
     $credits = (int) $db->FetchOne($result);
     $db->FreeResult($result);
     //Add on credits for triggers, autoresponders, and manual adjustments (@TODO manual adjustments)
     $query = "\n\t\t\t\tSELECT\n\t\t\t\t\t\tSUM(credit)\n\t\t\t\tFROM\n\t\t\t\t\t\t[|PREFIX|]user_credit\n\t\t\t\tWHERE\n\t\t\t\t\t\tuserid = {$this->userid} AND\n\t\t\t\t\t\ttransactiontype != 'send_campaign'\n\t\t";
     $result = $db->Query($query);
     if (!$result) {
         trigger_error(mysql_error(), E_USER_WARNING);
     }
     $add_credits = (int) $db->FetchOne($result);
     if ($add_credits > 0) {
         $credits += $add_credits;
     } else {
         if ($add_credits < 0) {
             $credits -= $add_credits;
         }
     }
     $db->FreeResult($result);
     return $credits;
 }
	/**
	* Process
	* Works out what you're trying to do and takes appropriate action.
	* Checks to make sure you have access to import subscribers before anything else.
	*
	* @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 GetUser
	* @see User_API::HasAccess
	* @see ChooseList
	* @see ImportSubscribers_Step2
	* @see FileGetLine
	* @see ImportSubscriberLine
	* @see PrintStatusReport
	* @see LinkFields
	*
	* @return Void Prints out the step, doesn't return anything.
	*/
	function Process($action=null)
	{
		$user = GetUser();

		$this->PrintHeader(false, false, false);

		if (!is_null($action)) {
			$action = strtolower($action);
		}

		switch ($action) {
			case 'view_report':
				$importresults = IEM::sessionGet('ImportResults');

				$report_type = (isset($_GET['ReportType'])) ? strtolower($_GET['ReportType']) : null;
				switch ($report_type) {
					case 'duplicates':
						$GLOBALS['Heading'] = GetLang('ImportResults_Report_Duplicates_Heading');
						$GLOBALS['Intro'] = GetLang('ImportResults_Report_Duplicates_Intro');
						$email_list = '';
						foreach ($importresults['duplicateemails'] as $p => $email) {
							$email_list .= htmlspecialchars(trim($email), ENT_QUOTES, SENDSTUDIO_CHARSET) . "\n";
						}
						$GLOBALS['EmailList'] = $email_list;
					break;

					case 'unsubscribes':
						$GLOBALS['Heading'] = GetLang('ImportResults_Report_Unsubscribed_Heading');
						$GLOBALS['Intro'] = GetLang('ImportResults_Report_Unsubscribed_Intro');
						$email_list = '';
						foreach ($importresults['unsubscribedemails'] as $p => $email) {
							$email_list .= htmlspecialchars(trim($email), ENT_QUOTES, SENDSTUDIO_CHARSET) . "\n";
						}
						$GLOBALS['EmailList'] = $email_list;
					break;

					case 'bans':
						$GLOBALS['Heading'] = GetLang('ImportResults_Report_Banned_Heading');
						$GLOBALS['Intro'] = GetLang('ImportResults_Report_Banned_Intro');
						$email_list = '';
						foreach ($importresults['bannedemails'] as $p => $email) {
							$email_list .= htmlspecialchars(trim($email), ENT_QUOTES, SENDSTUDIO_CHARSET) . "\n";
						}
						$GLOBALS['EmailList'] = $email_list;
					break;

					case 'failures':
						$GLOBALS['Heading'] = GetLang('ImportResults_Report_Failures_Heading');
						$GLOBALS['Intro'] = GetLang('ImportResults_Report_Failures_Intro');
						$email_list = '';
						foreach ($importresults['failedemails'] as $p => $email) {
							$email_list .= htmlspecialchars(trim($email), ENT_QUOTES, SENDSTUDIO_CHARSET) . "\n";
						}
						$GLOBALS['EmailList'] = $email_list;
					break;

					case 'bads':
						$GLOBALS['Heading'] = GetLang('ImportResults_Report_Bads_Heading');
						$GLOBALS['Intro'] = GetLang('ImportResults_Report_Bads_Intro');
						$email_list = '';
						foreach ($importresults['baddata'] as $p => $badline) {
							$email_list .= htmlspecialchars($badline, ENT_QUOTES, SENDSTUDIO_CHARSET) . "\n";
						}
						$GLOBALS['EmailList'] = $email_list;
					break;

					default:
						$GLOBALS['Heading'] = GetLang('ImportResults_Report_Invalid_Heading');
						$GLOBALS['Intro'] = GetLang('ImportResults_Report_Invalid_Intro');
						$GLOBALS['EmailList'] = GetLang('InvalidReportURL');
					break;
				}
				$this->ParseTemplate('Subscribers_Import_Results_View');
			break;

			case 'step2':
				$listid = (isset($_POST['list'])) ? (int)$_POST['list'] : (int)$_GET['list'];

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

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

				$importinfo = array();
				$importinfo['List'] = $listid;
				IEM::sessionSet('ImportInfo', $importinfo);
				$importresults = array(
					'duplicates' => 0,
					'success' => 0,
					'updates' => 0,
					'failures' => 0,
					'unsubscribes' => 0,
					'bans' => 0,
					'bads' => 0,
					'duplicateemails' => array(),
					'unsubscribedemails' => array(),
					'failedemails' => array(),
					'bannedemails' => array(),
					'baddata' => array()
				);
				IEM::sessionSet('ImportResults', $importresults);
				$this->ImportSubscribers_Step2();
			break;

			case 'step3':
				if (empty($_POST)) {
					$this->ImportSubscribers_Step2(GetLang('FileNotUploadedSuccessfully_TooBig'));
					break;
				}

				$importinfo = IEM::sessionGet('ImportInfo');
				$importinfo['Status'] = $_POST['status'];
				$importinfo['Confirmed'] = $_POST['confirmed'];
				$importinfo['Format'] = $_POST['format'];
				$importinfo['Type'] = $_POST['importtype'];
				$importinfo['Overwrite'] = (isset($_POST['overwrite'])) ? 1 : 0;
				$importinfo['Autoresponder'] = (isset($_POST['autoresponder'])) ? 1 : 0;
				$importinfo['Headers'] = (isset($_POST['headers'])) ? 1 : 0;
				$importinfo['FieldEnclosed'] = (isset($_POST['fieldenclosed'])) ? $_POST['fieldenclosed'] : false;
				$importinfo['FieldSeparator'] = $_POST['fieldseparator'];

				IEM::sessionSet('ImportInfo', $importinfo);

				$upload_status = false;

				switch (strtolower($importinfo['Type'])) {
					case 'file':
						$upload_status = $this->HandleImportFile();
					break;
				}

				if ($upload_status) {
					$this->LinkFields();
				}
			break;

			case 'step4':
				$linkfields = IEM::requestGetPOST('LinkField', array());

				if (!in_array('E', $linkfields)) {
					$GLOBALS['Error'] = GetLang('EmailAddressNotLinked');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->LinkFields();
					break;
				}

				$importinfo = IEM::sessionGet('ImportInfo');

				$requiredFieldNames = array();
				if (isset($importinfo['RequiredFields']) && is_array($importinfo['RequiredFields'])) {
					foreach ($importinfo['RequiredFields'] as $requiredFieldID => $requiredFieldName) {
						if (!in_array($requiredFieldID, $linkfields)) {
							$requiredFieldNames[] = $requiredFieldName;
							break;
						}
					}
				}

				if (!empty($requiredFieldNames)) {
					$GLOBALS['Error'] = sprintf(GetLang('RequireFieldNotLinked'), htmlspecialchars(implode(', ', $requiredFieldNames), ENT_QUOTES, SENDSTUDIO_CHARSET) );
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->LinkFields();
					break;
				}

				$importinfo['LinkFields'] = $linkfields;
				IEM::sessionSet('ImportInfo', $importinfo);

				$GLOBALS['ImportTotalSubscribers'] = $importinfo['TotalSubscribers'];
				$GLOBALS['ImportTotalSubscribersMessage'] = $this->PrintStatusReport(true);
				$this->ParseTemplate('Subscribers_Import_Step4');
			break;

			case 'importiframe':
				$this->PrintHeader(false, false, false);

				$importresults = IEM::sessionGet('ImportResults');
				$importinfo = IEM::sessionGet('ImportInfo');

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

				$GLOBALS['ProgressTitle'] = GetLang('ImportResults_InProgress');
				$GLOBALS['ProgressMessage'] = sprintf(GetLang('ImportResults_InProgress_Message'), $this->FormatNumber($importinfo['TotalSubscribers']));
				$GLOBALS['ProgressReport'] = $report;
				$GLOBALS['ProgressURLAction'] = 'index.php?Page=Subscribers&Action=Import&SubAction=Import';

				$this->ParseTemplate('ProgressReport_Popup');
				$this->PrintFooter(true);
			break;

			case 'import':
				$totalProcessed = null;
				$percentProcessed = 0;

				$importinfo = IEM::sessionGet('ImportInfo');
				$subscriber_info = false;

				switch (strtolower($importinfo['Type'])) {
					case 'file':
							$filename = array_shift($importinfo['FileList']);
							$subscriber_info = $this->FileGetLine(IEM_STORAGE_PATH . '/import' . "/{$filename}", true);

							if (is_file(IEM_STORAGE_PATH . '/import' . '/' . $filename)) {
								unlink(IEM_STORAGE_PATH . '/import' . '/' . $filename);
							}
					break;
				}

				$db = IEM::getDatabase();

				IEM::sessionSet('ImportInfo', $importinfo);

				if ($subscriber_info) {
					foreach ($subscriber_info as $pos => $details) {
						$importresults = IEM::sessionGet('ImportResults');

						// we don't want to import the headers!
						if ($importinfo['Headers'] && $details == $importinfo['ImportList']) {
							continue;
						}

						/*
						 * Checks to make sure there an equal amount of data columns to header columns.
						 * Erros are produced if not.
						 */
						if (sizeof($details) != sizeof($importinfo['ImportList'])) {
                            // to many
							if (sizeof($details) > sizeof($importinfo['ImportList'])) {
								$importresults['bads']++;
								$importresults['baddata'][] = implode($importinfo['FieldSeparator'], $details) . GetLang('InvalidSubscriberImportLine_TooMany');
                            // too little
							} else {
								$importresults['bads']++;
								$importresults['baddata'][] = implode($importinfo['FieldSeparator'], $details) . GetLang('InvalidSubscriberImportLine_NotEnough');
							}

							// actually set the errors
							IEM::sessionSet('ImportResults', $importresults);

							continue;
						}

						/*
						 * Do the importing of the details. This includes checking the validity
						 * of individual column data.
						 */
						$db->StartTransaction();
						$this->ImportSubscriberLine($details);
						$db->CommitTransaction();

						// Calculate total records processed so far
						if (is_null($totalProcessed)) {
							$totalProcessed = 0;
							
							foreach (array('success', 'updates', 'duplicates', 'failures', 'bans', 'unsubscribes', 'bads') as $key) {
								$totalProcessed += $importresults[$key];
							}
						} else {
							++$totalProcessed;
						}

						// Caclulate the percentage completed
						$percentProcessed = ceil(($totalProcessed / $importinfo['TotalSubscribers'])*100);

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

						// Update the status
						echo "<script>\n";
						echo sprintf("self.parent.UpdateStatusReport('%s');", $report);
						echo sprintf("self.parent.UpdateStatus('%s', %d);", '', $percentProcessed);
						echo "</script>\n";
						
						flush();
					}

					?>
						<script defer>
							setTimeout('window.location="index.php?Page=Subscribers&Action=Import&SubAction=Import&x=<?php echo rand(1,50); ?>;"', 10);
						</script>
					<?php

					exit();
				}

				?>
					<script>
						self.parent.parent.location = 'index.php?Page=Subscribers&Action=Import&SubAction=PrintReport';
					</script>
				<?php

				exit();
			break;

			case 'printreport':
				$this->PrintFinalReport();
			break;

			default:
				$this->ChooseList('Import', 'Step2');
			break;
		}
	}
 /**
  * Save record
  * 
  * This method will create/edit record in the database
  *
  * NOTE: You can pass in an associative array or "record" object.
  *
  * NOTE: The action that is taken by the API (either create a new record or edit an existing one)
  * will depends on the record that is passed in (ie. They have their primary key included or not)
  *
  * NOTE: The method will be able to transform the record passed in, by either adding new default value
  * (or in the case of creating new record, a new id)
  *
  * @param array|baseRecord $record Record to be saved
  * @return boolean Returns TRUE if successful, FALSE otherwise
  *
  * @todo ALL
  */
 public function saveRecord(&$record)
 {
     $db = IEM::getDatabase();
     if (!isset($record['groupid'])) {
         $record['groupid'] = 0;
     } else {
         $record['groupid'] = intval($record['groupid']);
     }
     if (isset($record['permissions']['system']) && is_array($record['permissions']['system']) && in_array('system', $record['permissions']['system'])) {
         $record['systemadmin'] = '1';
     }
     $main_record = $record;
     // permissions don't exist on the main record
     if (isset($main_record['permissions'])) {
         unset($main_record['permissions']);
     }
     // access doesn't exist on the main record
     if (isset($main_record['access'])) {
         unset($main_record['access']);
     }
     $obj = new record_UserGroups($main_record);
     $main_record = $obj->getAssociativeArray();
     $db->StartTransaction();
     /*
      * Save main usergroup record
      */
     if (empty($main_record['groupid'])) {
         unset($main_record['groupid']);
         $main_record['createdate'] = time();
         $fields = array();
         $values = array();
         foreach ($main_record as $key => $value) {
             $fields[] = $key;
             if (is_null($value) || $value === '') {
                 $values[] = 'NULL';
             } elseif (is_numeric($value)) {
                 $values[] = $value;
             } else {
                 $values[] = "'" . $db->Quote($value) . "'";
             }
         }
         $query = "INSERT INTO [|PREFIX|]usergroups(" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")";
         if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
             $query .= " RETURNING groupid";
         }
         $status = $db->Query($query);
         if (!$status) {
             $db->RollbackTransaction();
             trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Unable to insert record: ' . $db->Error(), E_USER_WARNING);
             return false;
         }
         $new_id = 0;
         if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
             $new_id = $db->FetchOne($status, 'groupid');
             $db->FreeResult($status);
         } else {
             $new_id = $db->LastId(SENDSTUDIO_TABLEPREFIX . 'usergroups_sequence');
         }
         $main_record['groupid'] = $record['groupid'] = $new_id;
         $record['createdate'] = $main_record['createdate'];
     } else {
         $id = $main_record['groupid'];
         // hacks to prevent db errors
         unset($main_record['groupid'], $main_record['createdate']);
         // more hacks so that the database doesn't complain about null values when
         // it is expecting an integer
         foreach ($main_record as $colName => &$colVal) {
             if (!$colVal && strpos($colName, 'limit_') === 0) {
                 $colVal = 0;
             }
         }
         $status = $db->UpdateQuery('usergroups', $main_record, "groupid = {$id}", true);
         if (!$status) {
             $db->RollbackTransaction();
             trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Cannot update record: ' . $db->Error(), E_USER_WARNING);
             return false;
         }
     }
     /*
      * Save permissions
      */
     // remove existing permissions since they are being overwritten
     $status = $db->Query("DELETE FROM [|PREFIX|]usergroups_permissions WHERE groupid = {$record['groupid']}");
     // if they weren't able to be deleted, rollback and trigger an error
     if (!$status) {
         $db->RollbackTransaction();
         trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Cannot delete group permission records: ' . $db->Error(), E_USER_WARNING);
         return false;
     }
     // if there are permissions to be saved
     if (!empty($record['permissions'])) {
         $values = array();
         // format them
         foreach ($record['permissions'] as $area => $subarea) {
             foreach ($subarea as $each) {
                 $values[] = $record['groupid'] . ", '" . $db->Quote($area) . "', '" . $db->Quote($each) . "'";
             }
         }
         // remove duplicates
         $values = array_unique($values);
         // insert them
         $status = $db->Query("INSERT INTO [|PREFIX|]usergroups_permissions (groupid, area, subarea) VALUES (" . implode('), (', $values) . ")");
         // rollback and trigger an error if they weren't able to be inserted
         if (!$status) {
             $db->RollbackTransaction();
             trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Cannot save permission records: ' . $db->Error(), E_USER_WARNING);
             return false;
         }
     }
     /*
      * Save access
      */
     // delete all access records first since they are being overwritten
     $status = $db->Query("DELETE FROM [|PREFIX|]usergroups_access WHERE groupid = {$record['groupid']}");
     // if they weren't able to be deleted, rollback and trigger an error
     if (!$status) {
         $db->RollbackTransaction();
         trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Cannot delete group access records: ' . $db->Error(), E_USER_WARNING);
         return false;
     }
     // if there are access permissions
     if (!empty($record['access'])) {
         $values = array();
         // format them
         foreach ($record['access'] as $resourcetype => $resoureid) {
             foreach ($resoureid as $each) {
                 $values[] = $record['groupid'] . ", '" . $db->Quote($resourcetype) . "', " . intval($each);
             }
         }
         // make sure there are no duplicates
         $values = array_unique($values);
         // insert the access permissions
         $status = $db->Query("INSERT INTO [|PREFIX|]usergroups_access (groupid, resourcetype, resourceid) VALUES (" . implode('), (', $values) . ")");
         // if they weren't able to be inserted, rollback and trigger an error
         if (!$status) {
             $db->RollbackTransaction();
             trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Cannot save access records: ' . $db->Error(), E_USER_WARNING);
             return false;
         }
     }
     $db->CommitTransaction();
     return true;
 }
	/**
	* GetDb
	* Sets up the database object for this and the child objects to use.
	* If the Db var is already set up and the connection is a valid resource, this will return true straight away.
	* If the Db var is null or the connection is not valid, it will fetch it and store it for easy reference.
	* If it's unable to setup the database (or it's null or false) it will trigger an error.
	*
	* @see Db
	* @see IEM::getDatabase()
	*
	* @return Boolean True if it works or false if it fails. Failing also triggers a fatal error.
	*/
	function GetDb()
	{
		if (is_object($this->Db) && is_resource($this->Db->connection)) {
			return true;
		}

		if (is_null($this->Db) || !$this->Db->connection) {
			$Db = IEM::getDatabase();
			$this->Db = &$Db;
		}

		if (!is_object($this->Db) || !is_resource($this->Db->connection)) {
			trigger_error('Unable to connect to database', SENDSTUDIO_ERROR_FATAL);
			return false;
		}
		return true;
	}
Exemple #28
0
 public function Admin_Action_Default()
 {
     $db = IEM::getDatabase();
 }
Exemple #29
0
	/**
	 * DbVersionCheck
	 * Checks if the database version is sufficient to upgrade and will not allow upgrades to continue if not.
	 *
	 * @return Void Does not return anything.
	 */
	function DbVersionCheck()
	{
		$db = IEM::getDatabase();
		$version = $db->Version();
		list($error, $msg) = IEM_Installer::DbVersionCheck(SENDSTUDIO_DATABASE_TYPE, $version);
		if (!$error) {
			return;
		}
		// See also admin/index.php for a similar message
		$tpl = GetTemplateSystem();
		$tpl->Assign('title', 'This Upgrade Cannot Proceed');
		$tpl->Assign('msg', '<p>Interspire Email Marketer requires ' . $msg['product'] . ' <em>' . $msg['req_version'] . '</em> or above to work properly. Your server is running <em>' . $msg['version'] . '</em>. To complete the installation, your web host must upgrade ' . $msg['product'] . ' to this version. Please note that this is not a software problem and it is something only your web host can change.</p>');
		$this->PrintHeader();
		$tpl->ParseTemplate('Upgrade_Body');
		$this->PrintFooter();
		exit();
	}
	/**
	* DeleteSubscribers
	* Deletes subscribers from the list. Goes through the subscribers array (passed in) and deletes them from the list as appropriate.
	*
	* @param Array $subscribers A list of subscriber id's to remove from the list.
	*
	* @see GetApi
	* @see Subscribers_API::DeleteSubscriber
	*
	* @return Void Doesn't return anything. Creates a report and prints that out.
	*/
	function DeleteSubscribers($subscribers=array())
	{
		if (!is_array($subscribers)) {
			$subscribers = array($subscribers);
		}

		if (empty($subscribers)) {
			return array(false, GetLang('NoSubscribersToDelete'));
		}
		if (!isset($GLOBALS['Message'])) {
			$GLOBALS['Message'] = '';
		}

		// ----- get jobs running for this user
		$listid = 0;
		if (isset($_POST['lists'])) {
			$listid = $_POST['lists'];
		} elseif (isset($_GET['Lists'])) {
			$listid = $_GET['Lists'];
		} elseif (isset($_POST['list'])) {
			$listid = $_POST['list'];
		} elseif (isset($_GET['List'])) {
			$listid = $_GET['List'];
		}
		if(is_array($listid) && $listid[0] == 'any'){
			$listid = array();
		} else {
			$listid = array(0 => (int) $listid);
		}
		$db = IEM::getDatabase();
		// don't have a specific list? use the subscribers' listid
		if(empty($listid)){
			$query = "SELECT listid FROM [|PREFIX|]list_subscribers WHERE subscriberid IN (".implode(",",$subscribers).")";
			$result = $db->Query($query);
			if(!$result){
				trigger_error(mysql_error()."<br />".$query);
				FlashMessage(mysql_error(), SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
				exit();
			}
			while($row = $db->Fetch($result)){
				$listid[] = $row['listid'];
			}
		}
		
		$jobs_to_check = array();
		
		if(!empty($listid)){
			$query = "SELECT jobid FROM [|PREFIX|]jobs_lists WHERE listid IN (".implode(",",$listid).")";
			$result = $db->Query($query);
			if(!$result){
				trigger_error(mysql_error()."<br />".$query);
				FlashMessage(mysql_error(), SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
				exit();
			}
			while($row = $db->Fetch($result)){
				$jobs_to_check[] = $row['jobid'];
			}
			$db->FreeResult($result);
		}
		
		if(!empty($jobs_to_check)){
			$query = "SELECT jobstatus FROM [|PREFIX|]jobs WHERE jobid IN (" . implode(',', $jobs_to_check) . ")";	
			$result = $db->Query($query);
			if(!$result){
				trigger_error(mysql_error()."<br />".$query);
				FlashMessage(mysql_error(), SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
				exit();
			}
			while($row = $db->Fetch($result)){
				if($row['jobstatus'] != 'c'){
					FlashMessage('Unable to delete contacts from list(s). Please cancel any campaigns sending to the list(s) in order to delete them.', SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
					exit();
				}
			}
			$db->FreeResult($result);
		}
		// -----


		$subscriber_search = IEM::sessionGet('Search_Subscribers');
		$list = $subscriber_search['List'];

		$subscribersdeleted = 0;
		$subscribersnotdeleted = 0;
		$SubscriberApi = $this->GetApi('Subscribers');
		foreach ($subscribers as $p => $subscriberid) {
			list($status, $msg) = $SubscriberApi->DeleteSubscriber(false, 0, $subscriberid);
			if ($status) {
				$subscribersdeleted++;
				continue;
			}
			$subscribersnotdeleted++;
		}

		$msg = '';

		if ($subscribersnotdeleted > 0) {
			if ($subscribersnotdeleted == 1) {
				$GLOBALS['Error'] = GetLang('Subscriber_NotDeleted');
			} else {
				$GLOBALS['Error'] = sprintf(GetLang('Subscribers_NotDeleted'), $this->FormatNumber($subscribersnotdeleted));
			}
			$msg .= $this->ParseTemplate('ErrorMsg', true, false);
		}

		if ($subscribersdeleted > 0) {
			if ($subscribersdeleted == 1) {
				$msg .= $this->PrintSuccess('Subscriber_Deleted');
			} else {
				$msg .= $this->PrintSuccess('Subscribers_Deleted', $this->FormatNumber($subscribersdeleted));
			}
		}
		$GLOBALS['Message'] .= $msg;
	}