コード例 #1
0
 /**
  * Retrieves the amount of credit the user has used this hour.
  * 
  * @return int
  */
 public function getUsedHourlyCredit()
 {
     $db = IEM::getDatabase();
     $query = "\n\t\t\tSELECT\n\t\t\t\tSUM(emailssent) as sendsize\n\t\t\tFROM\n\t\t\t\t[|PREFIX|]user_stats_emailsperhour\n\t\t\tWHERE\n\t\t\t\tuserid = {$this->userid}\n\t\t";
     $thisHour = AdjustTime(array(date('H'), 0, 0, date('n'), date('j'), date('Y')), true, null, true);
     $nextHour = AdjustTime(array(date('H') + 1, 0, 0, date('n'), date('j'), date('Y')), true, null, true);
     if ($thisHour) {
         if (is_numeric($thisHour)) {
             strtotime($thisHour);
         }
         $query .= ' AND sendtime >= ' . $thisHour;
     }
     if ($nextHour) {
         if (is_numeric($nextHour)) {
             strtotime($nextHour);
         }
         $query .= ' AND sendtime < ' . $nextHour;
     }
     $query .= ' AND statid != 0';
     $result = $db->FetchOne($query);
     $credits = (int) $result;
     $items = 0;
     $result = $db->Query("\n                SELECT\n                        jobdetails\n                FROM\n                        [|PREFIX|]jobs\n                WHERE\n                        ownerid    = {$this->userid} AND\n                        approved  != 0               AND\n                        jobtype    = 'send'          AND\n                        jobstatus != 'c'\n        ");
     // add on the current queue
     while ($row = $db->Fetch($result)) {
         $jobdetails = unserialize($row['jobdetails']);
         $sendsize = (int) $jobdetails['SendSize'];
         $items = $items + $sendsize;
     }
     $credits = $credits + $items;
     $db->FreeResult($result);
     return $credits;
 }
コード例 #2
0
ファイル: folders.php プロジェクト: hungnv0789/vhtm
	/**
	 * CreateFolder
	 * Creates a new folder.
	 *
	 * @param Int $owner_id The User ID of the owner.
	 * @param String $folder_type The type of folder.
	 * @param String $folder_name The name of the folder.
	 *
	 * @see $_TYPES
	 *
	 * @return Int|Boolean The ID of the new folder or false if the name clashes.
	 */
	public function CreateFolder($owner_id, $folder_type, $folder_name)
	{
		$folder_type = $this->GetValidType($folder_type);
		if (!$folder_type) {
			return false;
		}
		if ($this->_FolderExists($owner_id, $folder_type, $folder_name)) {
			return false;
		}
		$createdate = AdjustTime();
		$query = "INSERT INTO [|PREFIX|]folders (name, type, createdate, ownerid) VALUES
		('" . $this->Db->Quote($folder_name) . "', '" . $this->Db->Quote($folder_type) . "', " . intval($createdate) . ", " . intval($owner_id) . ")";
		$result = $this->Db->Query($query);
		if (!$result) {
			return false;
		}
		return $this->Db->LastId('[|PREFIX|]folders_sequence');
	}
コード例 #3
0
 /**
  * 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;
 }
コード例 #4
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;
	}
コード例 #5
0
	/**
	 * UpdateJob
	 * Updates when a job/scheduled event is set to send.
	 *
	 * A scheduled event by default cannot be changed if:
	 * - it has already sent some emails (it's too hard to re-calculate/re-check/re-allocate per-month statistics)
	 * - you are trying to send "in the past"
	 *
 	 * An addon can override this functionality if need be.
	 * If it does, it must call
	 *
	 * InterspireEventData::preventDefault
	 *
	 * to stop the default action from happening.
	 *
	 * @param Int $jobid The job that needs updating.
	 *
	 * @uses CheckJob
	 * @uses Jobs_API::UpdateTime
	 * @uses ManageSchedules
	 * @uses InterspireEvent::trigger
	 * @see InterspireEventData::preventDefault
	 *
	 * @return Void Doesn't return anything. Checks that it's ok to re-schedule a send. If it is ok, it changes the scheduled time. If it's not, the user gets a message.
	 *
	 * @uses EventData_IEM_SCHEDULE_UPDATEJOB
	 */
	function UpdateJob($jobid=0)
	{
		$check = $this->CheckJob($jobid);
		if (!$check) {
			return false;
		}

		$jobapi = $this->GetApi('Jobs');
		$jobinfo = $jobapi->LoadJob($jobid);

		/**
		 * Trigger Event
		 */
			$tempEventData = new EventData_IEM_SCHEDULE_UPDATEJOB();
			$tempEventData->jobrecord = &$jobinfo;

			if (!$tempEventData->trigger()) {
				$this->ManageSchedules();
				return;
			}

			unset($tempEventData);
		/**
		 * -----
		 */

		$user = GetUser();

		$sendtime = $_POST['sendtime'];

		$hr = $_POST['sendtime_hours'];
		$minute = $_POST['sendtime_minutes'];

		$ampm = null;
		if (isset($_POST['sendtime_ampm'])) {
			$ampm = strtolower($_POST['sendtime_ampm']);
		}

		if ($ampm == 'pm' && $hr < 12) {
			$hr += 12;
		}

		if ($ampm == 'am' && $hr == 12) {
			$hr = 0;
		}

		if ($hr > 23) {
			$hr = $hr % 24;
		}

		$scheduletime = AdjustTime(array($hr, $minute, 0, (int)$_POST['datetime']['month'], (int)$_POST['datetime']['day'], (int)$_POST['datetime']['year']), true);

		// see if they haev changed the send time. If they have, then we need to check stats again to make sure it's ok to do that.
		if ($jobinfo['jobtime'] != $scheduletime) {

			$now = $jobapi->GetServerTime();

			// you are trying to schedule before now (well, 5 minutes ago), then don't allow it.
			if ($scheduletime < ($now - (5 * 60))) {
				$GLOBALS['Error'] = GetLang('Send_Step4_CannotSendInPast');
				$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				$this->EditJob($jobid);
				return;
			}

			if ($jobinfo['queueid'] > 0) {
				$GLOBALS['Error'] = GetLang('CannotChangeAScheduleOnceItHasStarted');
				$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				$this->EditJob($jobid);
				return;
			}

			$schedulemonth = AdjustTime(array(0, 0, 1, date('m', $scheduletime), 1, date('Y', $scheduletime)), true);

			$original_schedulemonth = AdjustTime(array(0, 0, 1, date('m', $jobinfo['jobtime']), 1, date('Y', $jobinfo['jobtime'])), true);

			if ($schedulemonth != $original_schedulemonth) {

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

				/**
				* We need to check user stats for when this is scheduled to send.
				*/
				$check_stats = $statsapi->CheckUserStats($user, $jobinfo['jobdetails']['SendSize'],$scheduletime);

				list($ok_to_send, $not_ok_to_send_reason) = $check_stats;

				if (!$ok_to_send) {
					$GLOBALS['Error'] = GetLang($not_ok_to_send_reason);
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->EditJob($jobid);
					return;
				}

				$new_size = $jobinfo['jobdetails']['SendSize'];

				$statsapi->DeleteUserStats($user->userid, $jobid);

				$statsapi->RecordUserStats($user->userid, $jobid, $new_size, $scheduletime);
			}
		}

		$result = $jobapi->UpdateTime($jobid, $scheduletime);
		if ($result) {
			$GLOBALS['Message'] = $this->PrintSuccess('JobScheduled', $this->PrintTime($scheduletime));
		} else {
			$GLOBALS['Error'] = sprintf(GetLang('JobNotScheduled'), $this->PrintTime($scheduletime));
			$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
		}
		$this->ManageSchedules();
	}
コード例 #6
0
ファイル: send.php プロジェクト: hungnv0789/vhtm
	/**
	 * Step3
	 * Perform process for step 3 and print out output to the browser
	 * It shows information like:
	 * Approximately how many subscribers you will be sending to (based on your list/segment sizes or your custom search info)
	 * Whether to send immediately or not (if scheduled sending is enabled)
	 * Whether to notify the list owner(s) when the send starts and ends
	 *
	 * It also asks for information, including:
	 * which email campaign to send
	 * the send from name, email, reply-to email, bounce email
	 * Which custom field(s) to use for the "to" field (eg 'To: "first name last name" <*****@*****.**>')
	 * and about link & open tracking and embedded images.
	 *
	 * @retrun Void Does not return anything, but prints out directly to breowser
	 */
	function Step3()
	{
		$user = GetUser();

		$send_details = IEM::sessionGet('SendDetails');
		$subscriberApi = $this->GetApi('Subscribers');

		if (!isset($send_details['Segments'])) {
			if (isset($_POST['ShowFilteringOptions'])) {
				$show_filtering_options = $_POST['ShowFilteringOptions'];
				$user->SetSettings('ShowFilteringOptions', $show_filtering_options);
			}

			$send_criteria = array();
			if (isset($send_details['SendCriteria'])) {
				$send_criteria = $send_details['SendCriteria'];
			}

			if (isset($_POST['emailaddress']) && $_POST['emailaddress'] != '') {
				$send_criteria['Email'] = $_POST['emailaddress'];
			}

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

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

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

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

				$send_criteria['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'])) {
				$send_criteria['LinkType'] = 'clicked';
				if (isset($_POST['linktype']) && $_POST['linktype'] == 'not_clicked') {
					$send_criteria['LinkType'] = 'not_clicked';
				}

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

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

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

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

			$send_criteria['CustomFields'] = $customfields;

			$send_criteria['List'] = $send_details['Lists'];

			// can only send to active subscribers.
			$send_criteria['Status'] = 'a';

			$sortinfo = array();

			$subscriber_count = $subscriberApi->GetSubscribers($send_criteria, $sortinfo, true);

			/**
			* If we didn't get any subscribers with our search, then see if the reason is whether:
			*
			* - there are no subscribers on the list(s)
			* - if it's because of the filtering options chosen
			*
			* This is done so we can show an appropriate error message.
			*/
			if ($subscriber_count < 1) {
				$lists = $user->GetLists();
				$user_list_ids = array_keys($lists);
				$list_subscriber_count = 0;
				foreach ($send_details['Lists'] as $p => $listid) {
					if (in_array($listid, $user_list_ids)) {
						$list_subscriber_count += $lists[$listid]['subscribecount'];
						/**
						* we only need to keep going until we find a count > 0
						* as soon as we do, get out of this loop.
						* we know the problem is because of filtering, not because there are no subscribers.
						*/
						if ($list_subscriber_count > 0) {
							break;
						}
					}
				}

				if ($list_subscriber_count == 0) {
					$GLOBALS['Error'] = GetLang('NoSubscribersOnList');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->ChooseList('Send', 'step2', false);
				} else {
					$displaymsg = GetLang('NoSubscribersMatch');

					if ($send_details['BackStep'] == 1) {
						$GLOBALS['Error'] = $displaymsg;
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						$this->ChooseList('Send', 'step2', false);
					} else {
						$this->FilterRecipients($send_details['Lists'], $displaymsg);
					}
				}
				return;
			}

			$send_details['SendSize'] = $subscriber_count;
			$send_details['SendCriteria'] = $send_criteria;
			IEM::sessionSet('SendDetails', $send_details);
		} else {
			$status = $subscriberApi->GetSubscribersFromSegment($send_details['Segments'], true, false);

			$send_details['Lists'] = $status['lists'];
			$send_details['SendSize'] = $status['count'];

			if ($send_details['SendSize'] == 0) {
				$GLOBALS['Error'] = GetLang('NoSubscribersOnSegment');
				$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				$this->ChooseList('Send', 'step1', false);
				return;
			}

			$subscriber_count = $status['count'];

			IEM::sessionSet('SendDetails', $send_details);
		}

		/**
		* If we're not using scheduled sending, then we check the stats here.
		*/
		if (!SENDSTUDIO_CRON_ENABLED || SENDSTUDIO_CRON_SEND <= 0) {
			$stats_api = $this->GetApi('Stats');

			$check_stats = $stats_api->CheckUserStats($user, $subscriber_count, $stats_api->GetServerTime());

			list($ok_to_send, $not_ok_to_send_reason) = $check_stats;

			if (!$ok_to_send) {
				$GLOBALS['Error'] = GetLang($not_ok_to_send_reason);
				$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				echo $this->PrintError($not_ok_to_send_reason);
				return;
				// Please refer to Mitch about why I comment this out
				//$this->FilterRecipients($send_details['Lists'], GetLang($not_ok_to_send_reason));
			}
		}

		$this->SelectNewsletter();
	}
