Beispiel #1
0
 public static final function init($reset = false)
 {
     $GLOBALS['ApplicationUrl'] = SENDSTUDIO_APPLICATION_URL;
     if (defined('SENDSTUDIO_IS_SETUP') && SENDSTUDIO_IS_SETUP && !InterspireEvent::eventExists('IEM_MARKER_20090701')) {
         IEM_Installer::RegisterEventListeners();
         require_once IEM_ADDONS_PATH . '/interspire_addons.php';
         $addons = new Interspire_Addons();
         $addons->FixEnabledEventListeners();
         InterspireEvent::eventCreate('IEM_MARKER_20090701');
     }
     if (!self::configInit($reset)) {
         return false;
     }
     if (!self::sessionInit($reset)) {
         return false;
     }
     if (!self::userInit($reset)) {
         return false;
     }
     $tempUser = IEM::getCurrentUser();
     $tempUserLanguage = 'default';
     if (!empty($tempUser->user_language) && is_dir(IEM_PATH . "/language/{$tempUser->user_language}")) {
         $tempUserLanguage = $tempUser->user_language;
     }
     require_once IEM_PATH . "/language/{$tempUserLanguage}/whitelabel.php";
     require_once IEM_PATH . "/language/{$tempUserLanguage}/language.php";
     self::$_enableInfoTips = false;
     if (isset($tempUser->infotips) && $tempUser->infotips) {
         self::$_enableInfoTips = true;
     }
     unset($tempUserLanguage);
     unset($tempUser);
 }
Beispiel #2
0
 /**
  * CONSTRUCTOR
  * Override parant's constructor.
  *
  * We will need to check whether or not current user have the correct
  * privilage to use "AdminTools"
  *
  * TODO better PHPDOC
  */
 public function __construct()
 {
     // ----- Make sure that current user is an admin
     $currentUser = IEM::getCurrentUser();
     if (!$currentUser || !$currentUser->isAdmin()) {
         IEM::redirectTo('index');
         return false;
     }
     // -----
     return parent::__construct();
 }
	/**
	* RemoteStats
	* Loads up the language file.
	*
	* @return Void Doesn't return anything.
	*/
	function RemoteStats()
	{
		if (!IEM::getCurrentUser()) {
			if (defined('SENDSTUDIO_APPLICATION_URL') && SENDSTUDIO_APPLICATION_URL !== false) {
				header('Location: ' . SENDSTUDIO_APPLICATION_URL . '/admin/index.php');
			} else {
				header('Location: ../index.php');
			}
			exit;
		}

		$this->LoadLanguageFile('Stats');
	}
Beispiel #4
0
	/**
	* Process
	* Logs you out and redirects you back to the login page.
	*
	* @see Login::Process
	*
	* @return Void Doesn't return anything. Unsets session variables, removes the "remember me" cookie if it's set and redirects you back to the login page.
	*/
	function Process()
	{
		$sessionuser = IEM::getCurrentUser();
		$sessionuser->SaveSettings();
		unset($sessionuser);
		
		IEM::userLogout();
		
		IEM::requestRemoveCookie('IEM_CookieLogin');
		IEM::requestRemoveCookie('IEM_LoginPreference');

		$url = SENDSTUDIO_APPLICATION_URL;
		if (substr($url, -1, 1) != '/') {
			$url .= '/';
		}
		$url .= 'admin/index.php';

		header("Location: {$url}");
		exit();
	}
 /**
  * Initialize the framework
  * @param Boolean $reset Whether or not to re-initialize the framework again
  * @return Boolean Returns TRUE the application initializes without encountering any errors, FALSE otherwise
  */
 public static final function init($reset = false)
 {
     $GLOBALS['ApplicationUrl'] = SENDSTUDIO_APPLICATION_URL;
     // Defining IEM_MARKER in the event is part of the installation procedure
     // If it is not there, we can assume that the stash file has been overwritten
     // So we will need to restore it.
     // TODO change reference to SENSTUDIO_IS_SETUP
     if (defined('SENDSTUDIO_IS_SETUP') && SENDSTUDIO_IS_SETUP && !InterspireEvent::eventExists('IEM_MARKER_20090701')) {
         IEM_Installer::RegisterEventListeners();
         // Restore Addons listeners
         require_once IEM_ADDONS_PATH . '/interspire_addons.php';
         $addons = new Interspire_Addons();
         $addons->FixEnabledEventListeners();
         InterspireEvent::eventCreate('IEM_MARKER_20090701');
     }
     if (!self::configInit($reset)) {
         return false;
     }
     if (!self::sessionInit($reset)) {
         return false;
     }
     if (!self::userInit($reset)) {
         return false;
     }
     // ----- Include common language variables
     $tempUser = IEM::getCurrentUser();
     $tempUserLanguage = 'default';
     if (!empty($tempUser->user_language) && is_dir(IEM_PATH . "/language/{$tempUser->user_language}")) {
         $tempUserLanguage = $tempUser->user_language;
     }
     require_once IEM_PATH . "/language/{$tempUserLanguage}/whitelabel.php";
     require_once IEM_PATH . "/language/{$tempUserLanguage}/language.php";
     self::$_enableInfoTips = false;
     if (isset($tempUser->infotips) && $tempUser->infotips) {
         self::$_enableInfoTips = true;
     }
     unset($tempUserLanguage);
     unset($tempUser);
     // -----
 }