コード例 #7
0
ファイル: surveys.php プロジェクト: solsticehc/solsticehc
 /**
  * Admin_Action_Default
  * Displays the list of surveys, with pagination, and all the CRUD options.
  *
  * @return Void Returns nothing
  */
 public function Admin_Action_Default()
 {
     $this->Admin_Action_PreConfig();
     $me = self::LoadSelf();
     $surveyid = 0;
     if (isset($_REQUEST['id'])) {
         $surveyid = (int) $_REQUEST['id'];
     }
     $api = self::getApi();
     $user = GetUser();
     $me->template_system->Assign('Add_Button', $me->template_system->ParseTemplate('add_survey_button', true), false);
     $me->template_system->Assign('Delete_Button', $me->template_system->ParseTemplate('delete_survey_button', true), false);
     $me->template_system->Assign('FlashMessages', GetFlashMessages(), false);
     $numsurveys = $api->GetSurveys($user->userid, 0, 0, array(), array(), true);
     if ($numsurveys == 0) {
         $me->template_system->ParseTemplate('manage_surveys_empty');
         return;
     }
     $sort_details = array('SortBy' => 'name', 'Direction' => 'asc');
     if (isset($_GET['SortBy']) && in_array(strtolower(IEM::requestGetGET('SortBy')), Addons_survey_api::$validSorts)) {
         $sort_details['SortBy'] = strtolower(IEM::requestGetGET('SortBy'));
     }
     if (in_array(strtolower(IEM::requestGetGET('Direction')), array('up', 'down'))) {
         $direction = strtolower(IEM::requestGetGET('Direction'));
         if ($direction == 'up') {
             $sort_details['Direction'] = 'asc';
         } else {
             $sort_details['Direction'] = 'desc';
         }
     }
     $perpage = $me->GetPerPage();
     if (empty($perpage)) {
         $perpage = (int) IEM::requestGetGET('PerPageDisplay');
     }
     $me->SetPerPage($perpage);
     $page = (int) IEM::requestGetGET('DisplayPage');
     if ($page < 1) {
         $page = 1;
     }
     $paging = $me->SetupPaging($me->admin_url, $numsurveys);
     $me->template_system->Assign('Paging', $paging, false);
     $search_info = array();
     $surveys = $api->GetSurveys($user->userid, $page, $perpage, $search_info, $sort_details, false);
     $survey_rows = '';
     foreach ($surveys as $survey) {
         $me->template_system->Assign('name', $survey['name']);
         $me->template_system->Assign('surveyid', $survey['id']);
         $me->template_system->Assign('created', AdjustTime($survey['created'], false, GetLang('DateFormat'), true));
         if (isset($survey['updated'])) {
             $me->template_system->Assign('updated', AdjustTime($survey['updated'], false, GetLang('DateFormat'), true));
         } else {
             $me->template_system->Assign('updated', GetLang('Addon_Surveys_Default_NeverUpdated'), false);
         }
         // Number of response to be zero first..
         // now lets geat each number of response..
         $me->template_system->Assign('numresponses', $survey['responseCount']);
         if (empty($survey['responseCount'])) {
             $view_results = GetLang('Addon_Surveys_Default_Table_ViewResults');
             $export_responses = GetLang('Addon_Surveys_Default_Table_ExportResponses');
         } else {
             $view_results = '<a href="' . $me->admin_url . '&Action=result&surveyId=' . $survey['id'] . '">' . GetLang('Addon_Surveys_Default_Table_ViewResults') . '</a>';
             $export_responses = '<a href="' . $me->admin_url . '&Action=Export&ajax=1&surveyId=' . $survey['id'] . '">' . GetLang('Addon_Surveys_Default_Table_ExportResponses') . '</a>';
         }
         $me->template_system->Assign('view_results', $view_results, false);
         $me->template_system->Assign('export_responses', $export_responses, false);
         $editlink = '<a href="' . $me->admin_url . '&Action=Edit&formId=' . $survey['id'] . '">' . GetLang('Edit') . '</a>';
         $me->template_system->Assign('edit_link', $editlink, false);
         $deletelink = '<a class=\'deleteButton\' href="' . $me->admin_url . '&Action=Delete&id=' . $survey['id'] . '">' . GetLang('Delete') . '</a>';
         $me->template_system->Assign('delete_link', $deletelink, false);
         $previewlink = '<a target="_blank" href="' . SENDSTUDIO_APPLICATION_URL . '/surveys.php?id=' . $survey['id'] . '">' . GetLang('Preview') . '</a>';
         $me->template_system->Assign('preview_link', $previewlink, false);
         $survey_rows .= $me->template_system->ParseTemplate('manage_surveys_row', true);
     }
     $me->template_system->Assign('Items', $survey_rows, false);
     $me->template_system->ParseTemplate('manage_surveys');
 }
コード例 #8
0
ファイル: autoresponders.php プロジェクト: hungnv0789/vhtm
	/**
	* UpdateQueue
	* Updates the autoresponder queue when the hours after subscription has been changed.
	* If they are the same time, then it does nothing.
	* If the new time is after the old time, it does nothing.
	* If the new time is BEFORE the old time, then we need to check subscribe times to make sure we don't send it incorrectly.
	*
	* @see oldhoursaftersubscription
	* @see hoursaftersubscription
	*
	* @return Boolean Returns false if the autoresponder isn't loaded. Returns true if it doesn't have to do anything, or true if it succeeds in changing the queue.
	*/
	function UpdateQueue()
	{
		if ($this->autoresponderid <= 0) {
			return false;
		}

		if ($this->queueid <= 0) {
			return false;
		}

		if ($this->hoursaftersubscription >= $this->oldhoursaftersubscription) {
			return true;
		}

		$time = AdjustTime();
		$newtime = $time - ($this->hoursaftersubscription * 3600);

		if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
			$query = "DELETE FROM " . SENDSTUDIO_TABLEPREFIX . "queues WHERE recipient IN (SELECT l.subscriberid FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers l WHERE l.listid='" . (int)$this->listid . "' AND subscribedate < " . $newtime . ") AND queueid='" . (int)$this->queueid . "'";
			return $this->Db->Query($query);
		}

		if (SENDSTUDIO_DATABASE_TYPE == 'mysql') {
			$query = "SELECT subscriberid FROM " . SENDSTUDIO_TABLEPREFIX . "list_subscribers l WHERE listid='" . (int)$this->listid . "' AND subscribedate < " . $newtime;
			$subscribers = array('0');
			$result = $this->Db->Query($query);
			while ($row = $this->Db->Fetch($result)) {
				$subscribers[] = $row['subscriberid'];
			}

			return $this->RemoveFromQueue($this->queueid, 'autoresponder', $subscribers);
		}
	}
コード例 #9
0
ファイル: subscribers_event.php プロジェクト: hungnv0789/vhtm
	/**
	* ParseDate
	* This validates the date in $event['date'] and $event['time'] and turns it into a unix timestamp. The timestamp is stored in $event['eventdate']. If validate fails an alert() is printed.
	*
	* @param Array $event The values to to parse the time form. Time is in 12-hour format ex: 10:24 PM. Date is in dd/mm/yyyy. This value is passed by reference
	*
	* @see AdjustTime
	*
	* @return Boolean Returns true on success and false on failure.
	*/
	function ParseDate(&$event)
	{
		if (!preg_match('~^\d{1,2}/\d{1,2}/\d{4}$~',$event['date'])) {
			echo 'alert("' . GetLang('EventSpecifyDate') . '");';
			return false;
		}
		$date = explode('/',$event['date']);

		if (!preg_match('/^(\d{1,2}):(\d{2}) (AM|PM)$/i',$event['time'],$matches)) {
			echo 'alert("' . GetLang('EventSpecifyTime') . '");';
			return false;
		} else {
			$time = array($matches[1] + (strtolower($matches[3]) == 'pm' ? 12 : 0),$matches[2]);
		}

		$timestamp = AdjustTime(array($time[0],$time[1],0,$date[1],$date[0],(int)substr($date[2],-2,2)),true);
		$event['eventdate'] = $timestamp;
		return true;
	}
コード例 #10
0
ファイル: triggeremails.php プロジェクト: hungnv0789/vhtm
	/**
	 * _processRecord
	 * This function will process records that was fetched from the database
	 * to add any "processed" values that needed to be processed
	 *
	 * @param Array &$record The record to be processed
	 * @param Boolean $getdata Whether or not the function should also get triggeremails data
	 * @param Boolean $getactions Whether or not the function should also get triggeremails actions
	 *
	 * @return Void Does not return anything
	 *
	 * @uses AdjustTime()
	 * @uses GetLang()
	 */
	private function _processRecord(&$record, $getdata = false, $getactions = false)
	{
		$record['procstr_createdate'] = AdjustTime($record['createdate'], false, GetLang('DateFormat'), true);

		if ($getdata) {
			$temp = $this->GetData($record['triggeremailsid']);
			if (!$temp) {
				trigger_error('Cannot fetch trigger data', E_USER_NOTICE);
				return;
			}

			$record['data'] = $temp[$record['triggeremailsid']];
		}

		if ($getactions) {
			$temp = $this->GetActions($record['triggeremailsid']);
			if (!$temp) {
				trigger_error('Cannot fetch trigger data', E_USER_NOTICE);
				return;
			}

			$record['triggeractions'] = $temp[$record['triggeremailsid']];
		}
	}
コード例 #11
0
ファイル: index.php プロジェクト: hungnv0789/vhtm
	/**
	 * PrintGraph
	 * Prints out the graph on the front page
	 * Which shows contact activity for the last 7 days including:
	 * - signups (confirmed/unconfirmed)
	 * - bounces
	 * - unsubscribes
	 * - forwards
	 *
	 * @return Void Doesn't return anything, this just prints out the contact activity graph.
	 */
	function PrintGraph()
	{
		$user = GetUser();
		$lists = $user->GetLists();
		$listids = array_keys($lists);
		$stats_api = $this->GetApi('Stats');

		$idx_calendar = array('DateType' => 'last7days');
		IEM::sessionSet('IndexCalendar', $idx_calendar);

		$rightnow = AdjustTime(0, true);

		$today = AdjustTime(array(0, 0, 0, date('m'), date('d'), date('Y')), true, null, true);

		$time = AdjustTime(array(0, 0, 0, date('m'), date('d') - 6, date('Y')), true, null, true);

		$query = ' AND (%%TABLE%% >= ' . $time . ')';

		$restrictions = array();
		$restrictions['subscribes'] = str_replace('%%TABLE%%', 'subscribedate', $query);
		$restrictions['unsubscribes'] = str_replace('%%TABLE%%', 'unsubscribetime', $query);
		$restrictions['bounces'] = str_replace('%%TABLE%%', 'bouncetime', $query);
		$restrictions['forwards'] = str_replace('%%TABLE%%', 'forwardtime', $query);

		$data = $stats_api->GetSubscriberGraphData('last7days', $restrictions, $listids);

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

		IEM::sessionSet('IndexSubscriberGraphData', $data);

		$data_url = 'stats_chart.php?graph=' . urlencode(strtolower('subscribersummary')) . '&Area='.urlencode(strtolower('list')) . '&statid=0&i=1&' . IEM::SESSION_NAME . '=' . IEM::sessionID();

		$chart = InsertChart('column', $data_url);
		echo $chart;
	}