Beispiel #6
0
	/**
	* PrintEditForm
	* Prints the editing form for the userid passed in.
	* If the user doesn't have access to edit their details, it will only display them.
	* Also makes sure that the user doesn't try to edit another users' details.
	*
	* @param Int $userid UserID to show the form for. This will load up the user and use their details as the defaults.
	*
	* @see User_API::Admin
	* @see GetLang
	* @see GetUser
	*
	* @return Void Doesn't return anything, prints out the appropriate form and that's it.
	*/
	function PrintEditForm($userid=0)
	{
		$thisuser = IEM::getCurrentUser();
		if (!$thisuser->Admin()) {
			if ($userid != $thisuser->userid) {
				$this->DenyAccess();
			}
		}

		$user = GetUser($userid);

		$activity = $user->GetEventActivityType();
		if (!is_array($activity)) {
			$activity = array();
		}
		$GLOBALS['EventActivityType'] = implode("\n", $activity);

		$GLOBALS['UserID'] = $user->userid;
		$GLOBALS['UserName'] = $user->username;
		$GLOBALS['FullName'] = $user->fullname;
		$GLOBALS['EmailAddress'] = $user->emailaddress;

		$GLOBALS['TextFooter'] = $user->textfooter;
		$GLOBALS['HTMLFooter'] = $user->htmlfooter;

		$GLOBALS['CustomSmtpServer_Display'] = '0';

		if ($user->HasAccess('User', 'SMTP')) {
			$GLOBALS['SmtpServer'] = $user->Get('smtpserver');
			$GLOBALS['SmtpUsername'] = $user->Get('smtpusername');
			$GLOBALS['SmtpPassword'] = $user->Get('smtppassword');
			$GLOBALS['SmtpPort'] = $user->Get('smtpport');
			$smtp_access = true;
		} else {
			$GLOBALS['SmtpServer'] = '';
			$GLOBALS['SmtpUsername'] = '';
			$GLOBALS['SmtpPassword'] = '';
			$GLOBALS['SmtpPort'] = '';
			$smtp_access = false;
		}

		$GLOBALS['ShowSMTPInfo'] = 'none';
		$GLOBALS['DisplaySMTP'] = '0';

		if ($smtp_access) {
			$GLOBALS['ShowSMTPInfo'] = '';
		}

		if ($GLOBALS['SmtpServer']) {
			$GLOBALS['CustomSmtpServer_Display'] = '1';
			if ($smtp_access) {
				$GLOBALS['DisplaySMTP'] = '1';
			}
		}

		if ($user->Get('usewysiwyg')) {
			$GLOBALS['UseWysiwyg'] = ' CHECKED';
			$GLOBALS['UseXHTMLDisplay'] = ' style="display:block;"';
		} else {
			$GLOBALS['UseXHTMLDisplay'] = ' style="display:none;"';
		}

		if ($user->Get('enableactivitylog')) {
			$GLOBALS['EnableActivityLog'] = ' CHECKED';
		} else {
			$GLOBALS['EnableActivityLog'] = '';
		}

		$GLOBALS['UseXHTMLCheckbox'] = $user->Get('usexhtml')? ' CHECKED' : '';

		$GLOBALS['FormAction'] = 'Action=Save&UserID=' . $user->userid;

		$timezone = $user->usertimezone;
		$GLOBALS['TimeZoneList'] = $this->TimeZoneList($timezone);

		$GLOBALS['InfoTipsChecked'] = ($user->InfoTips()) ? ' CHECKED' : '';

		if ($smtp_access && $user->HasAccess('User', 'SMTPCOM')) {
		} else {
			$GLOBALS['ShowSMTPCOMOption'] = 'none';
		}
		$GLOBALS['googlecalendarusername'] = $user->googlecalendarusername;
		$GLOBALS['googlecalendarpassword'] = $user->googlecalendarpassword;

		if ($thisuser->EditOwnSettings()) {
			$this->ParseTemplate('User_Edit_Own');
		} else {
			$this->ParseTemplate('User_Display_Own');
		}
	}
 /**
  * IEM_Menu
  * This builds both the nav menu (with the dropdown items) and the text menu links at the top
  * It gets the main nav items from SendStudio_Functions::GenerateMenuLinks
  * It gets the text menu items from SendStudio_Functions::GenerateTextMenuLinks
  *
  * It will also see if test-mode is enabled (and display an appropriate message)
  * and also generate the right headers at the top (user is logged in as 'X', the current time is 'Y' etc).
  *
  * <b>Do *not* put any "ParseTemplate" calls inside IEM_Menu as you will cause an infinite loop.</b>
  * "ParseTemplate" calls "IEM_Menu" via IEM_DefaultVariables
  * Since the header menu has not yet finished building (ie the $menu variable is still null),
  * calling IEM_Menu at this stage will then call ParseTemplate (which then calls IEM_Menu).
  *
  * It returns an array:
  * - the first item is the main nav menu (contact lists, contacts, email campaigns etc)
  * - the second item is the text menu links at the top of the page (templates, users/manage account, logout etc)
  *
  * @uses SendStudio_Functions::GenerateMenuLinks
  * @uses SendStudio_Functions::GenerateTextMenuLinks
  *
  * @return Array Returns an array containing the main nav menu (the first item of the array) and the text menu items (the second item of the array).
  */
 private function IEM_Menu()
 {
     static $menu = null;
     // we've already built the menu? just return it.
     if ($menu !== null) {
         return $menu;
     }
     // see if there is an upgrade required or problem with the lk.
     if (!isset($_GET['Page']) || strtolower($_GET['Page']) != 'upgradenx') {
         if (IEM::sessionGet('LicenseError')) {
             if (!isset($_GET['Page']) || strtolower($_GET['Page']) != 'settings') {
                 header('Location: index.php?Page=Settings');
                 exit;
             }
         }
     }
     $user = IEM::getCurrentUser();
     // we're not logged in? we don't have a menu so just return empty items.
     if (!$user) {
         $menu = array('', '');
         return $menu;
     }
     $textlinks = SendStudio_Functions::GenerateTextMenuLinks();
     $nav_menus = '';
     if (!IEM::sessionGet('LicenseError')) {
         $nav_menus = SendStudio_Functions::GenerateMenuLinks();
     }
     $GLOBALS['UsingWYSIWYG'] = '0';
     if ($user->Get('usewysiwyg') == 1) {
         $GLOBALS['UsingWYSIWYG'] = '1';
     }
     $adjustedtime = AdjustTime();
     $GLOBALS['SystemDateTime'] = sprintf(GetLang('UserDateHeader'), AdjustTime($adjustedtime, false, GetLang('UserDateFormat'), true), $user->Get('usertimezone'));
     $name = $user->Get('username');
     $fullname = $user->Get('fullname');
     if ($fullname != '') {
         $name = $fullname;
     }
     $GLOBALS['UserLoggedInAs'] = sprintf(GetLang('LoggedInAs'), htmlentities($name, ENT_QUOTES, SENDSTUDIO_CHARSET));
     $unlimited_total_emails = $user->hasUnlimitedTotalCredit();
     if (!$unlimited_total_emails) {
         $creditUsed = API_USERS::getRecordById($user->userid)->getUsedCredit();
         $creditLeft = (int) $user->group->limit_totalemailslimit - (int) $creditUsed;
         $GLOBALS['TotalEmailCredits'] = sprintf(GetLang('User_Total_CreditsLeft'), SendStudio_Functions::FormatNumber($creditLeft));
     }
     $GLOBALS['MonthlyEmailCredits'] = '';
     $unlimited_monthly_emails = $user->hasUnlimitedMonthlyCredit();
     if (!$unlimited_monthly_emails) {
         $creditUsed = API_USERS::getRecordById($user->userid)->getUsedMonthlyCredit();
         $creditLeft = (int) $user->group->limit_emailspermonth - (int) $creditUsed;
         $GLOBALS['MonthlyEmailCredits'] = sprintf(GetLang('User_Monthly_CreditsLeft'), SendStudio_Functions::FormatNumber($creditLeft), SendStudio_Functions::FormatNumber($user->group->limit_emailspermonth));
         if (!$unlimited_total_emails) {
             $GLOBALS['MonthlyEmailCredits'] .= '&nbsp;&nbsp;|';
         }
     }
     $menu = array($nav_menus, $textlinks);
     return $menu;
 }
	/**
	 * This method will display a "manage user" page
	 *
	 * @return void
	 * @todo phpdocs
	 */
	public function page_manageGroups()
	{
		// ----- Sanitize and declare variables that is going to be used in this function
			$pageRecordPP		= 0;
			$pageCurrentIndex	= $this->GetCurrentPage();
			$pageSortInfo		= $this->GetSortDetails();

			$reqProcessPaging	= IEM::requestGetGET('ProcessPaging', 0, 'intval');

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

			$currentUser		= IEM::getCurrentUser();

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

		// Do we need to process paging?
		if ($reqProcessPaging) {
			$temp = IEM::requestGetGET('PerPageDisplay', 0, 'intval');
			if ($temp) {
				$this->SetPerPage($temp);
			}
		}

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

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

		$recordTotal = API_USERGROUPS::getRecords(true);
		if (!$recordTotal) {
			$recordTotal = 0;
		}

		$records = API_USERGROUPS::getRecords(false, false, $pageRecordPP, $start, $pageSortInfo['SortBy'], ($pageSortInfo['Direction'] == 'desc'));
		if (!$records) {
			$records = array();
		} else {
			for ($i = 0, $j = count($records); $i < $j; ++$i) {
				$records[$i]['processed_CreateDate'] = $this->PrintDate($records[$i]['createdate']);
			}
		}


		// ----- Calculate pagination, this is using the older method of pagination
			$GLOBALS['PAGE'] = 'UsersGroups';
			$GLOBALS['FormAction'] = 'Action=manageGroups&ProcessPaging=1';

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

		// ----- Print out HTML
			$this->PrintHeader();

			$tpl = GetTemplateSystem();
			$tpl->Assign('PAGE', $page);
			$tpl->Assign('records', $records);

			$tpl->ParseTemplate('UsersGroups_ManageGroups');

			$this->PrintFooter();
		// -----

		return;
	}
Beispiel #9
0
     $newPage = IEM::requestGetGET('page', false);
     $newPage = preg_replace('/[^\\w]/', '_', $newPage);
     if (!is_file(IEM_PATH . "/pages/{$newPage}.class.php")) {
         $newPage = false;
         $page = 'index';
     }
 }
 // --------------------------------------------------------------------------------
 // Check whether or not the request is coming from a user that's already logged in.
 //
 // If the user have not logged in yet, we need to check for "IEM_CookieLogin"
 // and "IEM_LoginPreference" cookie. This cookie is used in "remember me" feature.
 //
 // TODO refactor this to IEM::login() function
 // --------------------------------------------------------------------------------
 if (!IEM::getCurrentUser()) {
     $tempValid = false;
     $tempCookie = false;
     $tempUser = false;
     // This is not a loop, rather a way to "return early" to avoid nested if
     // * Comment from a later developer: If you have to do this, there is
     // * probably a better way to code it. Programming doesn't necessarily
     // * mean "hacking".
     while (true) {
         // if we are installing or upgrading then we need to bypass this
         if (!IEM::isInstalled() && IEM::isInstalling() || IEM::hasUpgrade() && IEM::isUpgrading() || IEM::isCompletingUpgrade()) {
             $tempValid = true;
             break;
         }
         // Get cookie
         $tempCookie = IEM::requestGetCookie('IEM_CookieLogin', array());
Beispiel #10
0
 /**
  * MoveFiles
  * Moves uploaded images from temporary storage under a user's id - to it's final location - under the type and it's id. Eg newsletter/1.
  *
  * @param String $destination The destination (eg newsletter or template).
  * @param Int $id The destinations id.
  *
  * @see CreateDirectory
  * @see list_files
  *
  * @return Boolean Returns false if it can't create the paths or it can't copy the necessary files. Returns true if everything worked ok.
  */
 function MoveFiles($destination = false, $id = 0)
 {
     if (!$destination || !$id) {
         return false;
     }
     $destinationdir = TEMP_DIRECTORY . '/' . $destination . '/' . $id;
     $createdir = CreateDirectory($destinationdir);
     if (!$createdir) {
         return false;
     }
     $user = IEM::getCurrentUser();
     $sourcedir = TEMP_DIRECTORY . '/user/' . $user->userid;
     $file_list = list_files($sourcedir);
     $dir_list = list_directories($sourcedir);
     if (empty($file_list) && empty($dir_list)) {
         return true;
     }
     $result = true;
     foreach ($file_list as $p => $filename) {
         if (!copy($sourcedir . '/' . $filename, $destinationdir . '/' . $filename)) {
             $result = false;
         }
     }
     if ($result) {
         foreach ($dir_list as $dir) {
             $dirname = str_replace($sourcedir, '', $dir);
             if ($dirname == 'attachments') {
                 continue;
             }
             $copy_dir_result = CopyDirectory($dir, $destinationdir . $dirname);
             if (!$copy_dir_result) {
                 $resut = false;
             }
         }
     }
     return $result;
 }
Beispiel #11
0
	/**
	* ManageSubscribers_Step3
	* Prints out the subscribers for the list chosen and criteria selected in steps 1 & 2. This handles sorting, paging and searching. If you are coming in for the first time, it remembers your search criteria in the session. If you change number per page, sorting criteria, it fetches the search criteria from the session again before continuing.
	*
	* @see ManageSubscribers_Step2
	* @see GetApi
	* @see GetPerPage
	* @see GetCurrentPage
	* @see GetSortDetails
	* @see Subscribers_API::FetchSubscribers
	* @see SetupPaging
	* @see Lists_API::Load
	*
	* @return Void Doesn't return anything. Prints out the results and that's it.
	*/
	function ManageSubscribers_Step3($change=false)
	{
		$subscriber_api = $this->GetApi('Subscribers');
		$user = IEM::getCurrentUser();
		$search_info = IEM::sessionGet('Search_Subscribers');

		$this->SetupGoogleCalendar();

		$user_lists = $user->GetLists();

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

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

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

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

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

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

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

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

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

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

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

			$search_details['CustomFields'] = $customfields;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		$sortinfo = $this->GetSortDetails();

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

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

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

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

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

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

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

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

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


		$DisplayPage = $pageid;

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

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

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

		$subscriberdetails = '';

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

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

		$loaded_customfields = array();

		$customfields = array();

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

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

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

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

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

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

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

			$search_info['List'] = $usedLists;

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

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

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

				$GLOBALS['ColumnCount'] = 3;

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

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

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

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

		$GLOBALS['SubscribersManage'] = $title;

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

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

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

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

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

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

					$visiblefields[] = $key;
				}
			}

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

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

		$customfield_data = array();

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

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

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

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

					$loaded_customfields[$name] = $subfield;

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

		echo $template;
	}