コード例 #12
0
    /**
     * ProcessJob
     * Does most of the work setting up the job (creates the queue, removes duplicates and so on) to run. Once the job has been set up ready to run, it 'Actions' the job, then marks it as 'finished'.
     *
     * @param Int $jobid The job to run.
     *
     * @see Email_API
     * @see Subscriber_API
     * @see Lists_API
     * @see newsletter_api
     * @see GetUser
     * @see StartJob
     * @see GetJobQueue
     * @see CreateQueue
     * @see JobQueue
     * @see Subscribers_API::GetSubscribers
     * @see RemoveDuplicatesInQueue
     * @see RemoveBannedEmails
     * @see ActionJob
     * @see FinishJob
     *
     * @return Boolean Returns false if the job can't be started. Otherwise runs the job and returns true.
     */
    function ProcessJob($jobid=0) {
        if (!$this->StartJob($jobid)) {
            $this->PauseJob($jobid);
            $this->jobstatus = 'p';
            trigger_error("Unable to start send job {$jobid}");
            return false;
        }

        $user = GetUser($this->jobowner);
        IEM::userLogin($this->jobowner, false);

        $queueid = false;

        // if there's no queue, start one up.
        if (!$queueid = $this->GetJobQueue($jobid)) {
            $sendqueue = $this->CreateQueue('send');
            $queueok = $this->JobQueue($jobid, $sendqueue);
            $send_criteria = $this->jobdetails['SendCriteria'];

            $original_queuesize = $this->jobdetails['SendSize'];

            $queueinfo = array('queueid' => $sendqueue, 'queuetype' => 'send', 'ownerid' => $this->jobowner);

            if (isset($this->jobdetails['Segments']) && is_array($this->jobdetails['Segments'])) {
                $this->Subscriber_API->GetSubscribersFromSegment($this->jobdetails['Segments'], false, $queueinfo, 'nosort');
            } else {
                $this->Subscriber_API->GetSubscribers($send_criteria, array(), false, $queueinfo, $sendqueue);
            }

            $this->Subscriber_API->RemoveDuplicatesInQueue($sendqueue, 'send', $this->jobdetails['Lists']);

            $this->Subscriber_API->RemoveBannedEmails($this->jobdetails['Lists'], $sendqueue, 'send');

            $this->Subscriber_API->RemoveUnsubscribedEmails($this->jobdetails['Lists'], $sendqueue, 'send');

            $queueid = $sendqueue;

            $newsletterstats = $this->jobdetails;
            $newsletterstats['Job'] = $jobid;
            $newsletterstats['Queue'] = $sendqueue;
            $newsletterstats['SentBy'] = $queueinfo['ownerid'];

            $real_queuesize = $this->Subscriber_API->QueueSize($queueid, 'send');

            $newsletterstats['SendSize'] = $real_queuesize;

            $statid = $this->Stats_API->SaveNewsletterStats($newsletterstats);

            /**
             * Process tracker request where because cron was not enabled, we need to parse the option straight away
             * @todo Result for the call to module_Tracker::ParseOptionsForAllTracker() is not being processed and being ignored
             */
            $tempAPIFile = dirname(__FILE__) . '/module_trackerfactory.php';
            if (is_file($tempAPIFile)) {
                require_once($tempAPIFile);
                $temp = array_merge($this->jobdetails, array('statid' => $statid,
                    'stattype' => 'newsletter',
                    'newsletterid' => $this->jobdetails['Newsletter']));

                $status = module_Tracker::ParseOptionsForAllTracker($temp);
            }
            /**
             * -----
             */
            /**
             * So we can link user stats to send stats, we need to update it.
             */
            $this->Stats_API->UpdateUserStats($queueinfo['ownerid'], $jobid, $statid);

            /**
             * The 'queuesize' in the stats_users table is updated by MarkNewsletterFinished in send.php
             * so we don't need to worry about it while setting up the send.
             * That takes into account whether some recipients were skipped because a html-only email was sent etc.
             */
            /**
             * We re-check the user stats in case a bunch of subscribers have joined, or the user has done something like:
             * - create a list
             * - added a few subscribers
             * - scheduled a send
             * - added more subscribers
             */
            $check_stats = $this->Stats_API->ReCheckUserStats($user, $original_queuesize, $real_queuesize, AdjustTime());

            list($ok_to_send, $not_ok_to_send_reason) = $check_stats;
            if (!$ok_to_send) {
                trigger_error(__CLASS__ . '::' . __METHOD__ . " -- " . GetLang($not_ok_to_send_reason), E_USER_WARNING);
                $this->PauseJob($jobid);
                $this->UnapproveJob($jobid);
                IEM::userLogout();
                return false;
            }

            API_USERS::creditEvaluateWarnings($user->GetNewAPI());
        }

        $this->statid = $this->LoadStats($jobid);
        if (empty($this->statid)) {
            trigger_error(__CLASS__ . '::' . __METHOD__ . " -- Cannot find statid. Previous preliminary job process did not get finalized (either CRON died, or it hasn't finished processing the job). Ignoring this job: jobid {$jobid}.", E_USER_NOTICE);
            IEM::userLogout();
            return false;
        }

        $queuesize = $this->Subscriber_API->QueueSize($queueid, 'send');

        // used by send.php::CleanUp
        $this->queuesize = $this->jobdetails['SendSize'];

        /**
         * There's nothing left? Just mark it as done.
         */
        if ($queuesize == 0) {
            $this->jobstatus = 'c';
            $this->FinishJob($jobid);
            IEM::userLogout();
            return true;
        }

        $finished = $this->ActionJob($jobid, $queueid);

        if ($finished) {
            $this->jobstatus = 'c';
            $this->FinishJob($jobid);
        }

        IEM::userLogout();
        return true;
    }