Beispiel #12
0
	/**
	* SelectNewsletter
	* Displays a list of newsletters you can send.
	* Only gets live newsletters.
	* If cron scheduling is enabled, then you get extra options to choose from (whether to notify the owner and of course what time to send the newsletter).
	* You can also choose the character set for the send to use.
	*
	* @see GetApi
	* @see Newsletters_API::GetLiveNewsletters
	* @see CreateDateTimeBox
	* @see CharsetList
	* @see SENDSTUDIO_CRON_ENABLED
	*
	* @return Void Doesn't return anything, prints out the step where you select the newsletter you want to send to your list(s).
	*/
	function SelectNewsletter($errormsg=false)
	{
		$send_details = IEM::sessionGet('SendDetails');
		$user = IEM::getCurrentUser();
		$newsletterapi = $this->GetApi('Newsletters');

		$sendsize = $send_details['SendSize'];
		if ($sendsize == 1) {
			$sendSizeInfo = GetLang('SendSize_One');
		} else {
			$sendinfo = IEM::sessionGet('SendInfoDetails');
			$sendSizeInfo = $sendinfo['Msg'];
		}

		if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
			$sendSizeInfo .= sprintf(' <a href="javascript:void(0)" onClick="alert(\'%s\')">%s</a>', GetLang('ReadMoreWhyApprox'), GetLang('ReadMore'));
		}

		$GLOBALS['Message'] = '';

		if (!IEM::sessionGet('MyError')) {
			$GLOBALS['Success'] = $sendSizeInfo;
			$GLOBALS['Message'] = $this->ParseTemplate('SuccessMsg', true, false);
		}

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

		if (IEM::sessionGet('MyError')) {
			$GLOBALS['Message'] .= IEM::sessionGet('MyError') . IEM::sessionGet('ExtraMessage');
		}

		$newsletterowner = ($user->Admin() ? 0 : $user->userid);

		$newsletters = $newsletterapi->GetLiveNewsletters($newsletterowner);
		$newsletterlist = '';
		$count = sizeof(array_keys($newsletters));
		$newsletterlist = '<option value="0">' . GetLang('SelectNewsletterToSend') . '</option>';

		foreach ($newsletters as $pos => $newsletterinfo) {
			$chosen = '';
			if ($newsletterinfo['newsletterid'] == $send_details['NewsletterChosen']) {
				$chosen = ' SELECTED';
			}
			$newsletterlist .= '<option value="' . $newsletterinfo['newsletterid'] . '"' . $chosen . '>' . htmlspecialchars($newsletterinfo['name'], ENT_QUOTES, SENDSTUDIO_CHARSET) . '</option>';
		}

		$list = $send_details['Lists'][0]; // always choose the first list. doesn't matter if there are multiple lists to choose from.
		$listapi = $this->GetApi('Lists');
		$listapi->Load($list);

		$customfields = $listapi->GetCustomFields($send_details['Lists'], 'text');

		if (empty($customfields)) {
			$GLOBALS['DisplayNameOptions'] = 'none';
		} else {
			$GLOBALS['NameOptions'] = '';
			foreach ($customfields as $p => $details) {
				$GLOBALS['NameOptions'] .= "<option value='" . $details['fieldid'] . "'>" . htmlspecialchars($details['name'], ENT_QUOTES, SENDSTUDIO_CHARSET) . "</option>";
			}
		}

		$GLOBALS['SendFromEmail'] = $listapi->Get('owneremail');
		$GLOBALS['SendFromName'] = $listapi->Get('ownername');
		$GLOBALS['ReplyToEmail'] = $listapi->Get('replytoemail');
		$GLOBALS['BounceEmail'] = $listapi->Get('bounceemail');

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

		if ($user->HasAccess('Lists', 'BounceSettings')) {
			$GLOBALS['ShowBounceInfo'] = '';
		}

		$GLOBALS['SendCharset'] = SENDSTUDIO_CHARSET;

		$GLOBALS['SendTimeBox'] = $this->CreateDateTimeBox(0, false, 'datetime', true);

		$GLOBALS['NewsletterList'] = $newsletterlist;

		$GLOBALS['DisplayEmbedImages'] = 'none';
		if (SENDSTUDIO_ALLOW_EMBEDIMAGES) {
			$GLOBALS['DisplayEmbedImages'] = '';
			if (SENDSTUDIO_DEFAULT_EMBEDIMAGES) {
				$GLOBALS['EmbedImages'] = ' CHECKED';
			}
		}

		$cron_options = '';
		if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
			$cron_options = $this->ParseTemplate('Send_Step3_Cron', true);
		}
		$GLOBALS['CronOptions'] = $cron_options;


		if (check('send', $user->Admin(), $list) && (!SENDSTUDIO_CRON_ENABLED || SENDSTUDIO_CRON_SEND == 0)) {
			if ($user->Admin()) {
				$NoCronMessage = 'Send_NoCronEnabled_Explain_Admin';
			} else {
				$NoCronMessage = 'Send_NoCronEnabled_Explain_NotAdmin';
			}

			$GLOBALS['NoCronMessage'] = $this->PrintWarning($NoCronMessage);
		}

		if (check('TrackThisSend', 'enabled')) {
			if ($this->GetApi('module_TrackerFactory', false)) {
				$trackerOptions = module_Tracker::GetDisplayOptionsForAllTracker();
				$GLOBALS['TrackerOptions'] = implode('', $trackerOptions);
			}
		}

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

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

		$this->DisplayCronWarning();

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

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

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

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

		} else {

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

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

		$GLOBALS['PreviewID'] = $autoresponderid;

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

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

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

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

		$session_autoresponder['contents'] = $autorespondercontents;

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

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

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

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

		$tpl->ParseTemplate('Autoresponder_Form_Step4');
	}