コード例 #13
0
ファイル: stats.php プロジェクト: hungnv0789/vhtm
	/**
	* PrintListStats_Step2
	* Print mailing list statistics for the list selected. This includes all sorts of stuff.
	* It checks to make sure you're not trying to view someone elses statistics before anything else.
	*
	* @param Int $listid The listid to print statistics for.
	*
	* @see Stats_Chart::Process
	*
	* @return Void Prints out the list of statistics for this particular mailing list. It doesn't return anything.
	*/
	function PrintListStats_Step2($listid=0)
	{
		$listid = (int)$listid;

		$GLOBALS['Heading'] = GetLang('Stats_List_Step2_Heading');

		$user = IEM::userGetCurrent();
		$lists = $user->GetLists();
		if (!in_array($listid, array_keys($lists))) {
			$GLOBALS['SummaryIntro'] = sprintf(GetLang('Stats_List_Step2_Intro'), GetLang('Unknown_List'));
			$this->DenyAccess();
			return;
		}

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

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

		// Log this to "User Activity Log"
		IEM::logUserActivity($_SERVER['REQUEST_URI'], 'images/chart_bar.gif', $listapi->name);

		$GLOBALS['SummaryIntro'] = sprintf(GetLang('Stats_List_Step2_Intro'), htmlspecialchars($listapi->Get('name'), ENT_QUOTES, SENDSTUDIO_CHARSET));

		$GLOBALS['TabID'] = '7';

		$base_action = 'SubAction=List&NextAction=ViewSummary&list=' . $listid;

		$this->SetupCalendar('Action=ProcessCalendar&' . $base_action);

		$statsapi = $this->GetApi();

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

		$statsapi->CalculateStatsType();

		$restrictions = array();
		if (isset($calendar_dates['subscribers'])) {
			$restrictions = $calendar_dates['subscribers'];
		}


		$summary = $statsapi->GetListSummary($listid);

		IEM::sessionSet('ListStatistics', $summary['statids']);

		$data = $statsapi->GetSubscriberGraphData($statsapi->stats_type, $restrictions, $listid);

		$domain_data = $statsapi->GetSubscriberDomainGraphData($restrictions, $listid);

		IEM::sessionSet('SubscriberGraphData', $data);

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

		$GLOBALS['SummaryChart'] = InsertChart('column', $data_url, array('graph_title' => GetLang("List_Summary_Graph_subscribersummary")));

		$areas = array('unconfirms', 'confirms', 'unsubscribes', 'bounces', 'forwards');
		$now = getdate();
		$today = $now['0'];

		$totals = array('unconfirms' => 0, 'confirms' => 0, 'unsubscribes' => 0, 'forwards' => 0, 'bounces' => 0);
		$domain_totals = array('unconfirms' => 0, 'confirms' => 0, 'unsubscribes' => 0, 'forwards' => 0, 'bounces' => 0);

		$time_display = '';

		$this_year = date('Y');

		switch ($statsapi->calendar_type) {
			case 'today':
			case 'yesterday':
				for ($i = 0; $i < 24; $i++) {

					$server_time = AdjustTime(array($i, 1, 1, 1, 1, $this_year), true);
					$GLOBALS['Name'] = $this->PrintDate($server_time, GetLang('Daily_Time_Display'));

					foreach ($areas as $k => $area) {
						$GLOBALS[$area] = 0;
						foreach ($data[$area] as $p => $details) {
							if ($details['hr'] == $i) {
								$GLOBALS[$area] = $this->FormatNumber($details['count']);
								$totals[$area] += $details['count'];
								break;
							}
						}
						if (empty($data)) {
							break;
						}
					}
					$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
				}
			break;

			case 'last24hours':
				$hours_now = $now['hours'];

				$i = 24;
				while ($i > 0) {
					$yr = AdjustTime(array($hours_now, 1, 1, 1, 1, $this_year), true, null, true);
					$GLOBALS['Name'] = $this->PrintDate($yr, GetLang('Daily_Time_Display'));

					$hour_check = date('G', $yr);

					foreach ($areas as $k => $area) {
						$GLOBALS[$area] = 0;
						foreach ($data[$area] as $p => $details) {
							if ($details['hr'] == $hour_check) {
								$GLOBALS[$area] = $this->FormatNumber($details['count']);
								$totals[$area] += $details['count'];
								break;
							}
						}
						if (empty($data)) {
								$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
							break 2;
						}
					}
					$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);

					$hours_now--;

					$i--;
				}
			break;

			case 'last7days':

				$date = AdjustTime($today, true, null, true);

				$i = 7;
				while ($i > 0) {
					$GLOBALS['Name'] = $this->PrintDate($date, GetLang('DOW_Word_Full_Display'));

					foreach ($areas as $k => $area) {
						$GLOBALS[$area] = 0;
						foreach ($data[$area] as $p => $details) {
							if ($details['dow'] == date('w', $date)) {
								$GLOBALS[$area] = $this->FormatNumber($details['count']);
								$totals[$area] += $details['count'];
								break;
							}
						}
						if (empty($data)) {
							$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
							break 2;
						}
					}
					$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);

					$date = $date - 86400; // take off one day each time.

					$i--;
				}
			break;

			case 'last30days':

				$date = $today;

				$i = 30;
				while ($i > 0) {
					$GLOBALS['Name'] = $this->PrintDate($date);

					foreach ($areas as $k => $area) {
						$GLOBALS[$area] = 0;
						foreach ($data[$area] as $p => $details) {
							if ($details['dom'] == date('j', $date)) {
								$GLOBALS[$area] = $this->FormatNumber($details['count']);
								$totals[$area] += $details['count'];
								break;
							}
						}
						if (empty($data)) {
								$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
							break 2;
						}
					}
					$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);

					$date = $date - 86400; // take off one day each time.

					$i--;
				}
			break;

			case 'thismonth':
			case 'lastmonth':
				if ($statsapi->calendar_type == 'thismonth') {
					$month = $now['mon'];
				} else {
					$month = $now['mon'] - 1;
				}

				$timestamp = AdjustTime(array(1, 1, 1, $month, 1, $now['year']), true);

				$days_of_month = date('t', $timestamp);

				for ($i = 1; $i <= $days_of_month; $i++) {
					$GLOBALS['Name'] = $this->PrintDate($timestamp);

					foreach ($areas as $k => $area) {
						$GLOBALS[$area] = 0;
						foreach ($data[$area] as $p => $details) {
							if ($details['dom'] == $i) {
								$GLOBALS[$area] = $this->FormatNumber($details['count']);
								$totals[$area] += $details['count'];
								break;
							}
						}
					}

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

					$timestamp += 86400;
				}
			break;

			default:
				$calendar_settings = $user->GetSettings('Calendar');
				$found = false;
				foreach ($areas as $k => $area) {
					foreach ($data[$area] as $p => $details) {
						if ($details['count'] > 0) {
							$found = true;
							break 2;
						}
					}
				}

				if ($found) {
					if ($statsapi->stats_type == 'last7days') {
						$date = AdjustTime(array(1, 1, 1, $calendar_settings['From']['Mth'], 1, $calendar_settings['From']['Yr']), true);

						$i = 7;
						while ($i > 0) {
							$GLOBALS['Name'] = $this->PrintDate($date, GetLang('DOW_Word_Full_Display'));

							foreach ($areas as $k => $area) {
								$GLOBALS[$area] = 0;
								foreach ($data[$area] as $p => $details) {
									if ($details['dow'] == date('w', $date)) {
										$GLOBALS[$area] = $this->FormatNumber($details['count']);
										$totals[$area] += $details['count'];
										break;
									}
								}
								if (empty($data)) {
									$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
									break 2;
								}
							}
							$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);

							$date = $date - 86400; // take off one day each time.

							$i--;
						}
					}

					if ($statsapi->stats_type == 'monthly') {
						$timestamp = AdjustTime(array(1, 1, 1, $calendar_settings['From']['Mth'], 1, $calendar_settings['From']['Yr']), true);

						$days_of_month = date('t', $timestamp);

						for ($i = 1; $i <= $days_of_month; $i++) {
							$GLOBALS['Name'] = $this->PrintDate($timestamp);

							foreach ($areas as $k => $area) {
								$GLOBALS[$area] = 0;
								foreach ($data[$area] as $p => $details) {
									if ($details['dom'] == $i) {
										$GLOBALS[$area] = $this->FormatNumber($details['count']);
										$totals[$area] += $details['count'];
										break;
									}
								}
							}

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

							$timestamp += 86400;
						}
					}

					if ($statsapi->stats_type != 'last7days' && $statsapi->stats_type != 'monthly') {
                                                $now = getdate();
						$month = $now['mon'];
						for ($i = 1; $i <= 12; $i++) {
							$found_stats = false;
							foreach ($areas as $k => $area) {
								$GLOBALS[$area] = 0;
								foreach ($data[$area] as $p => $details) {
									if ($details['mth'] == $month) {
                                                                                $GLOBALS['Name'] = GetLang($this->Months[$month]) . $details['yr'];
                                                                                $GLOBALS[$area] = $this->FormatNumber($details['count']);
                                                                                $totals[$area] += $details['count'];
                                                                                $found_stats = true;
                                                                        }

								}
							}

                                                        $month = $month==1 ? 12 : $month-1;

							if ($found_stats) {
                                                            $time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
							}
						}
					}
				} else {
					$GLOBALS['Name'] = '&nbsp;';
					$time_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
				}
			break;
		}

		$GLOBALS['DisplayList'] = $time_display;

		$domain_lines = array();

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

		$graph_details = array();

		$domain_display = '';
		if (!empty($domain_lines)) {
			foreach ($domain_lines as $domain_name => $domain_info) {
				$GLOBALS['Name'] = htmlspecialchars($domain_name, ENT_QUOTES, SENDSTUDIO_CHARSET);
				foreach ($domain_info as $area => $count) {
					$GLOBALS[$area] = $this->FormatNumber($count);
					$domain_totals[$area] += $count;
					if ($area == 'confirms') {
						if (!isset($graph_details[$domain_name])) {
							$graph_details[$domain_name] = 0;
						}
						$graph_details[$domain_name] += $count;
						continue;
					}
				}
				$domain_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
			}
		} else {
			$GLOBALS['Name'] = '';
			foreach ($areas as $k => $area) {
				$GLOBALS[$area] = 0;
			}
			$domain_display .= $this->ParseTemplate('Stats_List_Step3_Row', true, false);
		}

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

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

		$page = $this->ParseTemplate('Stats_List_Step3', true, false);

		$base_action = 'SubAction=List&NextAction=ViewSummary&list=' . $listid . '&tab=7';

		$this->SetupCalendar('Action=ProcessCalendar&' . $base_action);

		$GLOBALS['DisplayDomainList'] = $domain_display;

		if (!empty($domain_lines)) {
			$this->DisplayChart('DomainChart', 'SubscriberDomains', '0','pie',array(
			 'hide_labels_percent' => 2,
			 'group_percent' => 2,
			 'x_position' => '',
			 'radius' => 85,
			 'graph_title' => GetLang("ListStatistics_Snapshot_PerDomain")
			));
		}

		$subscriber_count = $listapi->Get('subscribecount');

		if ($subscriber_count <= 0) {
			$GLOBALS['Error'] = GetLang('Stats_NoSubscribersOnList');
			$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
			$domain_page = $this->ParseTemplate('Stats_List_Step3_Domains_Empty', true, false);
		} elseif (empty($domain_lines)) {
			$GLOBALS['Error'] = GetLang('Stats_NoSubscribersOnList_DateRange');
			$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
			$domain_page = $this->ParseTemplate('Stats_List_Step3_Domains_Empty', true, false);
		} else {
			$domain_page = $this->ParseTemplate('Stats_List_Step3_Domains', true, false);
		}

		$page = str_replace('%%TPL_DomainPage%%', $domain_page, $page);

		// by default this is for all opens, not unique opens.
		$unique_only = false;
		if (isset($_GET['Unique'])) {
			$unique_only = true;
		}

		$chosen_bounce_type = '';
		if (isset($_GET['bouncetype'])) {
			$chosen_bounce_type = $_GET['bouncetype'];
		}

		$chosen_link = 'a';
		if (isset($_GET['link'])) {
			if (is_numeric($_GET['link'])) {
				$chosen_link = $_GET['link'];
			}
		}

		$summary['listname'] = $listapi->Get('name');

		// we need to process the opens page first because it sets the number of opens used in a calculation for the links page.
		$open_page = $this->DisplayListOpens($listid, $summary, $unique_only);

		$links_page = $this->DisplayListLinks($listid, $summary, $chosen_link);

		$bounces_page = $this->DisplayListBounces($listid, $summary, $chosen_bounce_type);

		$unsubscribes_page = $this->DisplayListUnsubscribes($listid, $summary);
		$forwards_page = $this->DisplayListForwards($listid, $summary);

		$page = str_replace(array('%%TPL_OpensPage%%', '%%TPL_LinksPage%%', '%%TPL_BouncesPage%%', '%%TPL_UnsubscribesPage%%', '%%TPL_ForwardsPage%%'), array($open_page, $links_page, $bounces_page, $unsubscribes_page, $forwards_page), $page);

		if (isset($_GET['tab'])) {
			$page .= '
			<script>
				ShowTab(' . $_GET['tab'] . ');
			</script>
			';
		}
		echo $page;
	}
コード例 #14
0
ファイル: survey_templates.php プロジェクト: hungnv0789/vhtm
 /**
  * Admin_Action_Templates_Default
  * Prints the list of templates
  *
  * @return Void Returns nothing
  */
 public function Admin_Action_Templates_Default()
 {
     $api = self::getApi();
     $user = GetUser();
     /**
      * Add the add button and print flash messages
      */
     $this->template_system->Assign('Add_Button', $this->template_system->ParseTemplate('add_survey_template_button', true), false);
     $this->template_system->Assign('Message', GetFlashMessages(), false);
     /**
      * If there are no templates print an empty message
      */
     $numsurveys = $api->GetTemplates($user->userid, 0, 0, array(), array(), true);
     if ($numsurveys == 0) {
         $this->template_system->ParseTemplate('manage_templates_empty');
         return;
     }
     /**
      * The default sort details
      */
     $sort_details = array('SortBy' => 'name', 'Direction' => 'asc');
     /**
      * If valid sorting details are given overwrite the defaults
      */
     if (isset($_GET['SortBy']) && in_array(strtolower($_GET['SortBy']), $api->validSorts)) {
         $sort_details['SortBy'] = strtolower($_GET['SortBy']);
     }
     if (in_array(strtolower($_GET['Direction']), array('up', 'down'))) {
         $direction = strtolower($_GET['Direction']);
         if ($direction == 'up') {
             $sort_details['Direction'] = 'asc';
         } else {
             $sort_details['Direction'] = 'desc';
         }
     }
     $perpage = $this->GetPerPage();
     if (isset($_GET['PerPageDisplay'])) {
         $perpage = (int) $_GET['PerPageDisplay'];
         $this->SetPerPage($perpage);
     }
     $page = (int) $_GET['DisplayPage'];
     if ($page < 1) {
         $page = 1;
     }
     $paging = $this->SetupPaging($this->admin_url, $numsurveys);
     $this->template_system->Assign('Paging', $paging, false);
     $search_info = array();
     $surveys = $api->GetTemplates($user->userid, $page, $perpage, $search_info, $sort_details, false);
     $survey_rows = '';
     foreach ($surveys as $survey) {
         $this->template_system->Assign('name', $survey['name']);
         $this->template_system->Assign('surveyid', $survey['surveyid']);
         $this->template_system->Assign('created', AdjustTime($survey['created'], false, GetLang('DateFormat'), true));
         /**
          * add the edit link
          */
         $editlink = '<a href="' . $this->admin_url . '&Action=Edit&id=' . $survey['surveyid'] . '">' . GetLang('Edit') . '</a>';
         $this->template_system->Assign('edit_link', $editlink, false);
         /**
          * add the delete link
          */
         $deletelink = '<a href="' . $this->admin_url . '&Action=Delete&id=' . $survey['surveyid'] . '">' . GetLang('Delete') . '</a>';
         $this->template_system->Assign('delete_link', $deletelink, false);
         $survey_rows .= $this->template_system->ParseTemplate('manage_surveys_row', true);
     }
     $this->template_system->Assign('Items', $survey_rows, false);
     $this->template_system->ParseTemplate('templates_manage');
 }