Beispiel #14
0
	/**
	* ExportSubscribers_Step3
	* Checks that there are subscribers to export. Creates a 'queue' of subscribers to export and lets you choose which fields you want to export.
	*
	* @see GetApi
	* @see Lists_API::Load
	* @see Lists_API::GetCustomFields
	* @see GetSortDetails
	* @see Subscribers_API::GetSubscribers
	* @see ExportSubscribers_Step2
	* @see API::CreateQueue
	*
	* @return Void Prints out the form, doesn't return anything.
	*/
	function ExportSubscribers_Step3()
	{
		$subscriber_api = $this->GetApi('Subscribers');
		$user = IEM::getCurrentUser();
		$exportinfo = IEM::sessionGet('ExportInfo');

		$listApi = $this->GetApi('Lists');
		$listid = $exportinfo['List'];
		$CustomFieldsList = array();

		if (is_numeric($listid)) {
			$listApi->Load($listid);
			$listname = $listApi->name;
			$GLOBALS['List'] = $listid;
			$GLOBALS['Heading'] = GetLang('Subscribers_Export');
			$CustomFieldsList = $listApi->GetCustomFields($listid);
		} elseif (is_array($listid)) {
			// Load list name for each of the selected mailing list
			$listnames = array();
			$eachCustomFieldList = array();
			foreach ($listid as $id) {
				if ($listApi->Load($id)) {
					array_push($listnames, $listApi->name);
					$eachCustomFieldList = $listApi->getCustomFields($id);
					$CustomFieldsList = array_merge($CustomFieldsList, $eachCustomFieldList);
				}
			}
			$GLOBALS['List'] = implode('&Lists[]=',$listid);
			$GLOBALS['Heading'] = sprintf(GetLang('Subscribers_Export_MultipleList'), htmlspecialchars("'".implode("', '", $listnames)."'", ENT_QUOTES, SENDSTUDIO_CHARSET));
		} else {
			$GLOBALS['List'] = $listid;
			$GLOBALS['Heading'] = GetLang('Subscribers_Export_AnyList');
		}

		if (!$exportinfo || !empty($_POST)) {
			$export_details = array();
			if (isset($_POST['emailaddress']) && $_POST['emailaddress'] != '') {
				$export_details['Email'] = $_POST['emailaddress'];
			}

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

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

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

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

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

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

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

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

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

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

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

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

			$export_details['CustomFields'] = $customfields;

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

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

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

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

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

			$export_details['List'] = $listid;

			$exportinfo['ExportDetails'] = $export_details;

			$exportinfo['ExportsCompleted'] = 0;

			IEM::sessionSet('ExportInfo', $exportinfo);
		}

		$exportinfo = IEM::sessionGet('ExportInfo');
		$export_details = $exportinfo['ExportDetails'];

		if (isset($exportinfo['ExportQueue'])) {
			$queueid = $exportinfo['ExportQueue'];
			if ($queueid && is_array($queueid)) {
				foreach($queueid as $id) {
					$subscriber_api->ClearQueue($id['queueid'], 'export');
				}
			}
		}

		/**
		 * Get export queueIDs
		 */
			$exportqueue = array();
			if(is_numeric($export_details['List'])) {
				array_push($exportqueue, array(	'queueid' 	=> $subscriber_api->CreateQueue('Export'),
												'listid' 	=> $export_details['List']));
			} elseif(is_array($export_details['List'])) {
				foreach($export_details['List'] as $listid) {
					array_push($exportqueue, array(	'queueid' 	=> $subscriber_api->CreateQueue('Export'),
													'listid' 	=> $listid));
				}
			} else {
				$user_lists = $user->GetLists();
				foreach($user_lists as $listid=>$each) {
					array_push($exportqueue, array(	'queueid' 	=> $subscriber_api->CreateQueue('Export'),
													'listid' 	=> $listid));
				}
			}
			$exportinfo['ExportQueue'] = $exportqueue;
		/**
		 * -----
		 */

		/**
		 * Put subscribers into queue
		 */
			$totalsubscribers = 0;
			$tempExportDetails = $export_details;
			foreach($exportinfo['ExportQueue'] as $queue) {
				$queueinfo = array('queueid' => $queue['queueid'], 'queuetype' => 'export', 'ownerid' => $user->userid);
				$tempExportDetails['List'] = $queue['listid'];
				$tempInfo = $subscriber_api->GetSubscribers($tempExportDetails, array(), false, $queueinfo, 'true');
				$totalsubscribers += $tempInfo['count'];
			}

			$jobapi = $this->GetApi('jobs');
			$jobcreated = $jobapi->Create('export', time(), $user->userid, $exportinfo, 'export', 0, 0, $user->userid);
			$exportinfo['ExportJobId'] = $jobcreated;
		/**
		 * -----
		 */

		if ($totalsubscribers < 1) {
			$this->ExportSubscribers_Step2($exportinfo['List'], GetLang('NoSubscribersMatch'));
			return;
		}

		$exportinfo['QueueSize'] = $totalsubscribers;
		IEM::sessionSet('ExportInfo', $exportinfo);

		$GLOBALS['TotalSubscriberCount'] = $this->FormatNumber($totalsubscribers);
		if ($totalsubscribers == 1) {
			$GLOBALS['Message'] = $this->PrintSuccess('Subscribers_Export_FoundOne');
		} else {
			$GLOBALS['Message'] = $this->PrintSuccess('Subscribers_Export_FoundMany', $GLOBALS['TotalSubscriberCount']);
		}

		$all_options = array('e' => GetLang('EmailAddress'), 'f' => GetLang('Format'), 'c' => GetLang('Confirmed'), 'mdy' => GetLang('SubscribeDate_MDY'));

		if (SENDSTUDIO_IPTRACKING) {
			$all_options['i'] = GetLang('SubscriberIPAddress');
		}

		if (isset($export_details['Status']) && $export_details['Status'] == 'b') {
			$all_options['btime'] = GetLang('SubscriberBounceTime');
			$all_options['btype'] = GetLang('SubscriberBounceType');
		}

		foreach ($CustomFieldsList as $pos => $details) {
			$all_options[$details['fieldid']] = $details['name'];
		}

		$all_options['n'] = GetLang('None');

		$fieldoptions = '';

		$fieldcount = sizeof($all_options) - 1;
		for ($i = 1; $i <= $fieldcount; $i++) {
			$GLOBALS['FieldName'] = sprintf(GetLang('ExportField'), $i);
			$GLOBALS['OptionName'] = 'fieldoption[' . $i . ']';
			$optionlist = '';
			$fcount = 1;
			foreach ($all_options as $id => $name) {
				$optionlist .= '<option value="' . $id . '"';
				if ($fcount == $i) {
					$optionlist .= ' SELECTED';
				}

				$optionlist .= '>' . htmlspecialchars($name, ENT_QUOTES, SENDSTUDIO_CHARSET) . '</option>';
				if ($id == 'mdy') {
					$optionlist .= '<option value="dmy">' . GetLang('SubscribeDate_DMY') . '</option>';
					$optionlist .= '<option value="ymd">' . GetLang('SubscribeDate_YMD') . '</option>';
				}
				$fcount++;
			}
			$GLOBALS['OptionList'] = $optionlist;
			$fieldoptions .= $this->ParseTemplate('Subscribers_Export_Step3_Options', true, false);
		}
		$GLOBALS['FieldOptions'] = $fieldoptions;

		$this->ParseTemplate('Subscribers_Export_Step3');
	}
	/**
	* ManageCustomField_Lists
	* Prints out the custom field to list associations.
	*
	* @param Int $fieldid Fieldid to print associations for.
	* @param Boolean $newfield Whether we're creating a new field or not. This changes language variables accordingly.
	*
	* @see GetApi
	* @see CustomFields_API::Load
	* @see CustomFields_API::Settings
	* @see CustomFields_API::Associations
	* @see User_API::GetLists
	*
	* @return Void Doesn't return anything, just prints out the results.
	*/
	function ManageCustomField_Lists($fieldid=0, $newfield=false)
	{
		if ($fieldid <= 0) {
			return false;
		}

		$api = $this->GetApi();
		if (!$api->Load($fieldid)) {
			return false;
		}

		if ($newfield) {
			$GLOBALS['Heading'] = GetLang('CreateCustomField_Step3');
			$GLOBALS['Intro'] = GetLang('CreateCustomField_Step3_Intro');
			$GLOBALS['CancelButton'] = GetLang('CreateCustomField_CancelPrompt');
		} else {
			$GLOBALS['Heading'] = GetLang('EditCustomField_Step3');
			$GLOBALS['Intro'] = GetLang('EditCustomField_Step3_Intro');
			$GLOBALS['CancelButton'] = GetLang('EditCustomField_CancelPrompt');
		}

		$fieldapi = $this->GetApi('CustomFields_' . $api->fieldtype);
		$fieldapi->Load($fieldid);

		$user = IEM::getCurrentUser();
		$lists = $user->GetLists();

		$GLOBALS['fieldid'] = $fieldid;
		$GLOBALS['CustomFieldListAssociation'] = sprintf(GetLang('CustomFieldListAssociation'), $fieldapi->Settings['FieldName']);

		$list_assoc = '';

		$GLOBALS['ListAssociations'] = '';

		foreach ($lists as $listid => $listdetails) {
			$GLOBALS['ListAssociations'] .= '<option value="'. $listid . '"';

			if (in_array($listid, $fieldapi->Associations)) {
				$GLOBALS['ListAssociations'] .= ' selected="selected"';
			}
			$GLOBALS['ListAssociations'] .= '>' . htmlspecialchars($listdetails['name'], ENT_QUOTES, SENDSTUDIO_CHARSET) . '</option>';
		}

		$this->ParseTemplate('CustomField_Form_Step3');
	}
	/**
	* GetPredefinedLinkList
	* A function to generate a list of the available predefined links
	*
	* @return Void Doesn't return anything. Display the javascript content.
	*/
	function GetPredefinedLinkList()
	{

		$user = IEM::getCurrentUser();
		$form_userid = $user->userid;
		if ($user->Admin()) {
			$form_userid = 0;
		}
		$formapi = $this->GetApi('Forms');
		$output = '';

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

		$allLinks[] = array('name' => GetLang('Link_MailingListArchives'), 'url' => '%%mailinglistarchive%%');
		$allLinks[] = array('name' => GetLang('Link_WebVersion'), 'url' => '%%webversion%%');
		$allLinks[] = array('name' => GetLang('Link_Unsubscribe'), 'url' => '%%unsubscribelink%%');

		$modify_forms = $formapi->GetUserForms($form_userid, 'modify');
		if (!empty($modify_forms)) {
			foreach ($modify_forms as $p => $formdetails) {
				$allLinks[] = array('name' => htmlspecialchars($formdetails['name'], ENT_QUOTES, SENDSTUDIO_CHARSET), 'url' => "%%modifydetails_" . $formdetails['formid'] . "%%");
			}
		}

		$sendfriend_forms = $formapi->GetUserForms($form_userid, 'friend');
		if (!empty($sendfriend_forms)) {
			foreach ($sendfriend_forms as $p => $formdetails) {
				$allLinks[] = array('name' => htmlspecialchars($formdetails['name'], ENT_QUOTES, SENDSTUDIO_CHARSET), 'url' => "%%sendfriend_" . $formdetails['formid'] . "%%");
			}
		}

		foreach ($allLinks as $k=>$link){
			$outputArray[] = '["' . $link['name'] . '", "' . $link['url'] . '"]';
		}

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

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

		echo $output;
		die();
	}