コード例 #15
0
ファイル: stats_chart.php プロジェクト: hungnv0789/vhtm
	/**
	* SetupChartDates
	* This sets default values for the charts, works out 'skip' criteria and puts the basic chart information together, ready for SetupChart_Subscribers and SetupChart to use.
	*
	* @see calendar_type
	* @see chart
	* @see SetupChart_SubscriberSummary
	* @see SetupChart
	*
	* @return Void Doesn't return anything, updates data in the chart class variable.
	*/
	function SetupChartDates($chart_type=false)
	{
		$num_areas = 1;

		if ($chart_type == 'subscribersummary') {
			$num_areas = 5;
		}

		if ($chart_type == 'bouncechart') {
			$num_areas = 2;
		}

		$now = getdate();

		switch ($this->stats_api->calendar_type) {
			case 'last24hours':
				$this->chart['axis_category']['skip'] = 2;
				/**
				* Here we go backwards so "now" is on the far right hand side
				* and yesterday is on the left
				*/
				$hours_now = $now['hours'];

				$server_time = AdjustTime(array($hours_now, 1, 1, 1, 1, $now['year']), true, null, true);

				$this->chart['chart_data'][0][24] = $this->PrintDate($server_time, GetLang('Daily_Time_Display'));

				for ($i = 1; $i <= $num_areas; $i++) {
					$this->chart['chart_data'][$i][24] = 0;
					$this->chart['chart_value_text'][$i][24] = 0;
				}

				$i = 23;
				while ($i > 0) {
					$hours_now--;

					$server_time = AdjustTime(array($hours_now, 1, 1, 1, 1, $now['year']), true, null, true);
					$this->chart['chart_data'][0][$i] = $this->PrintDate($server_time, GetLang('Daily_Time_Display'));

					for ($x = 1; $x <= $num_areas; $x++) {
						$this->chart['chart_data'][$x][$i] = 0;
						$this->chart['chart_value_text'][$x][$i] = 0;
					}

					$i--;
				}
			break;

			case 'today':
			case 'yesterday':
				$this->chart['axis_category']['skip'] = 2;

				for ($i = 0; $i < 24; $i++) {
					$server_time = AdjustTime(array($i, 1, 1, 1, 1, $now['year']), true);
					$this->chart['chart_data'][0][$i + 1] = $this->PrintDate($server_time, GetLang('Daily_Time_Display'));

					for ($x = 1; $x <= $num_areas; $x++) {
						$this->chart['chart_data'][$x][$i + 1] = 0;
						$this->chart['chart_value_text'][$x][$i + 1] = 0;
					}
				}
			break;

			case 'last7days':
				$this->chart['axis_category']['skip'] = 0;

				$today = $now['0'];

				$this->chart['chart_data'][0][7] = GetLang($this->days_of_week[$now['wday']]);

				for ($t = 1; $t <= $num_areas; $t++) {
					$this->chart['chart_data'][$t][7] = 0;
					$this->chart['chart_value_text'][$t][7] = 0;
				}

				$date = $today;
				$i = 6;
				while ($i > 0) {
					$date = $date - 86400; // take off one day each time.
					$datenow = getdate($date);
					$this->chart['chart_data'][0][$i] = GetLang($this->days_of_week[$datenow['wday']]);

					for ($x = 1; $x <= $num_areas; $x++) {
						$this->chart['chart_data'][$x][$i] = 0;
						$this->chart['chart_value_text'][$x][$i] = 0;
					}
					$i--;
				}
			break;

			case 'last30days':
				$this->chart['axis_category']['skip'] = 1;

				$today = $now['0'];
				$this->chart['chart_data'][0][30] = $this->PrintDate($today, GetLang('DOM_Number_Display'));

				for ($x = 1; $x <= $num_areas; $x++) {
					$this->chart['chart_data'][$x][30] = 0;
					$this->chart['chart_value_text'][$x][30] = 0;
				}

				$date = $today;
				$i = 29;
				while ($i > 0) {
					$date = $date - 86400; // take off one day each time.
					$this->chart['chart_data'][0][$i] = $this->PrintDate($date, GetLang('DOM_Number_Display'));

					for ($x = 1; $x <= $num_areas; $x++) {
						$this->chart['chart_data'][$x][$i] = 0;
						$this->chart['chart_value_text'][$x][$i] = 0;
					}

					$i--;
				}
			break;

			case 'thismonth':
			case 'lastmonth':
				if ($this->stats_api->calendar_type == 'thismonth') {
					$month = $now['mon'];
				} else {
					$month = $now['mon'] - 1;
				}

				$timestamp = AdjustTime(array(1, 1, 1, $month, 1, $now['year']), true);

				$days_of_month = date('t', $timestamp);

				for ($i = 1; $i <= $days_of_month; $i++) {
					$this->chart['chart_data'][0][$i] = $this->PrintDate($timestamp, GetLang('DOM_Number_Display'));

					for ($x = 1; $x <= $num_areas; $x++) {
						$this->chart['chart_data'][$x][$i] = 0;
						$this->chart['chart_value_text'][$x][$i] = 0;
					}

					$timestamp += 86400;
				}
			break;

			default:
				$this->chart['axis_category']['skip'] = 0;
				if ($this->stats_api->stats_type != 'monthly' && $this->stats_api->stats_type != 'last7days') {
					$month = $now['mon'];
					for ($i = 1; $i <= 12; $i++) {
						$this->chart['chart_data'][0][$i] = GetLang($this->Months[$month]);
						$month--;
						if ($month == 0) {
							$month = 12;
						}

						for ($x = 1; $x <= $num_areas; $x++) {
							$this->chart['chart_data'][$x][$i] = 0;
							$this->chart['chart_value_text'][$x][$i] = 0;
						}
					}
				}

				$user = GetUser();

				$calendar_settings = $user->GetSettings('Calendar');

				if ($this->stats_api->stats_type == 'monthly') {
					$month = $calendar_settings['From']['Mth'];
					$year = $calendar_settings['From']['Yr'];
					$timestamp = AdjustTime(array(1, 1, 1, $month, 1, $year), true);

					$days_of_month = date('t', $timestamp);

					for ($i = 1; $i <= $days_of_month; $i++) {
						$this->chart['chart_data'][0][$i] = $this->PrintDate($timestamp, GetLang('DOM_Number_Display'));

						for ($x = 1; $x <= $num_areas; $x++) {
							$this->chart['chart_data'][$x][$i] = 0;
							$this->chart['chart_value_text'][$x][$i] = 0;
						}

						$timestamp += 86400;
					}
				}

				if ($this->stats_api->stats_type == 'last7days') {
					$this->chart['axis_category']['skip'] = 0;

					$today = $now['0'];

					$this->chart['chart_data'][0][7] = GetLang($this->days_of_week[$now['wday']]);

					for ($t = 1; $t <= $num_areas; $t++) {
						$this->chart['chart_data'][$t][7] = 0;
						$this->chart['chart_value_text'][$t][7] = 0;
					}

					$date = $today;
					$i = 6;
					while ($i > 0) {
						$date = $date - 86400; // take off one day each time.
						$datenow = getdate($date);
						$this->chart['chart_data'][0][$i] = GetLang($this->days_of_week[$datenow['wday']]);

						for ($x = 1; $x <= $num_areas; $x++) {
							$this->chart['chart_data'][$x][$i] = 0;
							$this->chart['chart_value_text'][$x][$i] = 0;
						}
						$i--;
					}
				}
			break;
		}
	}
コード例 #16
0
	/**
	* ExportSubscriber
	* Actually does the exporting of the subscriber.  Gets what it needs to export from the session, prints out the subscriber info to the export file.
	*
	* @param Int $subscriberid The subscriber to export.
	* @param Int $listid The list id subscriber is listed on
	* @param boolean $first Indicates whether or not this is the first record, used only by XML export (OPTIONAL)
	* @param boolean $last Indicates whether or not this is the last record, used only by XML export (OPTIONAL)
	*
	* @see GetApi
	* @see Subscribers_API::LoadSubscriberList
	* @see Subscribers_API::GetCustomFieldSettings
	*
	* @return Void Exports the subscriber information to the export file.
	*/
	function ExportSubscriber($subscriberid=0, $listid=0, $first = false, $last = false)
	{

		$exportinfo = IEM::sessionGet('ExportInfo');

		$list = $listid;
		$exportfile = $exportinfo['ExportFile'];
		$exportsettings = $exportinfo['Settings'];

		$subscriberApi = $this->GetApi('Subscribers');
		$subscriberinfo = $subscriberApi->LoadSubscriberList($subscriberid, $list);

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

		$bounce_info = false;

		if (in_array('btype', $exportsettings['FieldOptions'])) {
			$bounce_info = $subscriberApi->LoadSubscriberBounceInfo($subscriberid, $list);
		}

		if (in_array('btime', $exportsettings['FieldOptions'])) {
			if (!$bounce_info) {
				$bounce_info = $subscriberApi->LoadSubscriberBounceInfo($subscriberid, $list);
			}
		}

		if ($bounce_info) {
			$this->LoadLanguageFile('Stats');
		}

		$parts = array();
		foreach ($exportsettings['FieldOptions'] as $pos => $type) {
			switch (strtolower($type)) {
				case 'n':
					continue;
				break;

				case 'e':
					$parts[] = $subscriberinfo['emailaddress'];
				break;

				case 'f':
					$parts[] = ($subscriberinfo['format'] == 'h') ? GetLang('Format_HTML') : GetLang('Format_Text');
				break;

				case 'c':
					$parts[] = ($subscriberinfo['confirmed']) ? GetLang('Confirmed') : GetLang('Unconfirmed');
				break;

				case 'dmy':
					$parts[] = AdjustTime($subscriberinfo['subscribedate'], false, 'd/m/Y');
				break;

				case 'mdy':
					$parts[] = AdjustTime($subscriberinfo['subscribedate'], false, 'm/d/Y');
				break;

				case 'ymd':
					$parts[] = AdjustTime($subscriberinfo['subscribedate'], false, 'Y/m/d');
				break;

				case 'i':
					// if they have a confirm ip, we'll use that.
					$ip = $subscriberinfo['confirmip'];

					// if they don't have a confirm ip, check for the request ip.
					if (!$ip) {
						$ip = $subscriberinfo['requestip'];
					}

					// if they still don't have an ip then chuck in a message.
					if (!$ip) {
						$ip = GetLang('SubscriberIP_Unknown');
					}
					$parts[] = $ip;
				break;

				case 'btime':
					$parts[] = AdjustTime($bounce_info['bouncetime'], false, GetLang('BounceTimeFormat'));
				break;

				case 'btype':
					$parts[] = sprintf(GetLang('BounceTypeFormat'), GetLang('Bounce_Rule_' . $bounce_info['bouncerule']), $bounce_info['bouncetype']);
				break;

				default:
					if (is_numeric($type)) {
						$customfield_data = $subscriberApi->GetCustomFieldSettings($type, true);

						//if ($customfield_data['fieldtype'] == 'checkbox') {
							/**
							* See if we have loaded this custom field yet or not.
							* If we haven't then load it up.
							*
							* If we have, then use that instead for the checkdata calls.
							*
							* Doing it this way saves a lot of db queries/overhead especially with lots of custom fields.
							*/
							$fieldid = $customfield_data['fieldid'];

							if (!in_array($fieldid, array_keys($this->_customfields_loaded))) {
								$field_options = $CustomFieldApi->Load($fieldid, false, true);
								$subfield = $CustomFieldApi->LoadSubField($field_options);
								$this->_customfields_loaded[$fieldid] = $subfield;
							}

							$subf = $this->_customfields_loaded[$fieldid];
							$customfield_data['data'] = $subf->GetRealValue($customfield_data['data']);
						//}

						if (!isset($customfield_data['data'])) {
							$parts[] = '';
							continue;
						}

						$customfield_data = $customfield_data['data'];

						if (!is_array($customfield_data)) {
							if (substr_count($customfield_data, $exportsettings['FieldSeparator']) > 0) {
								if ($exportsettings['FieldEnclosedBy'] == '') {
									$customfield_data = '"' . $customfield_data . '"';
								}
							}

							$parts[] = $customfield_data;
							continue;
						}

						if ($exportsettings['FieldEnclosedBy'] != '') {
							$customfield_sanitized = implode(',', $customfield_data);
						} else {
							if (sizeof($customfield_data) > 1) {
								$customfield_sanitized = '"' . implode(',', $customfield_data) . '"';
							} else {
								$customfield_sanitized = implode(',', $customfield_data);

								if (substr_count($customfield_sanitized, $exportsettings['FieldSeparator']) > 0) {
									$customfield_sanitized = '"' . $customfield_sanitized . '"';
								}
							}
						}
						$parts[] = $customfield_sanitized;
					}
				break;
			}
		}


		switch($exportsettings['FileType']) {
			case 'xml':
				$line = '';

				if($first) {
					$line = "\t".'<records>'."\n";
				}

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

				if($last) {
					$line .= "\t".'</records>' . "\n" . '</export>' . "\n";
				}
			break;

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

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

		$fp = fopen(TEMP_DIRECTORY . '/' . $exportinfo['ExportFile'], 'a');
		fputs($fp, $line, strlen($line));
		fclose($fp);
	}
コード例 #17
0
	/**
	* Copy
	* Copy segment details
	*
	* @param Int $segmentID Segment ID to copy.
	*
	* @return Array Returns an array of status (whether the copy worked or not) and a message to go with it. If the copy worked, then the message is the new ID.
	*/
	function Copy($segmentID)
	{
		$segmentID = intval($segmentID);
		if ($segmentID <= 0) {
			return array(false, 'No ID');
		}

		if (!$this->Load($segmentID)) {
			return array(false, 'Unable to load segment to be copied.');
		}

		$currentuser = GetUser();

		$this->segmentname = GetLang('CopyPrefix') . $this->segmentname;
		$this->ownerid = $currentuser->userid;
		$this->createdate = AdjustTime();

		$status = $this->Create();
		if (!$status) {
			return array(false, 'Unable to create new segment');
		}

		return array(true, $this->segmentid);
	}
コード例 #18
0
	/**
	* NotifyAdmin
	* Notifies the administrator when a user has exceeded their quota
	*
	* @param Int $userid The userid the notification is for
	* @param Int $size_difference The number of emails the user has exceeded their limit by
	* @param Int $queuetime The time the queue was created at
	* @param String $langvar The langvar to use to describe which limit has been exceeded. This langvar is returned by the CheckUserStats/ReCheckuserStats functions.
	* @param Boolean $stopped_send Specify true if the send has been halted, false if the send is continuing
	*
	* @see Stats_API::ReCheckUserStats
	* @see Stats_API::CheckUserStats
	*
	* @return Void Returns nothing
	*/
	function NotifyAdmin($userid, $size_difference, $queuetime, $langvar, $stopped_send=false)
	{
		$user = GetUser($userid);
		$user_queuetime = AdjustTime($queuetime, false, GetLang('UserDateFormat'));

		require_once(IEM_PATH . '/ext/interspire_email/email.php');

		$email_api = new Email_API();

		$email_api->Set('Subject', GetLang('User_OverQuota_Subject'));

		$username = $user->Get('username');
		if ($user->fullname) {
			$username = $user->fullname;
			$email_api->Set('FromName', $user->fullname);
		} else {
			$email_api->Set('FromName', GetLang('SendingSystem'));
		}

		if ($user->emailaddress) {
			$email_api->Set('FromAddress', $user->emailaddress);
		} else {
			$email_api->Set('FromAddress', GetLang('SendingSystem_From'));
		}

		$over_size = number_format($size_difference, 0, GetLang('NumberFormat_Dec'), GetLang('NumberFormat_Thousands'));

		$extra_mail = '';
		if ($stopped_send) {
			$extra_mail = GetLang('User_OverQuota_StoppedSend');
		}

		$message = sprintf(GetLang('User_OverQuota_Email'), $username, $user->Get('emailaddress'), $user_queuetime, GetLang('User_'.$langvar), $over_size, $extra_mail);

		$email_api->Set('Multipart', false);

		$email_api->AddBody('text', $message);

		$email_api->ClearAttachments();
		$email_api->ClearRecipients();

		$email_api->AddRecipient(SENDSTUDIO_EMAIL_ADDRESS, '', 't');

		$email_api->Send();

		$email_api->ForgetEmail();

		// now send the user notification.

		$email_api->Set('Subject', GetLang('User_OverQuota_Subject'));

		$email_api->Set('FromName', '');

		$email_api->Set('FromAddress', SENDSTUDIO_EMAIL_ADDRESS);

		$message = sprintf(GetLang('User_OverQuota_ToUser_Email'), $user_queuetime, GetLang('User_'.$langvar), $over_size, $extra_mail);

		$email_api->Set('Multipart', false);

		$email_api->AddBody('text', $message);

		$email_api->ClearAttachments();
		$email_api->ClearRecipients();

		$email_api->AddRecipient($user->emailaddress, '', 't');

		$email_api->Send();

		$email_api->ForgetEmail();
	}
コード例 #19
0
 /**
  * Show_Send_Step_3
  * Step 3 shows the user a report including:
  * - which split test they are sending
  * - how many subscribers it will be sent to
  * - which lists/segments they are sending to
  *
  * The user has to confirm they want to either schedule the campaign
  * or they can start sending the split test campaign
  * or (in either case), they can "cancel" the send
  * eg they chose the wrong split test to send or something
  *
  * @uses Jobs_API
  * @uses Stats_API
  * @uses Splittest_Send_API
  * @uses CheckCronEnabled
  * @uses Splittest_API::Load
  * @uses Stats_API::CheckUserStats
  * @uses Lists_API
  * @uses Segment_API
  * @uses GetApi
  */
 public function Show_Send_Step_3()
 {
     $send_details = IEM::sessionGet('SplitTestSend');
     /**
      * Check the user has been through step 1 successfully.
      */
     if (!$send_details || !isset($send_details['splitid']) || (int) $send_details['splitid'] <= 0) {
         FlashMessage(GetLang('Addon_splittest_Send_InvalidSplitTest'), SS_FLASH_MSG_ERROR, $this->admin_url);
         return;
     }
     /**
      * Make sure we're posting a proper form.
      */
     if (empty($_POST)) {
         FlashMessage(GetLang('Addon_splittest_Send_InvalidSplitTest'), SS_FLASH_MSG_ERROR, $this->admin_url);
         return;
     }
     $required_fields = array('sendfromname' => 'EnterSendFromName', 'sendfromemail' => 'EnterSendFromEmail', 'replytoemail' => 'EnterReplyToEmail');
     $erors = array();
     foreach ($required_fields as $fieldname => $lang_description) {
         if (!isset($_POST[$fieldname])) {
             $errors[] = GetLang('Addon_splittest_Send_Step3_' . $lang_description);
             continue;
         }
         $posted_value = trim($_POST[$fieldname]);
         if ($posted_value == '') {
             $errors[] = GetLang('Addon_splittest_Send_Step3_' . $lang_description);
             continue;
         }
     }
     if (!empty($errors)) {
         $errormsg = implode('<br/>', $errors);
         FlashMessage(sprintf(GetLang('Addon_splittest_Send_Step3_FieldsMissing'), $errormsg), SS_FLASH_MSG_ERROR, $this->admin_url . '&Action=Send&Step=2');
         return;
     }
     require_once SENDSTUDIO_API_DIRECTORY . '/jobs.php';
     $jobapi = new Jobs_API();
     require_once SENDSTUDIO_API_DIRECTORY . '/stats.php';
     $statsapi = new Stats_API();
     $send_api = $this->GetApi('Splittest_Send');
     $send_details['SendFromName'] = $_POST['sendfromname'];
     $send_details['SendFromEmail'] = $_POST['sendfromemail'];
     $send_details['ReplyToEmail'] = $_POST['replytoemail'];
     /**
      * If the user has access to set bounce details, this will be available.
      * If they don't, we'll use the email from the settings page.
      */
     if (isset($_POST['bounceemail'])) {
         $send_details['BounceEmail'] = $_POST['bounceemail'];
     } else {
         $send_details['BounceEmail'] = SENDSTUDIO_BOUNCE_ADDRESS;
     }
     /**
      * Set the charset.
      */
     $send_details['Charset'] = SENDSTUDIO_CHARSET;
     $to_firstname = false;
     if (isset($_POST['to_firstname']) && (int) $_POST['to_firstname'] > 0) {
         $to_firstname = (int) $_POST['to_firstname'];
     }
     $send_details['To_FirstName'] = $to_firstname;
     $to_lastname = false;
     if (isset($_POST['to_lastname']) && (int) $_POST['to_lastname'] > 0) {
         $to_lastname = (int) $_POST['to_lastname'];
     }
     $send_details['To_LastName'] = $to_lastname;
     $send_details['SendStartTime'] = $send_api->GetServerTime();
     foreach (array('success', 'total', 'failure') as $area) {
         $send_details['EmailResults'][$area] = 0;
     }
     $send_details['NotifyOwner'] = 1;
     /**
      * Split campaigns have to track opens & link clicks
      * There's no other way they will work.
      */
     $send_details['TrackOpens'] = $send_details['TrackLinks'] = 1;
     $send_details['Multipart'] = 0;
     if (isset($_POST['multipart'])) {
         $send_details['Multipart'] = 1;
     }
     $send_details['EmbedImages'] = 0;
     if (isset($_POST['embedimages'])) {
         $send_details['EmbedImages'] = 1;
     }
     /**
      * If cron is enabled, we'll get new info we need to take into account.
      */
     if (self::CheckCronEnabled()) {
         /**
          * The default (from above) is to "notify", so if it's not set, don't notify.
          */
         if (!isset($_POST['notifyowner'])) {
             $send_details['NotifyOwner'] = 0;
         }
         /**
          * If we're not sending immediately, then check the date/time.
          * We don't allow sending in past dates.
          */
         if (!isset($_POST['sendimmediately'])) {
             $hrs = $_POST['sendtime_hours'];
             $am_pm = null;
             if (isset($_POST['sendtime_ampm'])) {
                 $am_pm = strtolower($_POST['sendtime_ampm']);
             }
             if ($am_pm == 'pm' && $hrs < 12) {
                 $hrs += 12;
             }
             if ($am_pm == 'am' && $hrs == 12) {
                 $hrs = 0;
             }
             $gmt_check_time = AdjustTime(array($hrs, $_POST['sendtime_minutes'], 0, $_POST['datetime']['month'], $_POST['datetime']['day'], $_POST['datetime']['year']), true);
             $now = $send_api->GetServerTime();
             /**
              * There's a leeway of 5 minutes just in case there are any server/time issues.
              */
             $leeway = 5 * 60;
             if ($gmt_check_time < $now - $leeway) {
                 FlashMessage(GetLang('Addon_splittest_Send_Step2_SendingInPast'), SS_FLASH_MSG_ERROR, $this->admin_url . '&Action=Send&Step=2');
                 return;
             }
             $send_details['SendStartTime'] = $gmt_check_time;
         }
     }
     $this->template_system->Assign('AdminUrl', $this->admin_url, false);
     $api = $this->GetApi();
     $split_campaign_details = $api->Load($send_details['splitid']);
     $sendingCampaigns = array();
     $send_details['newsletters'] = array();
     foreach ($split_campaign_details['splittest_campaigns'] as $campaignid => $campaignname) {
         $sendingCampaigns[$campaignid] = htmlspecialchars($campaignname, ENT_QUOTES, SENDSTUDIO_CHARSET);
         $send_details['newsletters'][$campaignid] = $campaignid;
     }
     /**
      * Before saving the job details, randomize the newsletter order.
      * This is so we don't send the newsletters in the same order every time.
      */
     shuffle($send_details['newsletters']);
     $send_list = array();
     switch ($send_details['sendingto']['sendtype']) {
         case 'list':
             require_once SENDSTUDIO_API_DIRECTORY . '/lists.php';
             $list_api = new Lists_API();
             foreach ($send_details['sendingto']['sendids'] as $listid) {
                 $list_api->Load($listid);
                 $send_list[] = htmlspecialchars($list_api->Get('name'), ENT_QUOTES, SENDSTUDIO_CHARSET);
             }
             $this->template_system->Assign('SendingToLists', true);
             break;
         case 'segment':
             require_once SENDSTUDIO_API_DIRECTORY . '/segment.php';
             $segment_api = new Segment_API();
             foreach ($send_details['sendingto']['sendids'] as $segmentid) {
                 $segment_api->Load($segmentid);
                 $send_list[] = htmlspecialchars($segment_api->Get('segmentname'), ENT_QUOTES, SENDSTUDIO_CHARSET);
             }
             // The job expects a 'Segments' element, otherwise it will send to entire lists.
             $send_details['Segments'] = $send_details['sendingto']['sendids'];
             $this->template_system->Assign('SendingToSegments', true);
             break;
     }
     $subscriber_count = $send_details['sendsize'];
     $user = IEM::userGetCurrent();
     if ($user->HasAccess('Newsletters')) {
         $this->template_system->Assign('ApplicationUrl', $this->application_url, false);
         $this->template_system->Assign('NewsletterView', true);
     }
     $send_criteria = array();
     // can only send to active subscribers.
     $send_criteria['Status'] = 'a';
     $send_criteria['List'] = $send_details['sendingto']['Lists'];
     $send_details['SendCriteria'] = $send_criteria;
     $check_stats = $statsapi->CheckUserStats($user, $subscriber_count, $send_details['SendStartTime']);
     list($ok_to_send, $not_ok_to_send_reason) = $check_stats;
     if (!$ok_to_send) {
         require_once SENDSTUDIO_LANGUAGE_DIRECTORY . '/default/send.php';
         FlashMessage(GetLang($not_ok_to_send_reason), SS_FLASH_MSG_ERROR, $this->admin_url . '&Action=Send&Step=2');
         return;
     }
     /**
      * The 'job' expects a 'Lists' element, so just point it to the sendingto lists.
      */
     $send_details['Lists'] = $send_details['sendingto']['Lists'];
     $send_details['SendSize'] = $subscriber_count;
     $jobcreated = $jobapi->Create('splittest', $send_details['SendStartTime'], $user->userid, $send_details, 'splittest', $send_details['splitid'], $send_details['sendingto']['Lists']);
     $send_details['Job'] = $jobcreated;
     IEM::sessionSet('JobSendSize', $subscriber_count);
     // if we're not using scheduled sending, create the queue and start 'er up!
     if (!self::CheckCronEnabled()) {
         require_once SENDSTUDIO_API_DIRECTORY . '/subscribers.php';
         $subscriberApi = new Subscribers_API();
         $sendqueue = $subscriberApi->CreateQueue('splittest');
         $jobapi->StartJob($jobcreated);
         $queuedok = $jobapi->JobQueue($jobcreated, $sendqueue);
         $queueinfo = array('queueid' => $sendqueue, 'queuetype' => 'splittest', 'ownerid' => $user->userid);
         if ($send_details['sendingto']['sendtype'] == 'segment') {
             $subscriberApi->GetSubscribersFromSegment($send_details['sendingto']['sendids'], false, $queueinfo, 'nosort');
         } else {
             $subscriberApi->GetSubscribers($send_criteria, array(), false, $queueinfo, $user->userid);
         }
         if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
             $subscriberApi->Db->OptimizeTable(SENDSTUDIO_TABLEPREFIX . "queues");
         }
         $subscriberApi->RemoveDuplicatesInQueue($sendqueue, 'splittest', $send_details['sendingto']['Lists']);
         $subscriberApi->RemoveBannedEmails($send_details['sendingto']['Lists'], $sendqueue, 'splittest');
         $subscriberApi->RemoveUnsubscribedEmails($send_details['sendingto']['Lists'], $sendqueue, 'splittest');
         if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
             $subscriberApi->Db->OptimizeTable(SENDSTUDIO_TABLEPREFIX . "queues");
         }
         $send_details['SendSize'] = $subscriberApi->QueueSize($sendqueue, 'splittest');
         $send_details['Stats'] = array();
         $statids = array();
         foreach ($send_details['newsletters'] as $newsletterid) {
             $newsletterstats = $send_details;
             $newsletterstats['Job'] = $jobcreated;
             $newsletterstats['Queue'] = $sendqueue;
             $newsletterstats['SentBy'] = $queueinfo['ownerid'];
             $newsletterstats['SendType'] = 'splittest';
             $newsletterstats['Newsletter'] = $newsletterid;
             $newsletterstats['Lists'] = $send_details['sendingto']['Lists'];
             $newsletterstats['SendCriteria'] = $send_criteria;
             $statid = $statsapi->SaveNewsletterStats($newsletterstats);
             $statids[] = $statid;
             $send_details['Stats'][$newsletterid] = $statid;
             $statsapi->RecordUserStats($user->userid, $jobcreated, $subscriber_count, $send_details['SendStartTime'], $statid);
         }
         $send_api->SaveSplitStats($send_details['splitid'], $jobcreated, $statids);
         $jobapi->PauseJob($jobcreated);
     }
     $this->template_system->Assign('sendingCampaigns', $sendingCampaigns);
     $this->template_system->Assign('sendLists', $send_list);
     $send_size = $send_details['SendSize'];
     IEM::sessionSet('SplitTestSendDetails', $send_details);
     /**
      * This is used to work out if we should automatically clean up a half-finished send process.
      * We need to do this because a half-finished send may have taken email-credits from a user
      * so we need to give them back.
      */
     IEM::sessionSet('SplitTestSend_Cleanup', $send_details);
     if ($send_size == 1) {
         $send_size_msg = GetLang('Addon_splittest_Send_Step3_Size_One');
     } else {
         $send_size_msg = sprintf(GetLang('Addon_splittest_Send_Step3_Size_Many'), $this->PrintNumber($send_size));
     }
     $this->template_system->Assign('SendingToNumberOfContacts', $send_size_msg);
     $this->template_system->Assign('CronEnabled', false);
     if (self::CheckCronEnabled()) {
         /**
          * If cron is enabled, then record the stats allocation now.
          * This will get fixed up when the actual send starts as it needs to create a stat item for each newsletter.
          * However, at this stage we just need to record that the user is doing a send so it's removed from their send-allocation.
          */
         $statsapi->RecordUserStats($user->userid, $jobcreated, $subscriber_count, $send_details['SendStartTime']);
         $user_adjusted_time = AdjustTime($send_details['SendStartTime'], false, GetLang('TimeFormat'), true);
         $this->template_system->Assign('CronEnabled', true);
         $this->template_system->Assign('JobScheduleTime', sprintf(GetLang('Addon_splittest_Send_Step3_JobScheduleTime'), $user_adjusted_time));
         /**
          * Mark the job as "waiting".
          * This will be used on the "manage" page to show it's waiting to send out.
          */
         $send_api->StartJob($jobcreated, $send_details['splitid'], 'w');
     }
     $this->template_system->ParseTemplate('send_step3');
 }