Beispiel #17
0
	/**
	 * GetActivity
	 * Get log activity for current user
	 *
	 * @return Array|FALSE Returns an array of log records (or an empty array if none is available) if successful, FALSE otherwise
	 */
	public function GetActivity()
	{
		$user = IEM::getCurrentUser();
		if ($user === false) {
			return false;
		}

		$userid = intval($user->userid);

		$result = $this->Db->Query("SELECT * FROM [|PREFIX|]user_activitylog WHERE userid = {$userid} ORDER BY viewed DESC LIMIT " . self::NUMBER_OF_ACTIVITY_KEPT);
		if (!$result) {
			list($msg, $errno) = $this->Db->GetError();

			// If table does not exists, we will assume that the application is upgrading itself??
			// But we do still need to log this in the database error log
			$status = $this->_checkTableExists();
			if ($status === 0) {
				trigger_error('user_activitylog table does not exists', E_USER_NOTICE);
				return array();
			}

			trigger_error($msg, $errno);
			return false;
		}

		$rows = array();
		while ($row = $this->Db->Fetch($result)) {
			array_push($rows, $row);
		}

		$this->Db->FreeResult($result);

		return $rows;
	}
 /**
  * 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;
 }
	/**
	* EditBan
	* Edit a particular ban - either update it (change the banned email/domain) or change the list it applies to.
	*
	* @param Int $banid The banid to edit.
	* @param Mixed $list List to edit the ban for. This can either be a numeric value (listid), or if it's 'global' it will cover the 'global' bans.
	*
	* @see GetApi
	* @see Subscriber_API::LoadBan
	* @see User_API::GetLists
	* @see User_API::ListAdmin
	*
	* @return Void Prints out the report, doesn't return anything.
	*/
	function EditBan($banid=0, $list=null)
	{
		$subscriber_api = $this->GetApi('Subscribers');
		$ban = $subscriber_api->LoadBan($banid, $list);

		if (!$ban) {
			$this->DenyAccess(GetLang('BannedSubscriberDoesntExist'));
		}

		$user = IEM::getCurrentUser();
		$lists = $user->GetLists();

		$selectlist = '';

		if ($user->HasAccess('Lists', 'Global')) {
			$selected = '';
			if ($ban['list'] == 'g') {
				$selected = ' SELECTED';
			}

			$selectlist .= '<option value="global"' . $selected . '>' . GetLang('Subscribers_GlobalBan') . '</option>';
		}

		foreach ($lists as $listid => $listdetails) {
			$selected = '';
			if ($listid == $ban['list']) {
				$selected = ' SELECTED';
			}

			$selectlist .= '<option value="' . $listid . '"' . $selected . '>' . htmlspecialchars($listdetails['name'], ENT_QUOTES, SENDSTUDIO_CHARSET) . '</option>';
		}

		$GLOBALS['SelectList'] = $selectlist;

		$GLOBALS['BanID'] = $ban['banid'];
		$GLOBALS['BannedAddress'] = $ban['emailaddress'];

		$this->ParseTemplate('Subscribers_Banned_Edit');
	}
Beispiel #20
0
	/**
	* Process
	* Does all of the work. Includes the chart, works out the data, prints it out.
	* It works out the type of calendar you're viewing (monthly, daily, weekly etc) and sets appropriate variables.
	* The stats api works out what type of calendar it is. It is done there so the stats file can make use of it as well for displaying date/time information.
	*
	* @see calendar_type
	* @see daily_stats_type
	* @see stats_type
	* @see chart_details
	* @see SetupChartDates
	* @see SetupChart_Subscribers
	* @see SetupChart
	* @see Stats_API::GetSubscriberGraphData
	* @see Stats_API::GetGraphData
	* @see Stats_API::CalculateStatsType
	* @see chart
	*
	* @return Void Prints out the chard, doesn't return anything.
	*/
	function Process()
	{
		$thisuser = IEM::getCurrentUser();

		$this->LoadLanguageFile('Stats');

		$idx = false;
		if (isset($_GET['i']) && $_GET['i'] == 1) {
			$idx = true;
		}
		$this->stats_api->CalculateStatsType($idx);

		$calendar_dates = $thisuser->GetSettings('CalendarDates');

		include(dirname(__FILE__) . '/amcharts/amcharts.php');

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

		$chart_area = false;
		if (isset($_GET['Area'])) {
			$chart_area = strtolower($_GET['Area']);
		}

		switch ($chart_area) {
			case 'autoresponder':
			case 'list':
			case 'subscriberdomains':
				$chart_area = ucwords($chart_area);
			break;

			default:
				$chart_area = 'Newsletter';
		}

		$chart_type = false;
		if (isset($_GET['graph'])) {
			$chart_type = strtolower($_GET['graph']);
		}

		$list_statistics = IEM::sessionGet('ListStatistics');

		if ($list_statistics) {
			$statid = $list_statistics;
		}

		switch ($chart_type) {
			case 'bouncechart':
				$restrictions = isset($calendar_dates['bounces']) ? $calendar_dates['bounces'] : '';
				$this->chart['chart_data'][1][0] = GetLang('Stats_TotalBouncedEmails');

				$this->chart['chart_type'] = 'column';
				$this->chart['chart_data'][1][0] = GetLang('SoftBounces');
				$this->chart['chart_data'][2][0] = GetLang('HardBounces');
			break;

			case 'userchart':
				$restrictions = $calendar_dates['usersummary'];
				$this->chart['chart_data'][1][0] = GetLang('Stats_TotalEmailsSent');
			break;

			case 'openchart':
				$restrictions = IEM::ifsetor($calendar_dates['opens'], '');
				$this->chart['chart_data'][1][0] = GetLang('Stats_TotalOpens');
			break;

			case 'forwardschart':
				$restrictions = IEM::ifsetor($calendar_dates['forwards'], '');
				$this->chart['chart_data'][1][0] = GetLang('Stats_TotalForwards');
			break;

			case 'unsubscribechart':
				$restrictions = IEM::ifsetor($calendar_dates['unsubscribes'], '');
				$this->chart['chart_data'][1][0] = GetLang('Stats_TotalUnsubscribes');
			break;

			case 'linkschart':
				$restrictions = IEM::ifsetor($calendar_dates['clicks'], '');
				$this->chart['chart_data'][1][0] = GetLang('Stats_TotalClicks');
			break;

			case 'subscribersummary':
				$restrictions = IEM::ifsetor($calendar_dates['subscribers'], '');

				$this->chart['chart_type'] = 'column';
				$this->chart['chart_data'][1][0] = GetLang('Unconfirms');
				$this->chart['chart_data'][2][0] = GetLang('Confirms');
				$this->chart['chart_data'][3][0] = GetLang('Unsubscribes');
				$this->chart['chart_data'][4][0] = GetLang('Bounces');
				$this->chart['chart_data'][5][0] = GetLang('Forwards');

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

			// use 'custom_pie' chart type to send data to the plotting software and produce a pie chart
			case 'custom_pie':
				// expects a data string in the format "john:123,paul:101,george:153,ringo:139"
				$chart_type = false;
				$chart_data = array();
				$this->chart['chart_type'] = 'pie';
				$data = explode(",", $this->_getGETRequest('data', ''));

				for ($i = 0; $i < count($data); $i++ ) {
					$values = explode(":", $data[$i]);
					$this->chart['chart_data'][0][$i+1] = $values[0];
					$this->chart['chart_data'][1][$i+1] = $values[1];
				}

				$this->chart['chart_value_text'][1][1] = 7;
				$this->chart['chart_value_text'][1][2] = 8;
				$this->chart['chart_value_text'][1][3] = 9;

			break;

			// use 'custom_bar' chart type to send data to the plotting software and produce a bar chart
			// expects following url parameters :
			// data=john:56:23:9,paul:32:9:1,george:98:43:12 & xLabels=albums,eps,singles
			case 'custom_bar':
				$xLabels = explode(',', $this->_getGETRequest('xLabels', ''));
				$data = explode(",", $this->_getGETRequest('data', ''));
				$chart_type = false;
				$this->chart['chart_type'] = 'column';

				$chart_data = array();
				$xAxisLabels = array();
				$xAxisLabels[0] = '';

				// Add the X Axis Elements
				for ($i = 0; $i < count($xLabels); $i++ ) {
					$xAxisLabels[] = $xLabels[$i];
				}
				$chart_data[] = $xAxisLabels;

				// Add the data and legend information
				// the first item in each xData array is the legend text the remainder are data value elements
				for ($i = 0; $i < count($data); $i++ ) {
					$xData = array();
					$values = explode(":", $data[$i]);
					for ($j = 0; $j < count($values); $j++) {
						$xData[] = $values[$j];
					}
					$chart_data[] = $xData;
				}

				$this->chart['chart_data'] = $chart_data;
				$this->chart['axis_category'] = array('skip' => 0);

			break;

			default:
				// this is for the "summary" pages where it breaks down opens/unopened/bounces
				// the summary pages are all pie charts.
				$chart_type = false;

				$this->chart['chart_type'] = 'pie';

				if (strtolower($chart_area) == 'subscriberdomains') {
					$chart_title = GetLang('ListStatistics_Snapshot_PerDomain');
					$domain_details = IEM::sessionGet('SubscriberDomains');

					$total = array_sum($domain_details);

					$graph_pos = 1;

					if ($total == 0) {
						$this->chart['chart_type'] = 'column';
					} else {
						foreach ($domain_details as $domain_name => $count) {
							$percent = 0;
							if ($total > 0) {
								$percent = $this->FormatNumber(($count / $total) * 100);
							}

							$this->chart['chart_data'][0][$graph_pos] = sprintf(GetLang('Summary_Domain_Name'), $domain_name, $percent);

							$this->chart['chart_data'][1][$graph_pos] = $count;

							$this->chart['chart_value_text'][1][$graph_pos] = $this->FormatNumber($count);

							$graph_pos++;
						}
					}

					break;
				}

				$opens = $unopened = $bounces = 0;

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

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

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

				if (isset($_GET['Heading']) && $_GET['Heading'] == 'User') {
					$chart_title = GetLang('User_Summary_Graph');
				} else {
					$chart_title = GetLang($chart_area . '_Summary_Graph');
				}

				if ($opens == 0 && $bounces == 0 && $unopened == 0) {
					$unopened = 1;
				}

				$total = $opens + $unopened + $bounces;

				$opens_percent = $unopened_percent = $bounces_percent = 0;

				if ($total > 0) {
					$opens_percent = $this->FormatNumber(($opens / $total) * 100);
					$unopened_percent = $this->FormatNumber(($unopened / $total) * 100);
					$bounces_percent = $this->FormatNumber(($bounces / $total) * 100);
				}

				$this->chart['chart_data'][0][1] = sprintf(GetLang('Summary_Graph_Opened'), $opens_percent);
				$this->chart['chart_data'][0][2] = sprintf(GetLang('Summary_Graph_Unopened'), $unopened_percent);
				$this->chart['chart_data'][0][3] = sprintf(GetLang('Summary_Graph_Bounced'), $bounces_percent);

				$this->chart['chart_data'][1][1] = $opens;
				$this->chart['chart_data'][1][2] = $unopened;
				$this->chart['chart_data'][1][3] = $bounces;

				if ($opens == 0 && $unopened == 0 && $bounces == 0) {
					$this->chart['chart_type'] = 'column';
				}

				$opens_percent = $opens / 100;

				$this->chart['chart_value_text'][1][1] = $this->FormatNumber($opens);
				$this->chart['chart_value_text'][1][2] = $this->FormatNumber($unopened);
				$this->chart['chart_value_text'][1][3] = $this->FormatNumber($bounces);

		}

		if ($chart_type) {
			$chart_title = GetLang($chart_area . '_Summary_Graph_' . $chart_type);

			$this->SetupChartDates($chart_type);
			$listid = 0;
			if (isset($_GET['Area']) && $_GET['Area'] == 'list' && isset($_GET['statid'])) {
				$listid = (int)$_GET['statid'];
			}
			if (isset($_GET['List'])) {
				$listid = (int)$_GET['List'];
			}

			switch ($chart_type) {
				case 'bouncechart':
					$data = $this->stats_api->GetBounceGraphData($this->stats_api->stats_type, $restrictions, $statid, $listid);
					$this->SetupChart_BounceSummary($data);
				break;

				case 'subscribersummary':
					if (isset($_GET['i']) && $_GET['i'] == 1) {
						$data = IEM::sessionGet('IndexSubscriberGraphData');
					} else {
						$data = IEM::sessionGet('SubscriberGraphData');
					}

					$this->SetupChart_SubscriberSummary($data);
				break;

				case 'userchart':
					$data = IEM::sessionGet('userchart_data');
					$this->SetupChart($data);
				break;

				default:
					$data = $this->stats_api->GetGraphData($statid, $this->stats_api->stats_type, $restrictions, $chart_type, $listid);
					$this->SetupChart($data);
				break;
			}
		}

		// Prints the chart as a gif or png
		if (isset($_GET['GetAsImg'])) {
			// graphpite causes lots of notices and warning, so turn those off
			error_reporting(E_PARSE | E_ERROR);

			// Turn off error handling, it breaks the chart generation
			set_error_handler('ord');

			require_once(dirname(__FILE__) . "/amcharts/graphpite.php");
			// Width & height are fixed at 650x300 for printing
			$chart_image = new Chart_Image(650,300,$chart_title);
			$chart_image->Generate($this->chart);
			$chart_image->PrintImage();

			// Restore error handling
			error_reporting(E_ALL);
			restore_error_handler();
		} else {
			// gets chart data as xml for amcharts
			SendChartData($this->chart);
		}
	}