コード例 #20
0
	/**
	* PrintSubscribeDate
	* Prints out subscribe date searching so you can easily display the day/month/year dropdown boxes used in searching.
	*
	* @see Subscribers_Manage::Process
	*
	* @return Void Doesn't return anything, puts information into the GLOBALS['Display_subdate_date1_Field_X'] placeholders.
	*/
	function PrintSubscribeDate()
	{

		$time = AdjustTime(0, true, null, true);

		$dd_start = $dd_end = AdjustTime($time, false, 'd');
		$mm_start = $mm_end = AdjustTime($time, false, 'm');
		$yy_start = $yy_end = AdjustTime($time, false, 'Y');

		$field_order = array('day', 'month', 'year');

		$daylist_start = $daylist_end = '<select name="datesearch[dd_whichone]" class="datefield">';
		for ($i=1; $i<=31; $i++) {
			$dom = $i;
			$i = sprintf("%02d", $i);
			$sel = '';

			if ($i==$dd_start) {
				$sel='SELECTED';
			}

			$daylist_start.='<option '.$sel.' value="'.sprintf("%02d",$i).'">'.$dom . '</option>';

			$sel = '';
			if ($i==$dd_end) {
				$sel='SELECTED';
			}

			$daylist_end.='<option '.$sel.' value="'.sprintf("%02d",$i).'">'.$dom . '</option>';

		}
		$daylist_start.='</select>';
		$daylist_end.='</select>';

		$monthlist_start = $monthlist_end ='<select name="datesearch[mm_whichone]" class="datefield">';
		for ($i=1;$i<=12;$i++) {
			$mth = $i;
			$sel = '';
			$i = sprintf("%02d",$i);

			if ($i==$mm_start) {
				$sel='SELECTED';
			}

			$monthlist_start.='<option '.$sel.' value="'.sprintf("%02d",$i).'">'.GetLang($this->Months[$mth]) . '</option>';

			if ($i==$mm_end) {
				$sel='SELECTED';
			}

			$monthlist_end .='<option '.$sel.' value="'.sprintf("%02d",$i).'">'.GetLang($this->Months[$mth]) . '</option>';

		}
		$monthlist_start.='</select>';
		$monthlist_end.='</select>';

		$yearlist_start ='<input type="text" maxlength="4" size="4" value="'.$yy_start.'" name="datesearch[yy_whichone]" class="datefield">';
		$yearlist_end ='<input type="text" maxlength="4" size="4" value="'.$yy_end.'" name="datesearch[yy_whichone]" class="datefield">';

		foreach ($field_order as $p => $order) {
			switch ($order) {
				case 'day':
					$GLOBALS['Display_subdate_date1_Field'.($p+1)] = str_replace('_whichone', '_start', $daylist_start);
				break;
				case 'month':
					$GLOBALS['Display_subdate_date1_Field'.($p+1)] = str_replace('_whichone', '_start', $monthlist_start);
				break;
				case 'year':
					$GLOBALS['Display_subdate_date1_Field'.($p+1)] = str_replace('_whichone', '_start', $yearlist_start);
				break;
			}
		}

		foreach ($field_order as $p => $order) {
			switch ($order) {
				case 'day':
					$GLOBALS['Display_subdate_date2_Field'.($p+1)] = str_replace('_whichone', '_end', $daylist_end);
				break;
				case 'month':
					$GLOBALS['Display_subdate_date2_Field'.($p+1)] = str_replace('_whichone', '_end', $monthlist_end);
				break;
				case 'year':
					$GLOBALS['Display_subdate_date2_Field'.($p+1)] = str_replace('_whichone', '_end', $yearlist_end);
				break;
			}
		}
	}