Beispiel #21
0
/**
* GetUser
* If a userid is passed in, it will create a new user object and return the reference to it.
* If no userid is passed in, it will get the current user from the session.
*
* @param Int $userid If a userid is passed in, it will create a new user object and return it. If there is no userid it will get the current user from the session.
*
* @see User
*
* @return User_API The user object.
*
* @todo deprecate this in favour of IEM::getCurrentUser function
*/
function GetUser($userid = 0)
{
    if ($userid == 0) {
        $UserDetails = IEM::getCurrentUser();
        return $UserDetails;
    }
    if ($userid == -1) {
        $user = new User_API();
    } else {
        $user = new User_API($userid);
    }
    return $user;
}
Beispiel #22
0
	/**
	* ShowLoginForm
	* This shows the login form.
	* If there is a template to use in the data/templates folder it will use that as the login form.
	* Otherwise it uses the default one below. If you pass in a message it will show that message above the login form.
	*
	* @param String $template Uses the template passed in for the message (eg success / error).
	* @param String $msg Prints the message passed in above the login form (eg unsuccessful attempt).
	*
	* @see FetchTemplate
	* @see PrintHeader
	* @see PrintFooter
	*
	* @return Void Doesn't return anything, just prints the login form.
	*/
	function ShowLoginForm($template=false, $msg=false)
	{
		if (!IEM::getCurrentUser()) {
			$this->GlobalAreas['InfoTips'] = '';
		}

		$this->PrintHeader(true);

		$GLOBALS['Message'] = GetLang('Help_Login');

		if ($template && $msg) {
			switch ($template) {
				case 'login_error':
					$GLOBALS['Error'] = $msg;
				break;
				case 'login_success':
					$this->GlobalAreas['Success'] = $msg;
				break;
			}
			$GLOBALS['Message'] = $this->ParseTemplate($template,true);
		}

		$username = IEM::requestGetPOST('ss_username', false);
		if ($username) {
			$GLOBALS['ss_username'] = htmlspecialchars($username, ENT_QUOTES, SENDSTUDIO_CHARSET);
 		}

		$GLOBALS['ss_takemeto'] = 'index.php';
		$loginPreference = IEM::requestGetCookie('IEM_LoginPreference', array());
		if (is_array($loginPreference) && isset($loginPreference['takemeto'])) {
			$GLOBALS['ss_takemeto'] = $loginPreference['takemeto'];
		}

		$this->GlobalAreas['SubmitAction'] = 'Login';

		$this->ParseTemplate('login');

		$this->PrintFooter(true);
	}
Beispiel #23
0
	/**
	 * Pauses autoresponder
	 * @param integer $autoresponderid Autoresponder to be paused
	 * @return boolean Returns TRUE if successful, FALSE otherwise
	 */
	function PauseAutoresponder($autoresponderid)
	{
		$user = IEM::getCurrentUser();
		$autoresponderid = intval($autoresponderid);
		$userid = $user->userid;

		if ($userid == 0) {
			trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- You need to login first before you can pause autoresponder', E_USER_NOTICE);
			return false;
		}

		$status = $this->Db->Query("UPDATE [|PREFIX|]autoresponders SET pause = {$userid} WHERE autoresponderid = {$autoresponderid}");
		if (!$status) {
			return false;
		}

		return true;
	}
	/**
	* Process
	* This processes the ajax requests.
	* There are only two types of request - importfile and importurl.
	*
	* If it's importfile, it will display the 'fileupload' iframe again, and also process the file if there was one uploaded. It base 64 encodes the data to pass to javascript, this saves having to worry about newlines, quotes and so on. The javascript decodes it itself, then calls the DoImport function in the includes/js/javascript.js file.
	*
	* If it's importurl, it simply calls GetPageContents and returns that.
	*
	* @see GetPageContents
	*
	* @return Void Doesn't return anything, simply prints out the results.
	*/
	function Process()
	{
		// make sure they are logged in appropriately.
		if (!IEM::getCurrentUser()) {
			return;
		}

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

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

		$user = GetUser();

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

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

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

					$this->LoadLanguageFile('autoresponders');

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

					$userid = $user->userid;

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

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

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

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

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

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

				case 'importnewsletters':
					$listid = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						echo $page;
					}
				break;

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

					$lines = array();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

					$tpl = GetTemplateSystem();
					$tpl->Assign('SessionName', IEM::SESSION_NAME);
					$tpl->Assign('Pagination', $paging);
					$tpl->Assign('SessionID', IEM::sessionID());
					echo $tpl->ParseTemplate('Image_Manager_Sub');
				break;
			}
		}
	}
Beispiel #25
0
	/**
	* PrintEditForm
	* Prints a form to edit a user. If you pass in a userid, it will load up that user and print their information. If you pass in the details array, it will prefill the form with that information (eg if you tried to create a user with a duplicate username). Also checks whether you are allowed to edit this user. If you are not an admin, you are only allowed to edit your own account.
	*
	* @param Int $userid Userid to load up.
	* @param Array $details Details to prefill the form with (in case there was a problem creating the user).
	*
	* @see User_API::Admin
	* @see User_API::Status
	* @see User_API::ListAdmin
	* @see User_API::EditOwnSettings
	* @see GetUser
	*
	* @return Void Returns nothing. If you don't have access to edit a particular user, it prints an error message and exits. Otherwise it prints the correct form (either edit-own or edit) and then exits.
	*/
	function PrintEditForm($userid = 0, $details = array())
	{
		$thisuser = IEM::getCurrentUser();
		if (!$thisuser->UserAdmin()) {
			if ($userid != $thisuser->userid) {
				$this->DenyAccess();
			}

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

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

		$listapi = $this->GetApi('Lists');
		$all_lists = $listapi->GetLists(0, array('SortBy' => 'name', 'Direction' => 'asc'), false, 0, 0);

		$segmentapi = $this->GetApi('Segment');
		$all_segments = $segmentapi->GetSegments(array('SortBy' => 'segmentname', 'Direction' => 'asc'), false, 0, 'all');

		$templateapi = $this->GetApi('Templates');
		$all_templates = $templateapi->GetTemplates(0, array('SortBy' => 'name', 'Direction' => 'asc'), false, 0, 0);

		$all_groups = API_USERGROUPS::getRecords(false, false, 0, 0, 'groupname');

		$GLOBALS['CustomSmtpServer_Display'] = '0';

		$GLOBALS['XmlPath'] = SENDSTUDIO_APPLICATION_URL . '/xml.php';

		if ($userid > 0) {
			$user = GetUser($userid);
			if ($user->Get('userid') <= 0) {
				$GLOBALS['ErrorMessage'] = GetLang('UserDoesntExist');
				$this->DenyAccess();
				return;
			}
			$GLOBALS['UserID'] = $user->Get('userid');
			$GLOBALS['UserName'] = htmlspecialchars($user->Get('username'), ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['FullName'] = htmlspecialchars($user->Get('fullname'), ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['EmailAddress'] = htmlspecialchars($user->Get('emailaddress'), ENT_QUOTES, SENDSTUDIO_CHARSET);

			$activity = $user->GetEventActivityType();
			if (!is_array($activity)) {
				$activity = array();
			}
			$GLOBALS['EventActivityType'] = implode("\n", $activity);

			$GLOBALS['MaxLists'] = $user->group->limit_list;
			$GLOBALS['MaxEmails'] = $user->group->limit_totalemailslimit;
			$GLOBALS['PerMonth'] = $user->group->limit_emailspermonth;
			$GLOBALS['PerHour'] = $user->group->limit_hourlyemailsrate;


			$GLOBALS['DisplayMaxLists'] = '';
			if ($user->Get('maxlists') == 0) {
				$GLOBALS['LimitListsChecked'] = ' CHECKED';
				$GLOBALS['DisplayMaxLists'] = 'none';
			}

			$GLOBALS['DisplayEmailsPerHour'] = '';
			if ($user->Get('perhour') == 0) {
				$GLOBALS['LimitPerHourChecked'] = ' CHECKED';
				$GLOBALS['DisplayEmailsPerHour'] = 'none';
			}

			$GLOBALS['DisplayEmailsPerMonth'] = '';
			if ($user->Get('permonth') == 0) {
				$GLOBALS['LimitPerMonthChecked'] = ' CHECKED';
				$GLOBALS['DisplayEmailsPerMonth'] = 'none';
			}

			$GLOBALS['LimitMaximumEmailsChecked'] = ' CHECKED';
			$GLOBALS['DisplayEmailsMaxEmails'] = 'none';

			if (!$user->hasUnlimitedCredit()) {
				$GLOBALS['LimitMaximumEmailsChecked'] = '';
				$GLOBALS['DisplayEmailsMaxEmails'] = '';
			}

			if ($user->Get('usewysiwyg')) {
				$GLOBALS['UseWysiwyg'] = ' CHECKED';
				$GLOBALS['UseXHTMLDisplay'] = ' style="display:block;"';
			} else {
				$GLOBALS['UseXHTMLDisplay'] = ' style="display:none;"';
			}

			if ($user->Get('enableactivitylog')) {
				$GLOBALS['EnableActivityLog'] = ' CHECKED';
			} else {
				$GLOBALS['EnableActivityLog'] = '';
			}

			$GLOBALS['UseXHTMLCheckbox'] = $user->Get('usexhtml')? ' CHECKED' : '';

			$GLOBALS['Xmlapi'] = $user->Get('xmlapi')? ' CHECKED' : '';
			$GLOBALS['XMLTokenDisplay'] = ' style="display:none;"';

			if ($user->Get('xmlapi')) {
				$GLOBALS['XMLTokenDisplay'] = ' style="display:block;"';
			}
			$GLOBALS['XmlToken'] = htmlspecialchars($user->Get('xmltoken'), ENT_QUOTES, SENDSTUDIO_CHARSET);

			$GLOBALS['TextFooter'] = $user->Get('textfooter');
			$GLOBALS['HTMLFooter'] = $user->Get('htmlfooter');

			$GLOBALS['SmtpServer'] = $user->Get('smtpserver');
			$GLOBALS['SmtpUsername'] = $user->Get('smtpusername');
			$GLOBALS['SmtpPassword'] = $user->Get('smtppassword');
			$GLOBALS['SmtpPort'] = $user->Get('smtpport');

			if ($GLOBALS['SmtpServer']) {
				$GLOBALS['CustomSmtpServer_Display'] = '1';
			}

			$GLOBALS['googlecalendarusername'] = htmlspecialchars($user->Get('googlecalendarusername'), ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['googlecalendarpassword'] = htmlspecialchars($user->Get('googlecalendarpassword'), ENT_QUOTES, SENDSTUDIO_CHARSET);

			$GLOBALS['FormAction'] = 'Action=Save&UserID=' . $user->userid;

			if (!$thisuser->UserAdmin()) {

				$smtp_access = $thisuser->HasAccess('User', 'SMTP');

				$GLOBALS['ShowSMTPInfo'] = 'none';
				$GLOBALS['DisplaySMTP'] = '0';

				if ($smtp_access) {
					$GLOBALS['ShowSMTPInfo'] = '';
				}

				if ($GLOBALS['SmtpServer']) {
					$GLOBALS['CustomSmtpServer_Display'] = '1';
					if ($smtp_access) {
						$GLOBALS['DisplaySMTP'] = '1';
					}
				}

				$this->ParseTemplate('User_Edit_Own');
				return;
			}

			$GLOBALS['StatusChecked'] = ($user->Status()) ? ' CHECKED' : '';

			$GLOBALS['ForceDoubleOptInChecked'] = ($user->Get('forcedoubleoptin')) ? ' CHECKED' : '';
			$GLOBALS['ForceSpamCheckChecked'] = ($user->Get('forcespamcheck')) ? ' CHECKED' : '';
			$GLOBALS['InfoTipsChecked'] = ($user->InfoTips()) ? ' CHECKED' : '';

			$editown = '';
			if ($user->UserAdmin()) {
				$editown = ' CHECKED';
			} else {
				if ($user->EditOwnSettings()) {
					$editown = ' CHECKED';
				}
			}
			$GLOBALS['EditOwnSettingsChecked'] = $editown;

			$timezone = $user->usertimezone;

			$GLOBALS['TimeZoneList'] = $this->TimeZoneList($timezone);

			$admintype = $user->AdminType();
			$listadmintype = $user->ListAdminType();
			$segmentadmintype = $user->SegmentAdminType();
			$templateadmintype = $user->TemplateAdminType();

			$admin = $user->Admin();
			$listadmin = $user->ListAdmin();
			$segmentadmin = $user->SegmentAdmin();
			$templateadmin = $user->TemplateAdmin();

			$permissions = $user->Get('permissions');
			$area_access = $user->Get('access');

			$GLOBALS['Heading'] = GetLang('EditUser');
			$GLOBALS['Help_Heading'] = GetLang('Help_EditUser');

			$GLOBALS['AdminNotifyEmailAddress'] = $user->Get('adminnotify_email');
			if (empty($GLOBALS['AdminNotifyEmailAddress'])) {
				$GLOBALS['AdminNotifyEmailAddress'] = constant('SENDSTUDIO_EMAIL_ADDRESS');
			}

			$GLOBALS['AdminNotifications_Send_Email'] = $user->Get('adminnotify_send_emailtext');
			if (empty($GLOBALS['AdminNotifications_Send_Email'])) {
				$GLOBALS['AdminNotifications_Send_Email'] = GetLang('AdminNotifications_Send_Email');
			}

			$GLOBALS['AdminNotifications_Import_Email'] = $user->Get('adminnotify_import_emailtext');
			if (empty($GLOBALS['AdminNotifications_Import_Email'])) {
				$GLOBALS['AdminNotifications_Import_Email'] = GetLang('AdminNotifications_Import_Email');
			}

			$GLOBALS['SendLimit'] = $user->Get('adminnotify_send_threshold');
			$GLOBALS['ImportLimit'] = $user->Get('adminnotify_import_threshold');

			if (empty($GLOBALS['SendLimit'])) {
				$GLOBALS['SendLimit'] = 1000;
			}
			if (empty($GLOBALS['ImportLimit'])) {
				$GLOBALS['ImportLimit'] = 1000;
			}

			$admin_flag = $user->Get('adminnotify_send_flag');
			if ($user->Get('adminnotify_send_flag') == 1) {
				$GLOBALS['AdminNotificationsSend'] = 'CHECKED';
				$GLOBALS['UseNotifySend'] = '';
			} else {
				$GLOBALS['UseNotifySend'] = "style=display:none;";
			}
			if ($user->Get('adminnotify_import_flag') == 1) {
				$GLOBALS['AdminNotificationsImport'] = 'CHECKED';
				$GLOBALS['UseNotifyImport'] = '';
			} else {
				$GLOBALS['UseNotifyImport'] = "style=display:none;";
			}

			$GLOBALS['SmtpPort'] = $user->Get('smtpport');


			// Log this to "User Activity Log"
			IEM::logUserActivity(IEM::urlFor('users', array('Action' => 'Edit', 'UserID' => $userid)), 'images/user.gif', $user->username);

		} else {
			$timezone = (isset($details['timezone'])) ? $details['timezone'] : SENDSTUDIO_SERVERTIMEZONE;
			$GLOBALS['TimeZoneList'] = $this->TimeZoneList($timezone);

			$activity = $thisuser->defaultEventActivityType;
			if (!is_array($activity)) {
				$activity = array();
			}
			$GLOBALS['EventActivityType'] = implode("\n", $activity);

			$GLOBALS['FormAction'] = 'Action=Create';

			if (!empty($details)) {
				foreach ($details as $area => $val) {
					$GLOBALS[$area] = $val;
				}
			}
			$GLOBALS['Heading'] = GetLang('CreateUser');
			$GLOBALS['Help_Heading'] = GetLang('Help_CreateUser');

			$listadmintype = 'c';
			$segmentadmintype = 'c';
			$admintype = 'c';
			$templateadmintype = 'c';

			$GLOBALS['DisplayMaxLists'] = 'none';
			$GLOBALS['DisplayEmailsPerHour'] = 'none';
			$GLOBALS['DisplayEmailsPerMonth'] = 'none';
			$GLOBALS['DisplayEmailsMaxEmails'] = 'none';

			$GLOBALS['MaxLists'] = '0';
			$GLOBALS['PerHour'] = '0';
			$GLOBALS['PerMonth'] = '0';
			$GLOBALS['MaxEmails'] = '0';

			$GLOBALS['StatusChecked'] = ' CHECKED';
			$GLOBALS['ForceDoubleOptInChecked'] = '';
			$GLOBALS['ForceSpamCheckChecked'] = '';
			$GLOBALS['InfoTipsChecked'] = ' CHECKED';
			$GLOBALS['EditOwnSettingsChecked'] = ' CHECKED';

			$GLOBALS['LimitListsChecked'] = ' CHECKED';
			$GLOBALS['LimitPerHourChecked'] = ' CHECKED';
			$GLOBALS['LimitPerMonthChecked'] = ' CHECKED';
			$GLOBALS['LimitMaximumEmailsChecked'] = ' CHECKED';

			$GLOBALS['UseWysiwyg'] = ' CHECKED';
			$GLOBALS['EnableLastViewed'] = '';
			$GLOBALS['UseXHTMLCheckbox'] = ' CHECKED';

			$GLOBALS['HTMLFooter'] = GetLang('Default_Global_HTML_Footer');
			$GLOBALS['TextFooter'] = GetLang('Default_Global_Text_Footer');

			$GLOBALS['EnableActivityLog'] = ' CHECKED';

			$GLOBALS['Xmlapi'] = '';
			$GLOBALS['XMLTokenDisplay'] = ' style="display:none;"';

			$admin = $listadmin = $segmentadmin = $templateadmin = false;
			$permissions = array();
			$area_access = array('lists' => array(), 'templates' => array(), 'segments' => array());

			$GLOBALS['AdminNotifyEmailAddress'] = constant('SENDSTUDIO_EMAIL_ADDRESS');
			$GLOBALS['UseNotifySend'] = "style=display:none;";
			$GLOBALS['UseNotifyImport'] = "style=display:none;";

			$GLOBALS['SendLimit'] = 1000;
			$GLOBALS['ImportLimit'] = 1000;
			$GLOBALS['AdminNotifications_Send_Email'] = GetLang('AdminNotifications_Send_Email');
			$GLOBALS['AdminNotifications_Import_Email'] = GetLang('AdminNotifications_Import_Email');

		}

		$agencyid = defined('IEM_SYSTEM_LICENSE_AGENCY') ? IEM_SYSTEM_LICENSE_AGENCY : '';
		$available_users = $user->AvailableUsers();

		$template = GetTemplateSystem();
        
		$template->Assign('UserID', $user->userid);
		$template->Assign('groupid', $user->groupid);
		$template->Assign('canChangeUserGroup', !$user->isLastAdmin());
		$template->Assign('AgencyEdition', get_agency_license_variables());
		$template->Assign('EditOwn', ($user->userid != 0 && $user->userid == $thisuser->userid));
		$template->Assign('TrialUser', $user->trialuser);
		$template->Assign('EditMode', !empty($user->userid));
		$template->Assign('AvailableNormalUsers', isset($available_users['normal']) ? $available_users['normal'] : 0);
		$template->Assign('AvailableTrialUsers', isset($available_users['trial']) ? $available_users['trial'] : 0);
		$template->Assign('AvailableGroups', $all_groups);
		$template->Assign('record_groupid', $user->groupid);
		$template->Assign('DefaultIdTab', IEM::requestGetPOST('id_tab_num', 1, 'intval'));
		$template->Assign('showSmtpInfo', (bool) $user->smtpserver);

		$template->ParseTemplate('User_Form');
	}
		<div class="logo">
			<a href="index.php"><img id="logo" src="<?php print $IEM['ApplicationLogoImage']; ?>" alt="<?php echo GetLang('SendingSystem'); ?>" border="0" /></a>
		</div>

		<div class="textlinks" align="right">
			<div class="MenuText">
				<?php if(IEM::getCurrentUser()) print $IEM['TextLinks']; ?>
				<div class="loggedinas">
					<?php if(isset($GLOBALS['UserLoggedInAs'])) print $GLOBALS['UserLoggedInAs']; ?><?php if(isset($GLOBALS['SystemDateTime'])) print $GLOBALS['SystemDateTime']; ?>
				</div>
				<span class="emailcredits"><?php if(isset($GLOBALS['MonthlyEmailCredits'])) print $GLOBALS['MonthlyEmailCredits']; ?></span>
				<span class="emailcredits"><?php if(isset($GLOBALS['TotalEmailCredits'])) print $GLOBALS['TotalEmailCredits']; ?></span>
			</div>
		</div>

		<div class="Header_Bottom"></div>
	</div>

	<div class="menuBar">
		<div style="height:0px;">&nbsp;</div>
		<div><?php if(IEM::getCurrentUser()) print $IEM['MenuLinks']; ?></div>
	</div>

	<div class="ContentContainer">
		<div class="BodyContainer">
			<?php if($tpl->Get('ShowTestModeWarning')): ?>
				<div class="TestModeEnabled"><div style="valign: top"><img src="images/critical.gif"  align="left" hspace="5"><?php echo $tpl->Get('SendTestWarningMessage'); ?></div></div>
			<?php endif; ?>

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

        $user = GetUser();

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

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

        $tpl = GetTemplateSystem();


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

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

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

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

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

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

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

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

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

        $tpl->ParseTemplate('Newsletter_Form_Step2');
    }
Beispiel #28
0
	/**
	 * Have Access
	 * Check whether or not current user have access to the template
	 *
	 * @param array|integer $templateRecord Template record or template ID to check
	 * @param string $action Action to check
	 *
	 * @return boolean Returns TRUE if user have access, FALSE otherwise
	 */
	private function _haveTemplateAccess($templateRecord, $action)
	{
		$currentUser = IEM::getCurrentUser();

		if (!is_array($templateRecord)) {
			$templateid = intval($templateRecord);
			if ($templateid == 0) {
				return false;
			}

			$templateapi = $this->GetApi('Templates');
			if (!$templateapi->Load($templateid)) {
				return false;
			}

			// For now these two arrays will suffice.
			$templateRecord = array(
				'templateid'	=> $templateid,
				'ownerid'		=> $templateapi->ownerid
			);
		}

		// Owner always have access
		if (array_key_exists('ownerid', $templateRecord) && $templateRecord['ownerid'] == $currentUser->userid) {
			return true;
		}

		if (array_key_exists('templateid', $templateRecord)) {
			return $currentUser->HasAccess('Templates', $action, $templateRecord['templateid']);
		}

		// Invalid record
		return false;
	}