コード例 #21
0
	/**
	* ImportSubscriberLine
	* Imports a subscriber and sets appropriate customfield variables (if it needs to). Only handles one subscriber at a time.
	*
	* @param Array $subscriberinfo An array of the subscriber info to import. This includes format, confirmed status, custom field info.
	*
	* @see GetApi
	* @see Subscribers_API::IsDuplicate
	* @see Subscribers_API::UpdateEmailAddress
	* @see Subscribers_API::SubscriberExists
	* @see Subscribers_API::Create
	* @see Customfields_API::Load
	* @see Customfields_API::LoadSubField
	* @see _customfields_loaded
	* @see _saveCustomFields
	*
	* @return Void Doesn't return anything, updates statistics in the session.
	*/
	function ImportSubscriberLine($subscriberinfo=array())
	{
		$importinfo = IEM::sessionGet('ImportInfo');

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

		$importlist = $importinfo['ImportList'];
		$linkfields = $importinfo['LinkFields'];

		$list = $importinfo['List'];

		$subscriberformat = $importinfo['Format'];
		$subscriberconfirmed = strtolower($importinfo['Confirmed']);

		$email = '';
		$format = $subscriberformat;
		$confirmed = $subscriberconfirmed;

		$sd_m = $sd_d = $sd_y = 0;

		$customfields = array();

		$found_subscribedate = false;

		$subscriber_ip = '';

		/*
		 * Ok. Here is another spot where the programmer should be kicked.
		 */
		foreach ($linkfields as $pos => $type) {
			switch ($type) {
				case 'E':
					$email = $subscriberinfo[$pos];
				break;
				case 'C':
					$subscriberconfirmed = strtolower($subscriberinfo[$pos]);
				break;
				case 'F':
					$format = strtolower($subscriberinfo[$pos]);
				break;
				case 'N':
				break;
				case 'SD_MDY':
					if (substr_count($subscriberinfo[$pos], '/') == 2) {
						$found_subscribedate = true;
						list($sd_m, $sd_d, $sd_y) = explode('/', $subscriberinfo[$pos]);
					}
				break;

				case 'SD_DMY':
					if (substr_count($subscriberinfo[$pos], '/') == 2) {
						$found_subscribedate = true;
						list($sd_d, $sd_m, $sd_y) = explode('/', $subscriberinfo[$pos]);
					}
				break;

				case 'SD_YMD':
					if (substr_count($subscriberinfo[$pos], '/') == 2) {
						$found_subscribedate = true;
						list($sd_y, $sd_m, $sd_d) = explode('/', $subscriberinfo[$pos]);
					}
				break;

				case 'IP':
					$subscriber_ip = $subscriberinfo[$pos];
				break;

				default:
					$customfields[$type] = $subscriberinfo[$pos];
				break;
			}
		}

		$valid_subscribedate = false;
		$subscribedate = 0;

		if ($found_subscribedate && $sd_y >= 0 && $sd_m >= 0 && $sd_d >= 0) {
			$valid_subscribedate = checkdate($sd_m, $sd_d, $sd_y);

			if ($valid_subscribedate) {
				$subscribedate = AdjustTime(array(0, 0, 1, $sd_m, $sd_d, $sd_y), true);
			} else {
				$subscriberinfo[] = GetLang('InvalidSubscribeDate');
				$importresults['bads']++;
				$importresults['baddata'][] = implode($importinfo['FieldSeparator'], $subscriberinfo);
			}
		}

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

		if (!$SubscriberApi->ValidEmail($email)) {
			$subscriberinfo[] = GetLang('InvalidSubscriberEmailAddress');
			$importresults['bads']++;
			$importresults['baddata'][] = implode($importinfo['FieldSeparator'], $subscriberinfo);
			IEM::sessionSet('ImportResults', $importresults);
			return;
		}

		list($banned, $msg) = $SubscriberApi->IsBannedSubscriber($email, $list, false);
		if ($banned) {
			$importresults['bans']++;
			$importresults['bannedemails'][] = $email;
			IEM::sessionSet('ImportResults', $importresults);
			return;
		}

		$SubscriberApi->emailaddress = $email;

		$SubscriberApi->Set('subscribedate', $subscribedate);
		$SubscriberApi->Set('confirmdate', $subscribedate);

		$listapi = $this->GetApi('Lists');
		$CustomFieldApi = $this->GetApi('CustomFields');

		$CustomFieldsValid = true;

		foreach ($customfields as $fieldid => $fielddata) {
			/**
			* See if we have loaded this custom field yet or not.
			* If we haven't then load it up.
			*
			* If we have, then use that instead for the checkdata calls.
			*
			* Doing it this way saves a lot of db queries/overhead especially with lots of custom fields.
			*/
			if (!in_array($fieldid, array_keys($this->_customfields_loaded))) {
				$field_options = $CustomFieldApi->Load($fieldid, false, true);
				$subfield = $CustomFieldApi->LoadSubField($field_options);
				$this->_customfields_loaded[$fieldid] = $subfield;
			}

			$subf = $this->_customfields_loaded[$fieldid];

			$fieldtype = $subf->Get('fieldtype');
			if ($fieldtype == 'checkbox') {
				if (strpos($fielddata, ':') !== false) {
					$fielddata = explode(':', $fielddata);
				}
				if (strpos($fielddata, ',') !== false) {
					$fielddata = explode(',', $fielddata);
				}
				$fielddata = $subf->CheckData($fielddata, true);
				$customfields[$fieldid] = $fielddata;
			}

			if ($subf->IsRequired() && ($fielddata == '' || !$subf->CheckData($fielddata))) {
				$subscriberinfo[] = sprintf(GetLang('InvalidCustomFieldData'), $subf->GetFieldName());
				$importresults['bads']++;
				$importresults['baddata'][] = implode($importinfo['FieldSeparator'], $subscriberinfo);
				$CustomFieldsValid = false;
				break;
			}

			if ($fieldtype == 'date') {
				$fielddata = $subf->CheckData($fielddata, true);
				$customfields[$fieldid] = $fielddata;
			}
		}

		if (!$CustomFieldsValid) {
			IEM::sessionSet('ImportResults', $importresults);
			return;
		}

		if ($format == 'html') {
			$format = 'h';
		}

		if ($format == 'text') {
			$format = 't';
		}

		if ($format != 'h' && $format != 't') {
			$format = $importinfo['Format'];
		}

		// if the list doesn't accept both formats, force them to use the list format.
		if ($importinfo['ListFormat'] != 'b') {
			$format = $importinfo['ListFormat'];
		}

		$SubscriberApi->format = $format;

		$confirmstatus = false;
		if ($subscriberconfirmed == 'yes' || $subscriberconfirmed == 'confirmed' || $subscriberconfirmed == '1') {
			$confirmstatus = true;
		}

		$SubscriberApi->confirmed = $confirmstatus;

		if ($confirmstatus == true) {
			$SubscriberApi->Set('confirmip', $subscriber_ip);
		} else {
			$SubscriberApi->Set('requestip', $subscriber_ip);
		}

		$subscribercheck = $SubscriberApi->IsDuplicate($email, $list);

		if ($subscribercheck) {
			$unsubscribe_check = $SubscriberApi->IsUnSubscriber($email, $list);
			if (!$unsubscribe_check) {
				if ($importinfo['Overwrite']) {
					$SubscriberApi->UpdateEmailAddress($subscribercheck);
					$SubscriberApi->UpdateList($subscribercheck, $list);
					$result = $this->_SaveCustomFields($SubscriberApi, $subscribercheck, $customfields, $email, $importresults);
					if (!$result) {
						return;
					}
					if ($importinfo['Autoresponder']) {
						$SubscriberApi->AddToListAutoresponders($subscribercheck, $list);
					}
					$importresults['updates']++;
				} else {
					$importresults['duplicates']++;
					$importresults['duplicateemails'][] = $email;
				}
			} else {
				$importresults['unsubscribes']++;
				$importresults['unsubscribedemails'][] = $email;
			}
		} else {
			$subscriberid = $SubscriberApi->AddToList($email, $list, $importinfo['Autoresponder'], true);

			if (!$subscriberid) {
				$importresults['failures']++;
				$importresults['failedemails'][] = $email;
			} else {
				$result = $this->_SaveCustomFields($SubscriberApi, $subscriberid, $customfields, $email, $importresults);
				if (!$result) {
					return;
				}
				$importresults['success']++;
			}
		}

		IEM::sessionSet('ImportResults', $importresults);
	}
コード例 #22
0
ファイル: segment.php プロジェクト: hungnv0789/vhtm
		/**
		 * _SaveSegment
		 * Save segment, and then hand over the user interfasce creation to _ManageSegment function
		 * Save segment is a generic function where you can "Create" new segment or "Save" edited segment
		 *
		 * @param Array $parameter Any parameters that need to be parsed to this function
		 * @return String Returns response string that can be outputted to the browser
		 *
		 * @uses SendStudio_Functions::GetApi()
		 * @uses Segment::_getPOSTRequest()
		 * @uses Segment::_ManageSegment()
		 * @uses Segment_API
		 * @uses Segment_API::Load()
		 *
		 * @access private
		 */
		function _SaveSegment($parameter = array())
		{
			if (count($parameter['user']->GetLists()) == 0) {
				return $this->_ManageSegment($parameter);
			}

			$segment = $this->GetApi('Segment');
			$segmentID = intval($this->_getPOSTRequest('SegmentID', null));
			$segmentName = trim($this->_getPOSTRequest('SegmentName', null));
			$segmentLists = $this->_getPOSTRequest('Lists', null);
			$segmentRules = $this->_getPOSTRequest('Rules', null);


			// Make sure "Segment Name", "Segment Lists" and "Segment Rules" exists in the POST request
			// Otherwise, use might have gotten bere by typing a url
			if (is_null($segmentName) || is_null($segmentLists) || is_null($segmentRules)) {
				return $this->_ManageSegment($parameter);
			}

			/**
			 * Check permission (either "Create" or "Edit" permission),
			 * This section will also load values/set the default values to the "Segment_API" class
			 */
				if ($segmentID == 0) {
					if (!$parameter['user']->CanCreateSegment()) {
						return $this->_ManageSegment($parameter);
					}

					$segment->ownerid = $parameter['user']->userid;
					$segment->createdate = AdjustTime();
				} else {
					if (!$segment->Load($segmentID)) {
						$GLOBALS['Error'] = GetLang('SegmentFormErrorCannotLoadRecord');
						$parameter['message'] = $this->ParseTemplate('ErrorMsg', true, false);
						unset($GLOBALS['Error']);

						return $this->_ManageSegment($parameter);
					}

					if (!$this->_checkPermissionCanEdit($segment, $parameter['user'])) {
						$GLOBALS['Error'] = GetLang('SegmentManageSaveErrorNoPrivilege');
						$parameter['message'] = $this->ParseTemplate('ErrorMsg', true, false);
						unset($GLOBALS['Error']);

						return $this->_ManageSegment($parameter);
					}
				}
			/**
			 * -----
			 */

			$segment->segmentname = $segmentName;
			$segment->searchinfo = array(
				'Lists' => $segmentLists,
				'Rules' => $segmentRules,
			);

			$status = (is_null($segment->segmentid)? $segment->Create() : $segment->Save());
			if (!$status) {
				$GLOBALS['Error'] = GetLang('SegmentFormSaveFailed');
				$tempMessage = $this->ParseTemplate('ErrorMsg', true, false);
				unset($GLOBALS['Error']);

				return $this->_getEditor($parameter['user'], $segment, array(
					'Message'		=> $tempMessage,
					'Heading' 		=> (is_null($segment->segmentid)? GetLang('SegmentFormTitleCreate') : GetLang('SegmentFormTitleEdit')),
					'Intro'			=> (is_null($segment->segmentid)? GetLang('SegmentFormTitleCreateIntro') : GetLang('SegmentFormTitleEditIntro'))
				));
			} else {
				$parameter['message'] = $this->PrintSuccess('SegmentFormSaveSuccess');
				return $this->_ManageSegment($parameter);
			}
		}