Exemplo n.º 1
0
/**
* GetFlashMessages
* Gets the messages from the session and works out which template etc to display them in based on the message type.
* If there are multiple messages, they are all returned (based on which type/template etc) in one long string.
*
* It will not combine all 'success' messages into one box and all 'error' messages into another box.
* Each message is displayed in it's own box and they are returned in the order they were created.
*
* If you create a 'success' message then an 'info' message then an 'error' message, that is the order they are returned in.
*
* @see FlashMessage
* @uses SS_FLASH_MSG_SUCCESS
* @uses SS_FLASH_MSG_ERROR
* @uses SS_FLASH_MSG_WARNING
* @uses SS_FLASH_MSG_INFO
*
* @return String Returns the message ready for displaying.
*/
function GetFlashMessages()
{
	$flash_messages = IEM::sessionGet('FlashMessages', false);

	if (!$flash_messages) {
		return '';
	}

	$template_system = GetTemplateSystem();

	$print_msg = '';
	foreach ($flash_messages as $msg) {
		switch ($msg['type']) {
			case SS_FLASH_MSG_SUCCESS:
				$GLOBALS['Success'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('successmsg', true);
			break;

			case SS_FLASH_MSG_ERROR:
				$GLOBALS['Error'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('errormsg', true);
			break;

			case SS_FLASH_MSG_INFO:
				$GLOBALS['Message'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('infomsg', true);
			break;

			case SS_FLASH_MSG_WARNING:
				$GLOBALS['Warning'] = $msg['message'];
				$print_msg .= $template_system->ParseTemplate('warningmsg', true);
			break;
		}
	}
	IEM::sessionRemove('FlashMessages');

	return $print_msg;
}
Exemplo n.º 2
0
    /**
     * Process
     * This handles working out what stage you are up to and so on with workflow.
     * It handles creating, editing, deleting, copying etc.
     * It also uses the session to remember what you've done (eg chosen a text newsletter) so it only has to do one update at a time rather than doing everything separately.
     *
     * @see GetUser
     * @see User_API::HasAccess
     * @see PrintHeader
     * @see GetApi
     * @see Newsletter_API::Load
     * @see Newsletter_API::GetBody
     * @see Newsletter_API::Copy
     * @see Newsletter_API::Create
     * @see Newsletter_API::Save
     * @see Newsletter_API::Delete
     * @see ManageNewsletters
     * @see PreviewWindow
     * @see MoveFiles
     * @see CreateNewsletter
     * @see DisplayEditNewsletter
     * @see EditNewsletter
     *
     * Doesn't return anything, handles processing (with the api) and prints out the results.
     */
    function Process() {
        $GLOBALS['Message'] = '';

        $action = (isset($_GET['Action'])) ? strtolower(urldecode($_GET['Action'])) : null;
        $id = (isset($_GET['id'])) ? strtolower(urldecode($_GET['id'])) : null;
        $user = IEM::userGetCurrent();

        $final_action = $action;
        $secondary_actions = array('activate', 'deactivate', 'activatearchive', 'deactivatearchive');
        if (in_array($action, $secondary_actions)) {
            $final_action = 'approve';
        }

        // with 'change' actions, each separate action is checked further on, so we'll just check they can manage anything in this area.
        if (in_array($action, array('change', 'checkspam', 'viewcompatibility', 'processpaging', 'sendpreview', 'preview'))) {
            $final_action = 'manage';
        }

        if(is_null($id)){
            $access = $user->HasAccess('newsletters', $final_action);
        } else {
            $access = $user->HasAccess('newsletters', $final_action, $id);
        }


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

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

        if ($action == 'processpaging') {
            $this->SetPerPage($_GET['PerPageDisplay']);
            $this->ManageNewsletters();
            if (!in_array($action, $this->SuppressHeaderFooter)) {
                $this->PrintFooter($popup);
            }
            exit;
        }

        switch ($action) {
            case 'viewcompatibility':
                $newsletter_info = IEM::sessionGet('Newsletters');

                $html = (isset($_POST['myDevEditControl_html'])) ? $_POST['myDevEditControl_html'] : false;
                $text = (isset($_POST['TextContent'])) ? $_POST['TextContent'] : false;
                $showBroken = isset($_REQUEST['ShowBroken']) && $_REQUEST['ShowBroken'] == 1;
                $details = array();
                $details['htmlcontent'] = $html;
                $details['textcontent'] = $text;
                $details['format'] = $newsletter_info['Format'];

                $this->PreviewWindow($details, $showBroken);
                exit;
                break;

            case 'checkspamdisplay':
                $force = IEM::ifsetor($_GET['Force'], false);
                $this->CheckContentForSpamDisplay($force);
                break;

            case 'checkspam':
                $text = (isset($_POST['TextContent'])) ? $_POST['TextContent'] : false;
                $html = (isset($_POST['myDevEditControl_html'])) ? $_POST['myDevEditControl_html'] : false;
                $this->CheckContentForSpam($text, $html);
                break;

            case 'activate':
            case 'deactivate':
            case 'activatearchive':
            case 'deactivatearchive':
                $newsletterapi = $this->GetApi();
                $newsletterapi->Load($id);

                $message = '';

                if ($user->HasAccess('newsletters', 'approve')) {
                    switch ($action) {
                        case 'activatearchive':
                            $newsletterapi->Set('archive', 1);
                            if (!$newsletterapi->Active()) {
                                $GLOBALS['Error'] = GetLang('NewsletterCannotBeInactiveAndArchive');
                                $message .= $this->ParseTemplate('ErrorMsg', true, false);
                            }
                            $message .= $this->PrintSuccess('NewsletterArchive_ActivatedSuccessfully');
                            break;
                        case 'deactivatearchive':
                            $newsletterapi->Set('archive', 0);
                            $message .= $this->PrintWarning('NewsletterArchive_DeactivatedWarning');
                            $message .= $this->PrintSuccess('NewsletterArchive_DeactivatedSuccessfully');
                            break;
                        case 'activate':
                            $allow_attachments = $this->CheckForAttachments($id, 'newsletters');
                            if ($allow_attachments) {
                                $newsletterapi->Set('active', $user->Get('userid'));
                                $message .= $this->PrintSuccess('NewsletterActivatedSuccessfully');
                            } else {
                                $GLOBALS['Error'] = GetLang('NewsletterActivateFailed_HasAttachments');
                                $message .= $this->ParseTemplate('ErrorMsg', true, false);
                            }
                            break;
                        default:
                            $newsletterapi->Set('active', 0);
                            if ($newsletterapi->Archive()) {
                                $GLOBALS['Error'] = GetLang('NewsletterCannotBeInactiveAndArchive');
                                $message .= $this->ParseTemplate('ErrorMsg', true, false);
                            }
                            $message .= $this->PrintSuccess('NewsletterDeactivatedSuccessfully');
                    }
                    $newsletterapi->Save();

                    $GLOBALS['Message'] = $message;
                }
                $this->ManageNewsletters();
                break;

            case 'sendpreviewdisplay':
                $this->SendPreviewDisplay();
                break;

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

            case 'delete':
                $this->DeleteNewsletters($id);
                break;

            case 'view':
                $type = 'newsletters';
                $newsletter = $this->GetApi();
                if (!$newsletter->Load($id)) {
                    break;
                }

                // Log this to "User Activity Log"
                $logURL = SENDSTUDIO_APPLICATION_URL . '/admin/index.php?Page=Newsletters&Action=Edit&id=' . $_GET['id'];
                IEM::logUserActivity($logURL, 'images/newsletters_view.gif', $newsletter->name);

                $details = array();
                $details['htmlcontent'] = $newsletter->GetBody('HTML');
                $details['textcontent'] = $newsletter->GetBody('Text');
                $details['format'] = $newsletter->format;

                $this->PreviewWindow($details);
                exit;
                break;

            case 'preview':
                $type = 'newsletters';
                $newsletter = $this->GetApi();
                if (!$newsletter->Load($id)) {
                    break;
                }

                $details = array();
                $details['htmlcontent'] = $newsletter->GetBody('HTML');
                $details['textcontent'] = $newsletter->GetBody('Text');
                $details['format'] = $newsletter->format;

                $this->PreviewWindow($details, false, $id);
                exit;
                break;

            case 'copy':
                $api = $this->GetApi();
                list($newsletter_result, $files_copied) = $api->Copy($id);
                if (!$newsletter_result) {
                    $GLOBALS['Error'] = GetLang('NewsletterCopyFail');
                    $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
                } else {
                    $changed = false;
                    // check the permissions.
                    // if we can't make archive a newsletter, disable this aspect of it.
                    if (!$user->HasAccess('Newsletters', 'Approve')) {
                        $changed = true;
                        $api->Set('archive', 0);
                    }

                    // if we can't approve newsletters, then make sure we disable it.
                    if (!$user->HasAccess('Newsletters', 'Approve')) {
                        $changed = true;
                        $api->Set('active', 0);
                    }

                    if ($changed) {
                        $api->Save();
                    }
                    $GLOBALS['Message'] = $this->PrintSuccess('NewsletterCopySuccess');
                    if (!$files_copied) {
                        $GLOBALS['Error'] = GetLang('NewsletterFilesCopyFail');
                        $GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
                    }
                }
                $this->ManageNewsletters();
                break;

            case 'edit':
                $newsletter = $this->GetApi();
                $newsletter->Load($id);

                $subaction = (isset($_GET['SubAction'])) ? strtolower(urldecode($_GET['SubAction'])) : '';
                switch ($subaction) {
                    case 'step2':
                        $editnewsletter = array('id' => $id);

                        $checkfields = array('Name', 'Format');
                        $valid = true;
                        $errors = array();
                        foreach ($checkfields as $p => $field) {
                            if (!isset($_POST[$field])) {
                                $valid = false;
                                $errors[] = GetLang('Newsletter' . $field . 'IsNotValid');
                                break;
                            }
                            if ($_POST[$field] == '') {
                                $valid = false;
                                $errors[] = GetLang('Newsletter' . $field . 'IsNotValid');
                                break;
                            } else {
                                $value = $_POST[$field];
                                $editnewsletter[$field] = $value;
                            }
                        }
                        if (!$valid) {
                            $GLOBALS['Error'] = GetLang('UnableToUpdateNewsletter') . '<br/>- ' . implode('<br/>- ', $errors);
                            $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
                            $this->EditNewsletter($id);
                            break;
                        }

                        IEM::sessionSet('Newsletters', $editnewsletter);
                        $this->DisplayEditNewsletter($id);
                        break;

                    case 'save':
                    case 'complete':
                        $session_newsletter = IEM::sessionGet('Newsletters');

                        $text_unsubscribelink_found = true;
                        $html_unsubscribelink_found = true;
                        $textcontent = "";
                        $htmlcontent = "";

                        if (isset($_POST['TextContent'])) {
                            $textcontent = $_POST['TextContent'];
                            $newsletter->SetBody('Text', $textcontent);
                            $text_unsubscribelink_found = $this->CheckForUnsubscribeLink($textcontent, 'text');
                            $session_newsletter['contents']['text'] = $textcontent;
                        }

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

                            /**
                             * This is an effort not to overwrite the eixsting HTML contents
                             * if there isn't any contents in it (DevEdit will have '<html><body></body></html>' as a minimum
                             * that will be passed to here)
                             */
                            if (trim($htmlcontent) == '') {
                                $GLOBALS['Error'] = GetLang('UnableToUpdateNewsletter');
                                $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
                                $this->DisplayEditNewsletter($id);
                                break;
                            }

                            $newsletter->SetBody('HTML', $htmlcontent);
                            $html_unsubscribelink_found = $this->CheckForUnsubscribeLink($htmlcontent, 'html');
                            $session_newsletter['contents']['html'] = $htmlcontent;
                        }

                        if (isset($_POST['subject'])) {$newsletter->subject = $_POST['subject'];}
                        
                        $newsletter->name = $session_newsletter['Name'];
                        
                        $newsletter->format = $session_newsletter['Format'];

                        $newsletter->active = 0;
                        
                        if ($user->HasAccess('newsletters', 'approve')) {
                            if (isset($_POST['active'])) {
                                $newsletter->active = $user->userid;
                            }
                        }
                        
                        $newsletter->archive = 0;

                        if (isset($_POST['archive'])) {
                            $newsletter->archive = 1;
                        }
                    
                        $dest = 'newsletters';

                        if (!empty($textcontent)) {
                            $textcontent = $this->ConvertContent($textcontent, $dest, $id);
                            $newsletter->SetBody('Text', $textcontent);
                        }
                        if (!empty($htmlcontent)) {
                            $htmlcontent = $this->ConvertContent($htmlcontent, $dest, $id);
                            $newsletter->SetBody('HTML', $htmlcontent);
                        }


                        $result = $newsletter->Save();

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

                        $newsletter_info = $session_newsletter;
                        $newsletter_info['embedimages'] = true;
                        $newsletter_info['multipart'] = true;

                        list($newsletter_size, $newsletter_img_warnings) = $this->GetSize($newsletter_info);

                        if (SENDSTUDIO_ALLOW_EMBEDIMAGES) {
                            $size_message = GetLang('Newsletter_Size_Approximate');
                        } else {
                            $size_message = GetLang('Newsletter_Size_Approximate_Noimages');
                        }
                        $GLOBALS['Message'] = $this->PrintSuccess('NewsletterUpdated', sprintf($size_message, $this->EasySize($newsletter_size)));

                        if (SENDSTUDIO_EMAILSIZE_WARNING > 0) {
                            $warning_size = SENDSTUDIO_EMAILSIZE_WARNING * 1024;
                            if ($newsletter_size > $warning_size) {
                                $GLOBALS['Message'] .= $this->PrintWarning('Newsletter_Size_Over_EmailSize_Warning', $this->EasySize($warning_size));
                            }
                        }

                        // Delete any attachments we're meant to first
                        if (SENDSTUDIO_ALLOW_ATTACHMENTS) {
                            list($del_attachments_status, $del_attachments_status_msg) = $this->CleanupAttachments($dest, $id);

                            if ($del_attachments_status) {
                                if ($del_attachments_status_msg) {
                                    $GLOBALS['Success'] = $del_attachments_status_msg;
                                    $GLOBALS['Message'] .= $this->ParseTemplate('SuccessMsg', true, false);
                                }
                            } else {
                                $GLOBALS['Error'] = $del_attachments_status_msg;
                                $GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
                            }

                            // Only save the new attachments after deleting the old ones
                            list($attachments_status, $attachments_status_msg) = $this->SaveAttachments($dest, $id);

                            if ($attachments_status) {
                                if ($attachments_status_msg != '') {
                                    $GLOBALS['Success'] = $attachments_status_msg;
                                    $GLOBALS['Message'] .= $this->ParseTemplate('SuccessMsg', true, false);
                                }
                            } else {
                                $GLOBALS['Error'] = $attachments_status_msg;
                                $GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
                            }
                        }

                        if (!$newsletter->Active() && isset($_POST['archive'])) {
                            $GLOBALS['Error'] = GetLang('NewsletterCannotBeInactiveAndArchive');
                            $GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
                        }

                        if ($newsletter_img_warnings) {
                            $GLOBALS['Message'] .= $this->PrintWarning('UnableToLoadImage_Newsletter_List', $newsletter_img_warnings);
                        }

                        if (!$html_unsubscribelink_found) {
                            $GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInHTMLContent');
                        }

                        if (!$text_unsubscribelink_found) {
                            $GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInTextContent');
                        }

                        $GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);
                        
                        if ($subaction == 'save') {
                            $this->DisplayEditNewsletter($id);
                        } else {
                            IEM::sessionRemove("Newsletters");
                            $this->ManageNewsletters();
                        }
                        
                        break;

                    default:
                    case 'step1':
                        $this->EditNewsletter($id);
                        break;
                }
                break;

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

                switch ($subaction) {
                    default:
                        $this->CreateNewsletter(); 
                    break;
                    case 'step2':
                        if(is_dir(TEMP_DIRECTORY . "/newsletters/".$user->userid."_tmp")){remove_directory(TEMP_DIRECTORY . "/newsletters/".$user->userid."_tmp");}
                        $newnewsletter = array();
                        $checkfields = array('Name', 'Format');
                        $valid = true;
                        $errors = array();
                        foreach ($checkfields as $p => $field) {
                            if (!isset($_POST[$field]) || empty($_POST[$field])) {
                                $valid = false;
                                $errors[] = GetLang('Newsletter' . $field . 'IsNotValid');
                                break;
                            } else {
                                $value = $_POST[$field];
                                $newnewsletter[$field] = $value;
                            }
                        }
                        if (!$valid) {
                            $GLOBALS['Error'] = GetLang('UnableToCreateNewsletter') . '<br/>- ' . implode('<br/>- ', $errors);
                            $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
                            $this->CreateNewsletter();
                            break;
                        }
                        if (isset($_POST['TemplateID'])) {
                            $newnewsletter['TemplateID'] = $_POST['TemplateID'];
                        }
                        IEM::sessionSet('Newsletters', $newnewsletter);
                        $this->DisplayEditNewsletter();
                        break;

                    case 'save':
                    case 'complete':
                        $session_newsletter = IEM::sessionGet('Newsletters');

                        $newnewsletter = $this->GetApi();

                        $text_unsubscribelink_found = true;
                        $html_unsubscribelink_found = true;

                        if (isset($_POST['TextContent'])) {
                            $textcontent = $_POST['TextContent'];
                            $newnewsletter->SetBody('Text', $textcontent);
                            $text_unsubscribelink_found = $this->CheckForUnsubscribeLink($textcontent, 'text');
                            $session_newsletter['contents']['text'] = $textcontent;
                        }

                        if (isset($_POST['myDevEditControl_html'])) {
                            $htmlcontent = $_POST['myDevEditControl_html'];
                            $newnewsletter->SetBody('HTML', $htmlcontent);
                            $html_unsubscribelink_found = $this->CheckForUnsubscribeLink($htmlcontent, 'html');
                            $session_newsletter['contents']['html'] = $htmlcontent;
                        }

                        if (isset($_POST['subject'])) {
                            $newnewsletter->subject = $_POST['subject'];
                        }
                        
                        $newnewsletter->name = $session_newsletter['Name'];
                        $newnewsletter->format = $session_newsletter['Format'];
                        $newnewsletter->active = 0;
                        
                        if ($user->HasAccess('newsletters', 'approve')) {
                            if (isset($_POST['active'])) {
                                $newnewsletter->active = $user->userid;
                            }
                        }
                        
                        $newnewsletter->archive = 0;
                        if (isset($_POST['archive'])) {
                            $newnewsletter->archive = 1;
                        }

                        $newnewsletter->ownerid = $user->userid;
                        $result = $newnewsletter->Create();

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

                        $newsletter_info = $session_newsletter;
                        $newsletter_info['embedimages'] = true;
                        $newsletter_info['multipart'] = true;

                        list($newsletter_size, $newsletter_img_warnings) = $this->GetSize($newsletter_info);

                        if (SENDSTUDIO_ALLOW_EMBEDIMAGES) {
                            $size_message = GetLang('Newsletter_Size_Approximate');
                        } else {
                            $size_message = GetLang('Newsletter_Size_Approximate_Noimages');
                        }
                        $GLOBALS['Message'] = $this->PrintSuccess('NewsletterUpdated', sprintf($size_message, $this->EasySize($newsletter_size)));

                        if (SENDSTUDIO_EMAILSIZE_WARNING > 0) {
                            $warning_size = SENDSTUDIO_EMAILSIZE_WARNING * 1024;
                            if ($newsletter_size > $warning_size) {
                                $GLOBALS['Message'] .= $this->PrintWarning('Newsletter_Size_Over_EmailSize_Warning', $this->EasySize($warning_size));
                            }
                        }

                        $dest = 'newsletters';

                        $movefiles_result = $this->MoveFiles($dest, $result);

                        if ($movefiles_result) {
                            if (isset($textcontent)) {
                                $textcontent = $this->ConvertContent($textcontent, $dest, $result);
                                $newnewsletter->SetBody('Text', $textcontent);
                            }
                            if (isset($htmlcontent)) {
                                $htmlcontent = $this->ConvertContent($htmlcontent, $dest, $result);
                                $newnewsletter->SetBody('HTML', $htmlcontent);
                            }
                        } else {
                            $GLOBALS['Error'] = "Unable to move images to final location.";
                            $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
                            $this->DisplayEditNewsletter($result);
                            break;
                        }
                        
                        $newnewsletter->Save();
                        
                        if (SENDSTUDIO_ALLOW_ATTACHMENTS) {
                            list($attachments_status, $attachments_status_msg) = $this->SaveAttachments($dest, $result);
                            if ($attachments_status) {
                                if ($attachments_status_msg != '') {
                                    $GLOBALS['Success'] = $attachments_status_msg;
                                    $GLOBALS['Message'] .= $this->ParseTemplate('SuccessMsg', true, false);
                                }
                            } else {
                                $GLOBALS['Error'] = $attachments_status_msg;
                                $GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
                            }
                        }
                        if (!$newnewsletter->Active() && isset($_POST['archive'])) {
                            $GLOBALS['Error'] = GetLang('NewsletterCannotBeInactiveAndArchive');
                            $GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
                        }

                        if ($newsletter_img_warnings) {
                            $GLOBALS['Message'] .= $this->PrintWarning('UnableToLoadImage_Newsletter_List', $newsletter_img_warnings);
                        }

                        if (!$html_unsubscribelink_found) {
                            $GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInHTMLContent');
                        }

                        if (!$text_unsubscribelink_found) {
                            $GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInTextContent');
                        }

                        $GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);
                        
                        if(is_dir(TEMP_DIRECTORY . "/newsletters/".$user->userid."_tmp")){remove_directory(TEMP_DIRECTORY . "/newsletters/".$user->userid."_tmp");}
                        
                        if ($subaction == 'save') {
                            $this->DisplayEditNewsletter($result);
                        } else {
                            IEM::sessionRemove("Newsletters");
                            $this->ManageNewsletters();
                        }
                        break;
                }
                break;

            case 'change':
                $subaction = strtolower($_POST['ChangeType']);
                $newsletterlist = $_POST['newsletters'];

                switch ($subaction) {
                    case 'delete':
                        $access = $user->HasAccess('Newsletters', 'Delete');
                        if ($access) {
                            $this->DeleteNewsletters($newsletterlist);
                        } else {
                            $this->DenyAccess();
                        }
                        break;

                    case 'approve':
                    case 'disapprove':
                        $access = $user->HasAccess('Newsletters', 'Approve');
                        if ($access) {
                            $this->ActionNewsletters($newsletterlist, $subaction);
                        } else {
                            $this->DenyAccess();
                        }
                        break;

                    case 'archive':
                    case 'unarchive':
                        $access = $user->HasAccess('Newsletters', 'Edit');
                        if ($access) {
                            $this->ActionNewsletters($newsletterlist, $subaction);
                        } else {
                            $this->DenyAccess();
                        }
                        break;
                }
                break;

            default:
                $this->ManageNewsletters();
                break;
        }

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

		$user_lists = $user->GetLists();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		$GLOBALS['FormatList'] = $format;

		$this->PrintSubscribeDate();

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

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

		$this->ParseTemplate('Subscriber_Manage_Step2');

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

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

		if (!$msg && (isset($_POST['ShowFilteringOptions']) && $_POST['ShowFilteringOptions'] == 2)) {
			?>
			<script>
				document.forms[0].submit();
			</script>
			<?php
			exit();
		}
	}
Exemplo n.º 4
0
 /**
  * Admin_Action_PreConfig
  *
  * is use to preconfigured any request before hitting any of of the Action..
  * Perhaps this can be used to setup any prerequeisite like seting error messages or warning
  * and other related used that can be used accross action..
  *
  *
  * @return void
  */
 public function Admin_Action_PreConfig()
 {
     $messageText = IEM::sessionGet('MessageText');
     $messageType = IEM::sessionGet('MessageType');
     if ($messageText) {
         $message['type'] = $messageType;
         $message['message'] = $messageText;
         $messageArr[] = $message;
         IEM::sessionSet('FlashMessages', $messageArr);
         // removing the session for next usage
         IEM::sessionRemove('MessageText');
         IEM::sessionRemove('MessageType');
     }
 }
Exemplo n.º 5
0
	/**
	* ShowStep_0
	* This works out which upgrades are going to need to run, sets session variables and sets up javascript functionality to process the actions.
	*
	* @return Void Prints the page out, doesn't return it.
	*/
	function ShowStep_0()
	{
		$this->PrintHeader();

		$api = $this->GetApi('Settings');
		$current_db_version = $api->GetDatabaseVersion();

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

		$upgrade_api = new Upgrade_API();

		$upgrades_to_run = $upgrade_api->GetUpgradesToRun($current_db_version, SENDSTUDIO_DATABASE_VERSION);

		IEM::sessionSet('UpgradesToRun', $upgrades_to_run['upgrades']);

		$upgrades_done = array();
		IEM::sessionSet('DatabaseUpgradesCompleted', $upgrades_done);
		$upgrades_failed = array();
		IEM::sessionSet('DatabaseUpgradesFailed', $upgrades_failed);
		IEM::sessionSet('TotalSteps', $upgrades_to_run['number_to_run']);
		IEM::sessionSet('StepNumber', 1);
		IEM::sessionRemove('SendServerDetails');

		$previous_version = 'NX1.0';
		if (isset($upgrade_api->versions[$current_db_version])) {
			$previous_version = $upgrade_api->versions[$current_db_version];
		}
		IEM::sessionSet('PreviousVersion', $previous_version);
		IEM::sessionSet('PreviousDBVersion', $current_db_version);

		?>
			<br /><br /><br /><br />
			<table style="margin:auto;"><tr><td style="border:solid 2px #DDD; padding:20px; background-color:#FFF; width:450px;">
			<table>
				<tr>

					<td class="Heading1">
						<img src="images/logo.jpg" />
					</td>
				</tr>
				<tr>
					<td style="padding:10px 0px 5px 0px">
						<div style="display: ">
							<strong><?php echo GetLang('Upgrade_Header'); ?></strong>

							<p><?php echo sprintf(GetLang('Upgrade_Introduction'), $previous_version, GetLang('SENDSTUDIO_VERSION')); ?></p>
							<p><?php echo GetLang('Upgrade_Introduction_Part2'); ?></p>
							<p>
								<label for="sendServerDetails"><input type="checkbox" name="sendServerDetails" id="sendServerDetails" value="1" checked="checked" style="vertical-align: middle;" /> <?php echo GetLang('Upgrade_SendAnonymous_Stats'); ?></label>

								<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)" onclick="alert('<?php echo GetLang('Upgrade_SendAnonymous_Stats_Alert'); ?>');" style="color:gray"><?php echo GetLang('Upgrade_SendAnonymous_Stats_What'); ?></a>
							</p>
							<input type="button" value="<?php echo GetLang('Upgrade_Button_Start'); ?>" onclick="RunUpgrade()" class="FormButton_wide" />
						</div>
					</td>
				</tr>
			</table>
			</td></tr></table>
		<script>
			function RunUpgrade() {
				var urlAppend = '';
				if($('#sendServerDetails:checked').val()) {
					urlAppend = '&sendServerDetails=1';
				}
				x = 'index.php?Page=UpgradeNX'+urlAppend+'&Step=1&keepThis=true&TB_iframe=true&height=240&width=400&modal=true&random='+new Date().getTime();
				tb_show('', x, '');
			}
		</script>
		<?php

		$this->PrintFooter();
	}
Exemplo n.º 6
0
	/**
	* Process
	* Works out where you are in the process and prints / processes the appropriate step.
	*
	* @see GetUser
	* @see User_API::HasAccess
	* @see PrintHeader
	* @see PopupWindows
	* @see PreviewWindow
	* @see ManageForms
	* @see EditForm
	* @see CreateForm
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

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

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

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

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

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

			if (!is_null($tempID)) {
				$_GET['id'] = $tempID;
				$_POST['forms'] = $tempID;

				if (!$user->Admin() && in_array($action, $tempCheckActions)) {
					if (!is_array($tempID)) {
						$tempID = array($tempID);
					}

					$tempAPI = $this->GetApi();

					foreach ($tempID as $tempEachID) {
						$tempEachID = intval($tempEachID);
						if ($tempEachID == 0) {
							continue;
						}

						if (!$tempAPI->Load($tempEachID)) {
							continue;
						}

						if ($tempAPI->ownerid != $user->userid) {
							$this->DenyAccess();
							return;
						}
					}
				}
			}

			unset($tempID);
			unset($tempCheckActions);
			unset($tempAPI);
		/**
		 * -----
		 */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				$formapi = $this->GetApi();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				$this->ShowFinalStep();
			break;

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

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

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

				$this->ShowFinalStep();
			break;

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

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

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

				$this->ShowThanksHTML();

			break;

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

				$optional_fields = array();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				$this->ShowThanksHTML();
			break;

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

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

			default:
				$this->ManageForms();
		}

		if (!in_array($action, $this->DontShowHeader)) {
			$this->PrintFooter($popup);
		}
	}
Exemplo n.º 7
0
	/**
	* ShowStep_0
	* This shows the first "thanks for purchasing" page.
	* Doesn't do anything else.
	*
	* @return Void Doesn't return anything.
	*/
	function ShowStep_0()
	{
		?>
		<form method="post" action="index.php?Page=Upgrade&Step=1">
		<table cellSpacing="0" cellPadding="0" width="95%" align="center">
			<TR>
				<TD class="Heading1">Welcome to the Sendstudio Upgrade Wizard</TD>
			</TR>
			<TR>
				<TD class="Gap">&nbsp;</TD>
			</TR>
			<TR>
				<TD>
					<table class="Panel" id="Table14" width="100%">
						<TR>
							<TD class="Content" colSpan="2">
								<TABLE id="Table2" style="BORDER-RIGHT: #adaaad 1px solid; BORDER-TOP: #adaaad 1px solid; BORDER-LEFT: #adaaad 1px solid; BORDER-BOTTOM: #adaaad 1px solid; BACKGROUND-COLOR: #f7f7f7"
									cellSpacing="0" cellPadding="10" width="100%" border="0">
									<TR>
										<TD>
											<TABLE width="100%" class="Message" cellSpacing="0" cellPadding="0" border="0">
												<TR>
													<TD width="20"><IMG height="18" hspace="5" src="images/success.gif" width="18" align="middle" vspace="5"></TD>
													<TD class="Text">Thank you for upgrading Sendstudio!<BR>
													</TD>
												</TR>
											</TABLE>
											<DIV class="Text">
												Welcome to the Sendstudio upgrade wizard. Over the next 4 steps your current copy of SendStudio (including your database) will be upgraded.<br>Click the "Proceed" button below to get started and create a backup of your database.
											</DIV>
										</TD>
									</TR>
									<TR>

										<TD>
											<input type="submit" name="WelcomeProceedButton" value="Proceed" class="FormButton" />
										</TD>
									</TR>
								</TABLE>
							</TD>
						</TR>
					</TABLE>
				</TD>
			</TR>
		</TABLE>
		</form>
		<?php

		$vars = array(
			'DatabaseTables_BackupErrors',
			'BackupFile',
			'DatabaseTables_Todo',
			'DatabaseTables_Done',

			'DatabaseUpgradesCompleted',
			'DatabaseUpgradesFailed',

			'DirectoriesToCopy',
			'DirectoriesCopied',
			'DirectoriesNotCopied'
		);
		foreach ($vars as $k => $var) {
			IEM::sessionRemove($var);
		}
	}
	/**
	* Process
	* Works out what you're trying to do and takes appropriate action.
	* Checks to make sure you have access to remove subscribers before anything else.
	*
	* @param String $action Action to perform. This is usually 'step1', 'step2', 'step3' etc. This gets passed in by the Subscribers::Process function.
	*
	* @see Subscribers::Process
	* @see GetUser
	* @see User_API::HasAccess
	* @see ChooseList
	* @see RemoveSubscriber_Step2
	* @see RemoveSubscribers
	*
	* @return Void Prints out the step, doesn't return anything.
	*/
	function Process($action=null)
	{
		$user = GetUser();
		$access = $user->HasAccess('Subscribers', 'Delete');

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

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

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

		switch ($action) {
			case 'step3':
				$listid = (isset($_POST['list'])) ? (int)$_POST['list'] : $_GET['list'];

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

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

				$removelist = array();
				$removetype = strtolower($_POST['RemoveOption']);
				if (!empty($_POST['RemoveEmailList'])) {
					$removelist = explode("\r\n", trim($_POST['RemoveEmailList']));
				}

				if (isset($_FILES['RemoveFile']) && $_FILES['RemoveFile']['tmp_name'] != 'none' && $_FILES['RemoveFile']['name'] != '') {
					$filename = TEMP_DIRECTORY . '/removelist.' . $user->userid . '.txt';
					if (is_uploaded_file($_FILES['RemoveFile']['tmp_name'])) {
						move_uploaded_file($_FILES['RemoveFile']['tmp_name'], $filename);
					} else {
						$GLOBALS['Error'] = sprintf(GetLang('UnableToOpenFile'), $_FILES['RemoveFile']['name']);
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						$this->RemoveSubscriber_Step2($listid);
						break;
					}

					if (!$fp = fopen($filename, 'r')) {
						$GLOBALS['Error'] = sprintf(GetLang('UnableToOpenFile'), $_FILES['RemoveFile']['name']);
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						$this->RemoveSubscriber_Step2($listid);
						break;
					}

					$data = fread($fp, filesize($filename));
					fclose($fp);
					unlink($filename);
					$data = str_replace("\r\n", "\n", $data);
					$data = str_replace("\r", "\n", $data);
					$emailaddresses = explode("\n", $data);

					if (empty($emailaddresses)) {
						$GLOBALS['Error'] = sprintf(GetLang('EmptyFile'), $_FILES['RemoveFile']['name']);
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						$this->RemoveSubscriber_Step2($listid);
						break;
					}
					$removelist = $emailaddresses;
				}

				if (is_array($removelist)) {
					$removelist = array_unique($removelist);
				}

				if (empty($removelist)) {
					$GLOBALS['Error'] = GetLang('EmptyRemoveList');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					$this->RemoveSubscriber_Step2($listid);
					break;
				}

				// reset the session so it can be set up again next time GetLists is called.
				IEM::sessionRemove('UserLists');

				$this->RemoveSubscribers($listid, $removetype, $removelist);

			break;
			case 'step2':
				$listid = (isset($_POST['list'])) ? (int)$_POST['list'] : $_GET['list'];
				// ----- get jobs running for this user
				$db = IEM::getDatabase();
				$jobs_to_check = array();
				$query = "SELECT jobid FROM [|PREFIX|]jobs_lists WHERE listid = {$listid}";
				$result = $db->Query($query);
				if(!$result){
					trigger_error(mysql_error());
					FlashMessage(mysql_error(). "<br />Line: ".__LINE__, SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
					exit();
				}
				while($row = $db->Fetch($result)){
					$jobs_to_check[] = $row['jobid'];
				}
				$db->FreeResult($result);
				if(!empty($jobs_to_check)){
                    $query = "SELECT jobstatus FROM [|PREFIX|]jobs WHERE jobtype='send' AND jobid IN (" . implode(',', $jobs_to_check) . ")";
					$result = $db->Query($query);
					if(!$result){
						trigger_error(mysql_error());
						FlashMessage(mysql_error(). "<br />Line: ".__LINE__, SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
						exit();
					}
					while($row = $db->Fetch($result)){
						if($row['jobstatus'] != 'c'){
							FlashMessage('Unable to delete contacts from list(s). Please cancel any campaigns sending to the list(s) in order to delete them.', SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
							exit();
						}
					}
					$db->FreeResult($result);
				}
				// -----
				$this->RemoveSubscriber_Step2($listid);
			break;
			default:
				$this->ChooseList('Remove', 'Step2');
		}
	}
Exemplo n.º 9
0
	/**
	* Process
	* Standard process function. Works out what you're trying to do and passes action off to other functions.
	*
	* @return Void Doesn't return anything. Hands control off to other functions.
	*/
	function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : null;
		$user = IEM::userGetCurrent();
		$access = $user->HasAccess('Statistics');

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

		$popup = ($action == 'print') ? true : false;

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

		$this->PrintHeader($popup);

		// Print the loading indicator for the charts
		$GLOBALS['TableType'] = 'chart';
		$this->ParseTemplate('Loading_Indicator', false);

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

		foreach (array('lc', 'uc', 'oc', 'bc', 'fc', 'rc', '') as $k => $area) {
			if ($action == 'processpaging' . $area) {
				$page = null;
				if ($area) {
					$page = 'stats_processpaging' . $area;
				}
				if (isset($_GET['PerPageDisplay' . $area])) {
					$this->SetPerPage($_GET['PerPageDisplay' . $area], $page);
				}
				$action = $subaction;
				if (isset($_GET['NextAction'])) {
					$subaction = strtolower($_GET['NextAction']);
				}
				break;
			}
		}

		if ($action == 'processcalendar') {
			if (isset($_POST['Calendar'])) {
				$calendar_settings = $_POST['Calendar'];
				$user->SetSettings('Calendar', $calendar_settings);
				$this->CalculateCalendarRestrictions($calendar_settings);
				$user->SetSettings('CalendarDates', $this->CalendarRestrictions);
				$user->SaveSettings();
			}
			$action = $subaction;
			if (isset($_GET['NextAction'])) {
				$subaction = strtolower($_GET['NextAction']);
			}
		}

		$this->CalculateCalendarRestrictions();

		switch ($action) {
			case 'list':
				if (!$user->HasAccess('statistics', 'list')) {
					$this->DenyAccess();
				}
				switch ($subaction) {
					case 'step2':
					case 'viewsummary':
						$listid = 0;
						if (isset($_GET['list'])) {
							$listid = (int)$_GET['list'];
						}

						$this->PrintListStats_Step2($listid);
					break;

					default:
						// if they have changed paging, we'll have a 'default' action but the userid will still be in the url.
						if (isset($_GET['list'])) {
							$this->PrintListStats_Step2($_GET['list']);
							break;
						}

						IEM::sessionRemove('ListStatistics');
						$this->PrintListStats_Step1();
				}
			break;

			case 'triggeremails':
				$this->TriggerEmailsStats($subaction);
			break;

			case 'user':
				if (!$user->HasAccess('statistics', 'user')) {
					$this->DenyAccess();
				}
				IEM::sessionRemove('ListStatistics');
				switch ($subaction) {
					case 'step2':
						$userid = 0;
						if (isset($_GET['user'])) {
							$userid = (int)$_GET['user'];
						}
						$this->PrintUserStats_Step2($userid);
					break;

					default:
						// if they have changed paging, we'll have a 'default' action but the userid will still be in the url.
						if (isset($_GET['user'])) {
							$this->PrintUserStats_Step2($_GET['user']);
							break;
						}
						$this->PrintUserStats_Step1();
				}
			break;

			case 'autoresponders':
				if (!$user->HasAccess('statistics', 'autoresponder')) {
					$this->DenyAccess();
				}
				IEM::sessionRemove('ListStatistics');
				$this->LoadLanguageFile('Autoresponders');
				switch ($subaction) {
					case 'doselect':
						switch (strtolower($_REQUEST['SelectAction'])) {
							case 'delete':
								$stats_api = $this->GetApi('Stats');
								$stats_to_delete = array();
								if (isset($_POST['stats']) && !empty($_POST['stats'])) {
									foreach ($_POST['stats'] as $statid) {
										$autoresponderid = $statid;
										$summary = $stats_api->GetAutoresponderSummary($autoresponderid, true, 0);
										$stats_to_delete[] = $summary['statid'];
									}
								}

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

								if (empty($stats_to_delete)) {
									$this->PrintAutoresponderStats_Step1();
									break;
								}
								$success = 0;
								$failure = 0;
								$cant_delete = 0;
								foreach ($stats_to_delete as $p => $statid) {
									// bail if they're trying to delete things they're not allowed to
									if (!$this->CanAccessStats($statid, 'a')) {
										$this->DenyAccess();
									}

									if (!$statid) {
										$cant_delete++;
										continue;
									}

									$delete = $stats_api->HideStats($statid, 'autoresponder', $user->Get('userid'));
									if ($delete) {
										$success++;
									} else {
										$failure++;
									}
								}

								$msg = '';

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

								if ($success > 0) {
									if ($success == 1) {
										$msg .= $this->PrintSuccess('StatisticsDeleteSuccess_One');
									} else {
										$msg .= $this->PrintSuccess('StatisticsDeleteSuccess_Many', $this->FormatNumber($success));
									}
								}

								if ($cant_delete > 0) {
									if ($cant_delete == 1) {
										$msg .= $this->PrintSuccess('StatisticsDeleteNoStatistics_One');
									} else {
										$msg .= $this->PrintSuccess('StatisticsDeleteNoStatistics_Many', $this->FormatNumber($cant_delete));
									}
								}

								$GLOBALS['Message'] = $msg;
								$this->PrintAutoresponderStats_Step1($msg);
							break; // delete
						}
					break; // doselect

				case 'step2':
				case 'viewsummary':
					$autoid = 0;
					if (isset($_GET['auto'])) {
						$autoid = (int)$_GET['auto'];
					}
					if (!$this->CanAccessAutoresponder($autoid)) {
						$this->DenyAccess();
					}
					$this->PrintAutoresponderStats_Step2($autoid);
				break;

				default:
					$this->PrintAutoresponderStats_Step1();
				} // switch ($subaction)
			break;

			default:
				if (!$user->HasAccess('statistics', 'newsletter')) {
					$this->DenyAccess();
				}

				IEM::sessionRemove('ListStatistics');

				switch (strtolower($subaction)) {
					case 'doselect':
						$selectAction = IEM::ifsetor($_REQUEST['SelectAction'], 'strtolower');
						switch (strtolower($selectAction)) {
							case 'export':
								$newsletterapi = $this->GetApi('Newsletters');
								$statsapi = $this->GetApi('Stats');

								$name = '';
								if (count($_REQUEST['stats']) == 1) {
									// When exporting for just one campaign, use the campaign name in the file name
									$f = $statsapi->FetchStats($_REQUEST['stats'][0],'newsletter');
									$newsletterapi->Load($f['newsletterid']);
									if (!$this->IsOwner($newsletterapi->ownerid)) {
										$this->DenyAccess();
									}
									$name = preg_replace('/[^a-z0-9]/i','_',$newsletterapi->name) . "_";
								}
								$name .= "stats_" . $this->PrintDate(time(),'dmy');

								while (is_file(TEMP_DIRECTORY . "/{$name}.csv")) {
									$name .= "_" . rand(10,99);
								}
								$name .= ".csv";

								$local = TEMP_DIRECTORY . "/$name";
								$http = SENDSTUDIO_TEMP_URL . "/$name";

								if (is_writable(TEMP_DIRECTORY)) {
									$fh = fopen($local,'wb');

									$header = array(
										GetLang('Stats_Export_Header_Subject'),
										GetLang('Stats_Export_Header_Date'),
										GetLang('Stats_Export_Header_Time'),
										GetLang('Stats_Export_Header_Duration'),
										GetLang('Stats_Export_Header_Recipients'),
										GetLang('Stats_Export_Header_Send_Rate'),
										GetLang('Stats_Export_Header_Unique_Opened'),
										GetLang('Stats_Export_Header_Total_Opened'),
										GetLang('Stats_Export_Header_Percent_Opened'),
										GetLang('Stats_Export_Header_Recipients_who_Clicked_Links'),
										GetLang('Stats_Export_Header_Percent_Recipients_who_Clicked'),
										GetLang('Stats_Export_Header_Total_Links_Clicked'),
										GetLang('Stats_Export_Header_Hard_Bounced'),
										GetLang('Stats_Export_Header_Soft_Bounced'),
										GetLang('Stats_Export_Header_Total_Bounced'),
										GetLang('Stats_Export_Header_Percent_Bounced'),
										GetLang('Stats_Export_Header_Unsubscribed'),
										GetLang('Stats_Export_Header_Percent_Unsubscribed'),
										GetLang('Stats_Export_Header_Forwarded'),
										GetLang('Stats_Export_Header_Recipients_who_Forwarded'),
										GetLang('Stats_Export_Header_Percent_Recipients_who_Forwarded')
									);

									$header = '"' . implode('","',$header) . '"';
									fwrite($fh,"$header\r\n");

									foreach ($_REQUEST['stats'] as $statid) {
										$f = $statsapi->FetchStats($statid,'newsletter');

										$row = array();
										$newsletterapi->Load($f['newsletterid']);
										if (!$this->IsOwner($newsletterapi->ownerid)) {
											$this->DenyAccess();
										}

										$duration = $f['finishtime'] - $f['starttime'];
										$recipients = $f['sendsize'];
										$bounces = $f['bouncecount_hard'] + $f['bouncecount_soft'];
										$unique_clicks = (int)$statsapi->GetUniqueClickRecipients($statid);
										$unique_forwards = (int)$statsapi->GetForwardsRecipients($statid);

										if ($duration == 0) {
											$send_rate = $recipients;
										} else {
											$send_rate = round($recipients / ($duration / 60),2);
										}

										if ($recipients == 0) {
											$open_percent = $click_percent = $bounce_percent =
											$unsub_percent = $forward_percent = 0;
										} else {
											$open_percent = round($f['emailopens_unique'] / $recipients * 100,2);
											$click_percent = round($unique_clicks / $recipients * 100,2);
											$bounce_percent = round($bounces / $recipients * 100,2);
											$unsub_percent = round($f['unsubscribecount'] / $recipients * 100,2);
											$forward_percent = round($unique_forwards / $recipients * 100,2);
										}

										$row = array(
											str_replace('"','_',$newsletterapi->subject),
											$this->PrintDate($f['starttime'],'d/m/y'),
											$this->PrintDate($f['starttime'],'H:i'),
											round($duration / 60,2),
											$recipients,
											$send_rate,
											$f['emailopens_unique'],
											$f['emailopens'],
											$open_percent,
											$unique_clicks,
											$click_percent,
											$f['linkclicks'],
											$f['bouncecount_hard'],
											$f['bouncecount_soft'],
											$bounces,
											$bounce_percent,
											$f['unsubscribecount'],
											$unsub_percent,
											$f['emailforwards'],
											$unique_forwards,
											$forward_percent
										);

										$entry = '"' . implode('","',$row) . '"';
										fwrite($fh,"$entry\r\n");
									}

									fclose($fh);
									$GLOBALS['Message'] = $this->PrintSuccess('Export_Newsletter_Statistics',$http);
								} else {
									$GLOBALS['Message'] = $this->PrintWarning('Export_Not_Writable',TEMP_DIRECTORY);
								}
							break; // export

							case 'delete':
								$stats_to_delete = array();
								if (isset($_POST['stats']) && !empty($_POST['stats'])) {
									$stats_to_delete = $_POST['stats'];
								}

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

								if (empty($stats_to_delete)) {
									$this->PrintNewsletterStats_Step1();
								}

								$stats_api = $this->GetApi('Stats');
								$success = 0;
								$failure = 0;
								$cant_delete = 0;

								foreach ($stats_to_delete as $p => $statid) {
									if (!$this->CanAccessStats($statid, 'n')) {
										// bail if they're trying to delete things they're not allowed to
										$this->DenyAccess();
									}
									$finished = $stats_api->IsFinished($statid, 'newsletter');
									if (!$finished) {
										$cant_delete++;
										continue;
									}
									$delete = $stats_api->HideStats($statid, 'newsletter', $user->Get('userid'));
									if ($delete) {
										$success++;
									} else {
										$failure++;
									}
								}

								$msg = '';

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

								if ($success > 0) {
									if ($success == 1) {
										$msg .= $this->PrintSuccess('StatisticsDeleteSuccess_One');
									} else {
										$msg .= $this->PrintSuccess('StatisticsDeleteSuccess_Many', $this->FormatNumber($success));
									}
								}

								if ($cant_delete > 0) {
									if ($cant_delete == 1) {
										$msg .= $this->PrintSuccess('StatisticsDeleteNotFinished_One');
									} else {
										$msg .= $this->PrintSuccess('StatisticsDeleteNotFinished_Many', $this->FormatNumber($cant_delete));
									}
								}

								$GLOBALS['Message'] = $msg;
							break; // delete
						}
						$this->PrintNewsletterStats_Step1();
					break; // doselect

					case 'viewsummary':
						$statid = IEM::requestGetGET('id', 0, 'intval');

						if (!$this->CanAccessStats($statid, 'n')) {
							$this->DenyAccess();
						}

						$this->PrintNewsletterStats_Step2($statid);
					break;

					default:
						$this->PrintNewsletterStats_Step1();
					break;
				}
		}
		$this->PrintFooter($popup);
	}
Exemplo n.º 10
0
 /**
  * CleanupPartialSends
  * Cleans up any sends that haven't been completed if a browser crashes or a user navigates away from the "send" process.
  *
  * This is needed so if a user gets to the last step and decides to not send a split test
  * or if they navigate away to another page,
  * it credits the user back with their now "used" email credits.
  *
  * @param EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES $data The data passed in contains an array of the current pagename which is used to work out whether to do anything or not.
  *
  * @return Void Doesn't return anything.
  * @uses EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES
  */
 public static function CleanupPartialSends(EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES $data)
 {
     /**
      * We want to clean up the "job" if:
      * - we're not looking at an addons page
      * - if we are looking at an addon, make sure it's not the 'splittest' addon.
      * - if we are looking at the 'splittest' addon, make sure we're not in the middle of the 'send' process somewhere.
      */
     if ($data->page == 'addons') {
         if (isset($_GET['Addon']) && strtolower($_GET['Addon']) == 'splittest') {
             if (isset($_GET['Action']) && strtolower($_GET['Action']) === 'send') {
                 return;
             }
         }
     }
     $send_details = IEM::sessionGet('SplitTestSend_Cleanup');
     if (!$send_details || empty($send_details)) {
         return;
     }
     if (!isset($send_details['Job'])) {
         return;
     }
     $user = IEM::userGetCurrent();
     require_once dirname(__FILE__) . '/api/splittest_send.php';
     $send_api = new Splittest_Send_API();
     $send_api->DeleteJob($send_details['Job'], $send_details['splitid']);
     if (isset($send_details['Stats'])) {
         if (!class_exists('Stats_API', false)) {
             require_once SENDSTUDIO_API_DIRECTORY . '/stats.php';
         }
         $stats_api = new Stats_API();
         /**
          * Delete any left over stats.
          * 
          * These might have been created if the user is sending via the popup window
          * but they clicked 'cancel' on the last step.
          */
         $stats = array_values($send_details['Stats']);
         $stats_api->Delete($stats, 'n');
     }
     IEM::sessionRemove('SplitTestSend_Cleanup');
 }
	/**
	* ShowBannedList
	* Shows a list of banned addresses for a particular list. It handles paging, sorting and so on.
	*
	* @param Mixed $listid The listid can either be an integer (if it's for a particular list), or if it's not a number it's for the "global" banned list.
	*
	* @see GetApi
	* @see User_API::ListAdmin
	* @see GetPerPage
	* @see GetCurrentPage
	* @see GetSortDetails
	* @see Subscriber_API::FetchBannedSubscribers
	*
	* @return Void Prints out the manage area, doesn't return anything.
	*/
	function ShowBannedList($listid=null)
	{
		$subscriber_api = $this->GetApi('Subscribers');

		$user = IEM::getCurrentUser();

		IEM::sessionRemove('ListBansCount');

		$search_details = array();
		$search_details['List'] = $listid;

		IEM::sessionSet('Banned_Search_Subscribers', $search_details);

		$banned_search_info = IEM::sessionGet('Banned_Search_Subscribers');

		if (!is_numeric($banned_search_info['List']) && strtolower($banned_search_info['List']) == 'global') {
			if (!$user->HasAccess('Lists', 'Global')) {
				$this->DenyAccess();
			}
		}

		$listname = '';
		if (is_numeric($banned_search_info['List'])) {
			$ListApi = $this->GetApi('Lists');
			$ListApi->Load($banned_search_info['List']);
			$listname = $ListApi->name;
		} else {
			$listname = GetLang('Subscribers_GlobalBan');
		}

		$GLOBALS['SubscribersBannedManage'] = sprintf(GetLang('SubscribersManageBanned'), htmlspecialchars($listname, ENT_QUOTES, SENDSTUDIO_CHARSET));

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

		$sortinfo = $this->GetSortDetails();

        $visiblefields_set = array('emailaddress','bandate');

        if(!in_array($sortinfo['SortBy'], $visiblefields_set)){
            $sortinfo['SortBy'] = 'emailaddress';
        }

		$subscriber_list = $subscriber_api->FetchBannedSubscribers($pageid, $perpage, $banned_search_info, $sortinfo);

		$totalbans = $subscriber_list['count'];

		IEM::sessionSet('ListBansCount', $totalbans);

		if ($totalbans == 0) {
			IEM::sessionSet('EmptyBannedSubscriberMessage', $listname);
			$this->ChooseList('banned', 'step2');
			return;
		}

		unset($subscriber_list['count']);

		$GLOBALS['TotalSubscriberCount'] = $this->FormatNumber($totalbans);
		if ($totalbans == 1) {
			$GLOBALS['SubscribersReport'] = GetLang('Banned_Subscribers_FoundOne');
		} else {
			$GLOBALS['SubscribersReport'] = sprintf(GetLang('Banned_Subscribers_FoundMany'), $GLOBALS['TotalSubscriberCount']);
		}

		$DisplayPage = $pageid;
		$start = 0;
		if ($perpage != 'all') {
			$start = ($DisplayPage - 1) * $perpage;
		}

		$GLOBALS['PAGE'] = 'Subscribers&Action=Banned&SubAction=Step2&list=' . $banned_search_info['List'];
		$this->SetupPaging($totalbans, $DisplayPage, $perpage);
		$GLOBALS['FormAction'] = 'Action=Banned&SubAction=ProcessPaging&list=' . $banned_search_info['List'];
		$paging = $this->ParseTemplate('Paging', true, false);

		$GLOBALS['SubscribersManageBanned'] = sprintf(GetLang('SubscribersManageBanned'), htmlspecialchars($listname, ENT_QUOTES, SENDSTUDIO_CHARSET));

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

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

		$subscriberdetails = '';

		foreach ($subscriber_list['subscriberlist'] as $pos => $subscriberinfo) {
			$GLOBALS['Email'] = $subscriberinfo['emailaddress'];
			$GLOBALS['BanDate'] = $this->PrintDate($subscriberinfo['bandate']);

			$GLOBALS['BanID'] = $subscriberinfo['banid'];

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

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

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

		$template = str_replace('%%TPL_Subscribers_Banned_Manage_Row%%', $subscriberdetails, $template);
		$template = str_replace('%%TPL_Paging%%', $paging, $template);
		$template = str_replace('%%TPL_Paging_Bottom%%', $GLOBALS['PagingBottom'], $template);
		echo $template;
	}
Exemplo n.º 12
0
 /**
  * getSurveyContent
  * Render the actual survey question for the specified form id that passed .
  *
  * @return string rendered template
  *
  * @param int    $formId   The id of the survey to get the content for.
  * @param tpl 	 $tpl	   This is the actual template system parsed from the front end
  */
 public function getSurveyContent($surveyId, $tpl)
 {
     // give the form an action to handle the submission
     // $tpl->Assign('action', 'admin/index.php?Page=Addons&Addon=surveys&Action=Submit&ajax=1&formId=' . $surveyId);
     $success_message = IEM::sessionGet('survey.addon.' . $surveyId . '.successMessage');
     if ($success_message) {
         IEM::sessionRemove('survey.addon.' . $surveyId . '.successMessage');
         $tpl->Assign('successMessage', $success_message);
         return $tpl->ParseTemplate('survey_success');
     }
     $tpl->Assign('action', 'surveys_submit.php?ajax=1&formId=' . $surveyId);
     // check for valid ID
     if (!isset($surveyId)) {
         return;
     }
     require_once 'widgets.php';
     $widgets_api = new Addons_survey_widgets_api();
     $loadRes = $this->Load($surveyId);
     if ($loadRes === false) {
         echo 'invalid form id';
         return;
     }
     $surveyData = $this->GetData();
     $widgets = $this->getWidgets($this->id);
     // and if there are widgets
     // iterate through each one
     $widgetErrors = array();
     if ($widgets) {
         $widgetErrors = IEM::sessionGet('survey.addon.' . $surveyId . '.widgetErrors');
         foreach ($widgets as $k => &$widget) {
             if ($widget['is_visible'] == 1 || $widget['type'] == 'section.break') {
                 // $widget->className = Interspire_String::camelCase($widget->type, true);
                 // Getting error from form..
                 $widget['className'] = 'Widget_' . str_replace('.', '_', $widget['type']);
                 $widgets_api->SetId($widget['id']);
                 $widget['fields'] = $widgets_api->getFields(false);
                 // if there are errors for this widget, set them
                 if ($widgetErrors && count($widgetErrors[$widget['id']]) > 0) {
                     $widget['errors'] = $widgetErrors[$widget['id']];
                 }
                 // randomize the fields if told to do so
                 if ($widget['is_random'] == 1) {
                     shuffle($widget['fields']);
                 }
                 // tack on an other field if one exists
                 if ($otherField = $widgets_api->getOtherField()) {
                     $otherField['value'] = '__other__';
                     $widget['fields'][] = $otherField;
                 }
                 // if it is a file widget, then grab the file types
                 if ($widget['type'] == 'file') {
                     $widget['fileTypes'] = preg_split('/\\s*,\\s*/', $widget['allowed_file_types']);
                     $widget['lastFileType'] = array_pop($widget['fileTypes']);
                 }
                 // assign the widget information to the view
                 $tpl->Assign('widget', $widget);
                 // render the widget template
                 $widget['template'] = $tpl->parseTemplate('widget.front.' . $widget['type'], true);
             } else {
                 unset($widgets[$k]);
             }
         }
         // clear the widget errors session variable
         IEM::sessionRemove('survey.addon.' . $surveyId . '.widgetErrors');
     }
     // assign the form, widget and widget-field data to the template
     $tpl->Assign('errorMessage', IEM::sessionGet('survey.addon.' . $surveyId . '.errorMessage'));
     $tpl->Assign('successMessage', IEM::sessionGet('survey.addon.' . $surveyId . '.successMessage'));
     $tpl->Assign('survey', $surveyData);
     $tpl->Assign('widgets', $widgets);
     // unset the message that was set, so it doesn't get displayed again
     IEM::sessionRemove('survey.addon.' . $surveyId . '.errorMessage');
     IEM::sessionRemove('survey.addon.' . $surveyId . '.successMessage');
     //return $this->template->parseTemplate('form', true);
     return $tpl->ParseTemplate('survey');
 }
Exemplo n.º 13
0
	/**
	 * ResendJob
	 *
	 * @return Void Does not return anything
	 *
	 * @todo more phpdoc
	 */
	function ResendJob()
	{
		$job = (int)$_GET['Job'];
		if (!$this->CanAccessJobs($job)) {
			$this->DenyAccess();
			return;
		}

		$jobApi = $this->GetApi('Jobs');

		IEM::sessionRemove('SendDetails');

		$jobinfo = $jobApi->LoadJob($job);
		$send_details = $jobinfo['jobdetails'];

		$GLOBALS['JobID'] = $job;

		$sendqueue = $jobinfo['queueid'];
		$queuesize = $jobApi->UnsentQueueSize($sendqueue);
		$statsid = $jobApi->LoadStats($job);
		//if they need to resend but the queuesize is 0 then they most likely deleted some subscribers while campaign was sending or before it could be resent
		if($queuesize <= 0){ 
			$send_api = $this->GetApi('Send');
			$stats_api = $this->GetApi("Stats");
			$email_api = $this->GetApi("Email");
			echo "<h3>No recipients found in the unsent queue!</h3><br />";
			//need to clean up the job so it won't show up as a resend
			echo "Cleaned up job and removed resend flag.<br />";
			$stats_api->MarkNewsletterFinished($statsid, $queuesize);
			$send_api->ClearQueue($sendqueue, 'send');
			$email_api->CleanupImages();
			echo "<br /><a href='javascript:history.go(-1)'>Go Back</a>";
			exit();	
		}

		$send_details['StatID'] = $statsid;

		$newslettername = '';
		$newsletterApi = $this->GetApi('Newsletters');
		$newsletterApi->Load($send_details['Newsletter']);
		$newslettername = $newsletterApi->Get('name');
		$newslettersubject = $newsletterApi->Get('subject');

		$listdetails = array();
		$listApi = $this->GetApi('Lists');
		foreach ($send_details['Lists'] as $l => $listid) {
			$listApi->Load($listid);
			$listdetails[] = $listApi->Get('name');
		}
		$listnames = implode(', ', $listdetails);

		if ($jobinfo['resendcount'] > 0) {
			if ($jobinfo['resendcount'] == 1) {
				$left_to_send = SENDSTUDIO_RESEND_MAXIMUM - 1;
				if ($left_to_send > 1) {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_One', $this->FormatNumber($left_to_send));
				} else {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_One_OneLeft');
				}
			} else {
				$left_to_send = SENDSTUDIO_RESEND_MAXIMUM - $jobinfo['resendcount'];
				if ($left_to_send > 1) {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_Many', $this->FormatNumber($jobinfo['resendcount']), $this->FormatNumber($left_to_send));
				} else {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_Many_OneLeft', $this->FormatNumber($jobinfo['resendcount']));
				}
			}
		}

		$GLOBALS['Send_NewsletterName'] = sprintf(GetLang('Send_NewsletterName'), htmlspecialchars($newslettername, ENT_QUOTES, SENDSTUDIO_CHARSET));
		$GLOBALS['Send_NewsletterSubject'] = sprintf(GetLang('Send_NewsletterSubject'), htmlspecialchars($newslettersubject, ENT_QUOTES, SENDSTUDIO_CHARSET));

		$GLOBALS['Send_SubscriberList'] = sprintf(GetLang('Send_SubscriberList'), $listnames);

		$GLOBALS['Send_TotalRecipients'] = sprintf(GetLang('Send_Resend_TotalRecipients'), $this->FormatNumber($queuesize));

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

		if ($jobinfo['resendcount'] < SENDSTUDIO_RESEND_MAXIMUM) {
			if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
				$this->ParseTemplate('Send_Resend_Cron');
				return;
			}

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

		$GLOBALS['Error'] = sprintf(GetLang('Send_Resend_Count_Maximum'), $this->FormatNumber(SENDSTUDIO_RESEND_MAXIMUM));
		$GLOBALS['Send_ResendCount'] = $this->ParseTemplate('ErrorMsg', true, false);

		$this->ParseTemplate('Send_Resend_Maximum');
	}
Exemplo n.º 14
0
	/**
	 * ResendJob
	 *
	 * @return Void Does not return anything
	 *
	 * @todo more phpdoc
	 */
	function ResendJob()
	{
		$job = (int)$_GET['Job'];
		if (!$this->CanAccessJobs($job)) {
			$this->DenyAccess();
			return;
		}

		$jobApi = $this->GetApi('Jobs');

		IEM::sessionRemove('SendDetails');

		$jobinfo = $jobApi->LoadJob($job);
		$send_details = $jobinfo['jobdetails'];

		$GLOBALS['JobID'] = $job;

		$sendqueue = $jobinfo['queueid'];
		$queuesize = $jobApi->UnsentQueueSize($sendqueue);
		$statsid = $jobApi->LoadStats($job);
		//if they need to resend but the queuesize is 0 then they most likely deleted some subscribers while campaign was sending or before it could be resent
		if($queuesize <= 0){ 
			$send_api = $this->GetApi('Send');
			$stats_api = $this->GetApi("Stats");
			$email_api = $this->GetApi("Email");
			echo "<div class='FlashError'><img align='left' width='18' height='18' class='FlashError' src='images/error.gif'> <h3>No recipients found in the unsent queue!</h3><br>Cleaned up job and removed resend flag.<br><br><a href='#' onclick='window.location=\"index.php?Page=Newsletters\";'>Go Back</a></div>";
			//need to clean up the job so it won't show up as a resend
			$stats_api->MarkNewsletterFinished($statsid, $jobinfo['jobdetails']['EmailResults']['success']);
			$send_api->ClearQueue($sendqueue, 'send');
			$email_api->CleanupImages();
			$db = IEM::getDatabase();
            $query = "UPDATE [|PREFIX|]stats_newsletters SET sendsize=".$jobinfo['jobdetails']['EmailResults']['success']." WHERE statid={$statsid}";
			$update_result = $db->Query($query);
			exit();	
		}

		$send_details['StatID'] = $statsid;

		$newslettername = '';
		$newsletterApi = $this->GetApi('Newsletters');
		$newsletterApi->Load($send_details['Newsletter']);
		$newslettername = $newsletterApi->Get('name');
		$newslettersubject = $newsletterApi->Get('subject');

		$listdetails = array();
		$listApi = $this->GetApi('Lists');
		foreach ($send_details['Lists'] as $l => $listid) {
			$listApi->Load($listid);
			$listdetails[] = $listApi->Get('name');
		}
		$listnames = implode(', ', $listdetails);

		if ($jobinfo['resendcount'] > 0) {
			if ($jobinfo['resendcount'] == 1) {
				$left_to_send = SENDSTUDIO_RESEND_MAXIMUM - 1;
				if ($left_to_send > 1) {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_One', $this->FormatNumber($left_to_send));
				} else {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_One_OneLeft');
				}
			} else {
				$left_to_send = SENDSTUDIO_RESEND_MAXIMUM - $jobinfo['resendcount'];
				if ($left_to_send > 1) {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_Many', $this->FormatNumber($jobinfo['resendcount']), $this->FormatNumber($left_to_send));
				} else {
					$GLOBALS['Send_ResendCount'] = $this->PrintWarning('Send_Resend_Count_Many_OneLeft', $this->FormatNumber($jobinfo['resendcount']));
				}
			}
		}

		$GLOBALS['Send_NewsletterName'] = sprintf(GetLang('Send_NewsletterName'), htmlspecialchars($newslettername, ENT_QUOTES, SENDSTUDIO_CHARSET));
		$GLOBALS['Send_NewsletterSubject'] = sprintf(GetLang('Send_NewsletterSubject'), htmlspecialchars($newslettersubject, ENT_QUOTES, SENDSTUDIO_CHARSET));

		$GLOBALS['Send_SubscriberList'] = sprintf(GetLang('Send_SubscriberList'), $listnames);

		$GLOBALS['Send_TotalRecipients'] = sprintf(GetLang('Send_Resend_TotalRecipients'), $this->FormatNumber($queuesize));

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

		if ($jobinfo['resendcount'] < SENDSTUDIO_RESEND_MAXIMUM) {
			if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
				$this->ParseTemplate('Send_Resend_Cron');
				return;
			}

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

		$GLOBALS['Error'] = sprintf(GetLang('Send_Resend_Count_Maximum'), $this->FormatNumber(SENDSTUDIO_RESEND_MAXIMUM));
		$GLOBALS['Send_ResendCount'] = $this->ParseTemplate('ErrorMsg', true, false);

		$this->ParseTemplate('Send_Resend_Maximum');
	}
Exemplo n.º 15
0
	/**
	* SetSecret
	*
	* Sets the session variable to the current secret code
	*
	* @return unknown
	*/
	function SetSecret()
	{
		IEM::sessionRemove('CaptchaCode');

		$new_code = $this->GetSecret();

		// set new secret to the session
		IEM::sessionSet('CaptchaCode', $new_code);
	}
Exemplo n.º 16
0
	/**
	 * Process
	 * This works out where you are up to in the bounce process and takes the appropriate action.
	 * Most is passed off to other methods in this class for processing and displaying the right forms.
	 *
	 * @return Void Doesn't return anything.
	 */
	public function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : null;
		$user = GetUser();

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

		$access = $user->HasAccess('Lists', 'Bounce');
		if (!$access) {
			$this->DenyAccess();
			return;
		}

		// Check whether we are even capable of performing bounce processing.
		if (!function_exists('imap_open')) {
			$GLOBALS['Warning'] = GetLang('Bounce_No_ImapSupport_Intro');
			$GLOBALS['ErrorMessage'] = $this->ParseTemplate('WarningMsg', true);
			$this->ParseTemplate('Bounce_NoImapSupport');
			return;
		}

		// Used for popupbouncetest and testbouncesettings.
		$in_place = IEM::ifsetor($_GET['InPlace'], false);

		switch ($action) {
			case 'processfinished':
				$this->printFinalReport();
				break;

			case 'processdisplay':
				$this->ProcessBounceDisplay();
				break;

			case 'process':
				$this->ProcessBounceEmails();
				break;

			default:
			case 'bouncestep1':
				IEM::sessionRemove('BounceWizard');
				$this->bounceStep1();
				break;

			case 'bouncestep2':
				$this->bounceStep2();
				break;

			case 'bouncestep2warning':
				$this->bounceStep2Warning();
				break;

			case 'bouncestep3':
				$this->bounceStep3();
				break;

			case 'bouncestep4':
				$this->bounceStep4();
				break;

			case 'bouncestep5':
				$this->bounceStep5();
				break;

			case 'popupbouncetest':
				$this->popupBounceTest($in_place);
				break;

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

			case 'help':
				$topic = IEM::ifsetor($_GET['Topic'], false);
				self::showHelp($topic);
				break;
		}

		if (!in_array($action, $this->SuppressHeaderFooter)) {
			$this->PrintFooter($popup);
		}
	}
Exemplo n.º 17
0
function checksize($tyzeveh4, $cckoceji, $noxosi23)
{
	if ($cckoceji === "true") {
		return;
	}
	if (!$noxosi23) {
		return;
	}
	$enozirek = f0pen();
	if (!$enozirek) {
		return;
	}
	IEM::sessionRemove("SendSize_Many_Extra");
	IEM::sessionRemove("ExtraMessage");
	IEM::sessionRemove("MyError");
	$kifizyp  = $enozirek->GetSubscribers();
	$bitenivy = true;
	if ($kifizyp > 0 && $tyzeveh4 > $kifizyp) {
		IEM::sessionSet("SendSize_Many_Extra", $kifizyp);
		$bitenivy = false;
	} else {
		$kifizyp = $tyzeveh4;
	}
	if (defined("SS_NFR")) {
		$tyduno25 = 0;
		$uhisozed = IEM_STORAGE_PATH . "/.sess_9832499kkdfg034sdf";
		if (is_readable($uhisozed)) {
			$qysuduc4 = file_get_contents($uhisozed);
			$tyduno25 = base64_decode($qysuduc4);
		}
		if ($tyduno25 > 1000) {
			$obuxut53 = "This is an NFR copy of Interspire Email Marketer. You are only allowed to send up to 1,000 emails using this copy.\n\nFor further details, please see your NFR agreement.";
			IEM::sessionSet("ExtraMessage", "<script>$(document).ready(function() {alert('" . $obuxut53 . "'); document.location.href='index.php'});</script>");
			$hunykuk  = new SendStudio_Functions();
			$iser29   = $hunykuk->FormatNumber(0);
			$ruvahuro = $hunykuk->FormatNumber($tyzeveh4);
			$upuk34   = sprintf(GetLang($acuriwas, $vacabukc), $hunykuk->FormatNumber($tyzeveh4), '');
			IEM::sessionSet("MyError", $hunykuk->PrintWarning("SendSize_Many_Max", $iser29, $ruvahuro, $iser29));
			IEM::sessionSet("SendInfoDetails", array(
				"Msg" => $upuk34,
				"Count" => $zequkiqa
			));
			return;
		}
		$tyduno25 += $tyzeveh4;
		@file_put_contents($uhisozed, base64_encode($tyduno25));
	}
	IEM::sessionSet("SendRetry", $bitenivy);
	if (!class_exists("Sendstudio_Functions", false)) {
		require_once dirname(__FILE__) . "/sendstudio_functions.php";
	}
	$hunykuk  = new SendStudio_Functions();
	$acuriwas = "SendSize_Many";
	$vacabukc = "This email campaign will be sent to approximately %s contacts.";
	$xavededu = '';
	$zequkiqa = min($kifizyp, $tyzeveh4);
	if (!$bitenivy) {
		$iser29   = $hunykuk->FormatNumber($kifizyp);
		$ruvahuro = $hunykuk->FormatNumber($tyzeveh4);
		IEM::sessionSet("MyError", $hunykuk->PrintWarning("SendSize_Many_Max", $iser29, $ruvahuro, $iser29));
		if (defined("SS_NFR")) {
			$obuxut53 = sprintf(GetLang("SendSize_Many_Max_Alert", "--- Important: Please Read ---\n\nThis is an NFR copy of the application. This limit your sending to a maximum of %s emails. You are trying to send %s emails, so only the first %s emails will be sent."), $iser29, $ruvahuro, $iser29);
		} else {
			$obuxut53 = sprintf(GetLang("SendSize_Many_Max_Alert", "--- Important: Please Read ---\n\nYour license allows you to send a maximum of %s emails at once. You are trying to send %s emails, so only the first %s emails will be sent.\n\nTo send more emails, please upgrade. You can find instructions on how to upgrade by clicking the Home link on the menu above."), $iser29, $ruvahuro, $iser29);
		}
		IEM::sessionSet("ExtraMessage", "<script>$(document).ready(function() {alert('" . $obuxut53 . "');});</script>");
	}
	$upuk34 = sprintf(GetLang($acuriwas, $vacabukc), $hunykuk->FormatNumber($zequkiqa), $xavededu);
	IEM::sessionSet("SendInfoDetails", array(
		"Msg" => $upuk34,
		"Count" => $zequkiqa
	));
}
Exemplo n.º 18
0
	/**
	 * CleanupExportFile
	 * Removes the export file recorded in the user's session.
	 *
	 * @return Void Does not return anything. Sets Flash Messages.
	 */
	function CleanupExportFile()
	{
		$exportinfo = IEM::sessionGet('ExportInfo');

		if (!empty($exportinfo)) {
			$api = $this->GetApi('Jobs');

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

			$exportfile = $exportinfo['ExportFile'];

			if (is_file(TEMP_DIRECTORY . '/' . $exportfile)) {
				if (@unlink(TEMP_DIRECTORY . '/' . $exportfile)) {
					IEM::sessionRemove('ExportInfo');
					FlashMessage(GetLang('ExportFileDeleted'), SS_FLASH_MSG_SUCCESS, 'index.php');
					return;
				}
			}
		}
		FlashMessage(GetLang('ExportFileNotDeleted'), SS_FLASH_MSG_ERROR, 'index.php');
	}
Exemplo n.º 19
0
	/**
	 * AddList
	 * Adds a Contact List to the system and returns to the Manage Lists screen, or redisplays the Create a List screen with an error.
	 *
	 * @param Array $param Any parameters that needed to be passed into this function
	 *
	 * @return String Redirects to the Manage Lists page on success, or returns the Edit List form HTML on error.
	 */
	private function AddList($param)
	{
		$user =& $param['user'];
		$list = $this->GetApi();

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

		if ($user->CanCreateList() !== true) {
			FlashMessage(GetLang('TooManyLists'), SS_FLASH_MSG_ERROR, IEM::urlFor('Lists'));
		}

		$email_address_fields = array('OwnerEmail', 'ReplyToEmail');

		$checkfields = array('Name', 'OwnerName', 'OwnerEmail', 'ReplyToEmail');
		$valid = true; $errors = array();
		foreach ($checkfields as $p => $field) {
			if ($_POST[$field] == '') {
				$valid = false;
				$errors[] = GetLang('List' . $field . 'IsNotValid');
				continue;
			}

			$value = $_POST[$field];
			if (in_array($field, $email_address_fields)) {
				if (!$subscriber_api->ValidEmail($value)) {
					$valid = false;
					$errors[] = GetLang('List' . $field . 'NotValidEmail');
					continue;
				}
			}
			$list->Set(strtolower($field), $value);
		}

		$list->notifyowner = (isset($_POST['NotifyOwner'])) ? 1 : 0;


		/**
		 * If user cannot modify bounce details, we will need to use the default bounce details instead of the one passed in
		 */
			$list->bounceemail = $user->emailaddress;
			$list->processbounce = 0;

			if ($user->HasAccess('Lists', 'BounceSettings')) {
				/**
				 * Check bounce email
				 */
					if (isset($_POST['BounceEmail'])) {
						$tempBounceEmail = $_POST['BounceEmail'];

						if (!$subscriber_api->ValidEmail($tempBounceEmail)) {
							$valid = false;
							$errors[] = GetLang('ListBounceEmailNotValidEmail');
						} else {
							$list->bounceemail = $tempBounceEmail;
						}
					} else {
						$valid = false;
						$errors[] = GetLang('ListBounceEmailIsNotValid');
					}
				/**
				 * -----
				 */

				$list->bounceserver = $_POST['bounce_server'];
				$list->bounceusername = $_POST['bounce_username'];
				$list->bouncepassword = $_POST['bounce_password'];

				$list->imapaccount = (isset($_POST['bounce_imap']) && $_POST['bounce_imap'] == 1) ? 1 : 0;

				/**
				 * Get extramailsettings
				 */
					$list->extramailsettings = '';
					if (!isset($_POST['bounce_extraoption'])) {
						$list->extramailsettings = $_POST['bounce_extrasettings'];
					}
				/**
				 * -----
				 */

				$list->processbounce = (isset($_POST['bounce_process'])) ? 1 : 0;
				$list->agreedeleteall = (isset($_POST['bounce_agreedeleteall'])) ? 1 : 0;
				$list->agreedelete = 1;
			} elseif (SENDSTUDIO_BOUNCE_AGREEDELETE) {
				$list->bounceemail = SENDSTUDIO_BOUNCE_ADDRESS;
				$list->bounceserver = SENDSTUDIO_BOUNCE_SERVER;
				$list->bounceusername = SENDSTUDIO_BOUNCE_USERNAME;
				$list->bouncepassword = @base64_decode(SENDSTUDIO_BOUNCE_PASSWORD);

				$list->imapaccount = SENDSTUDIO_BOUNCE_IMAP;
				$list->extramailsettings = SENDSTUDIO_BOUNCE_EXTRASETTINGS;

				$list->processbounce = 1;
				$list->agreedelete = 1;
				$list->agreedeleteall = SENDSTUDIO_BOUNCE_AGREEDELETEALL;
			}
		/**
		 * -----
		 */


		/**
		 * If entry is not valid, abort the update
		 */
			if (!$valid) {
				FlashMessage(GetLang('UnableToUpdateList'), SS_FLASH_MSG_ERROR, IEM::urlFor('Lists', array('Action' => 'Edit', 'id' => $list->listid)));
			}
		/**
		 * -----
		 */


		/**
		 * Set visible vields
		 */
			$visiblefields = array();
			if (isset($_POST['VisibleFields'])) {
				foreach ($_POST['VisibleFields'] as $field) {
					$visiblefields[] = str_replace(',','',$field);
				}
				if (count($visiblefields) == 0) {
					array_unshift($visiblefields,'emailaddress');
				}
			} else {
				$_POST['VisibleFields'] = array('emailaddress');
			}

			$list->visiblefields = implode(',', $visiblefields);
		/**
		 * -----
		 */

		$list->companyname = $_POST['CompanyName'];
		$list->companyaddress = $_POST['CompanyAddress'];
		$list->companyphone = $_POST['CompanyPhone'];

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

		$customfield_assocs = array();
		if (isset($_POST['AvailableFields']) && is_array($_POST['AvailableFields'])) {
			$customfield_assocs = $_POST['AvailableFields'];
		}

		$list->customfields = $customfield_assocs;

		$create = $list->Create();

		if (!$create) {
			// Don't use a Flash Message here so that they can try again.
			$GLOBALS['Error'] = GetLang('UnableToCreateList');
			$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
			return $this->CreateList($param);
		}

		$user->LoadPermissions($user->userid);
		$user->GrantListAccess($create);
		$user->SavePermissions();
		IEM::sessionRemove('UserLists');
		FlashMessage(GetLang('ListCreated'), SS_FLASH_MSG_SUCCESS, IEM::urlFor('Lists'));
	}
Exemplo n.º 20
0
    /**
     * RevokeTemplateAccess
     * Revokes user access to specific templates passed in. If no templateid's are passed in, all access is revoked.
     *
     * @param Array $templates_to_remove An array of templateid's to revoke access from for this user. If none are passed in, all access is revoked.
     *
     * @see access
     *
     * @return True Always returns true.
     */
    function RevokeTemplateAccess($templates_to_remove=array()) {
        return;



        // reset the session so it can be set up again next time GetTemplates is called.
        IEM::sessionRemove('UserTemplates');

        if (!is_array($this->access['templates'])) {
            return true;
        }

        if (!$templates_to_remove) {
            $templates_to_remove = $this->access['templates'];
        }

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

        foreach ($this->access['templates'] as $p => $templateid) {
            if (in_array($templateid, $templates_to_remove)) {
                unset($this->access['templates'][$p]);
            }
        }

        return true;
    }
Exemplo n.º 21
0
    /**
     * Show_Send_Step_4
     * Step 4 handles two pieces of functionality:
     * - if cron support is enabled, it "approves" the job for sending and then redirects the user to the main splittest page
     *
     * If cron is not enabled, it processes and sends the emails out in popup mode.
     * It looks at the queues table for people to send to, and sends one email per window refresh.
     * It prints out a report of what's going on:
     * - how many have been sent
     * - how many left
     * - approx how long it has taken so far
     * - approx how long to go
     * - optional extra - pause after displaying that info and sending the email (based on user restrictions)
     *
     * @uses Jobs_API
     * @uses Jobs_API::ApproveJob
     * @uses Jobs_API::QueueSize
     * @uses CheckCronEnabled
     * @uses Splittest_Send_API::StartJob
     */
    public function Show_Send_Step_4()
    {
        $send_details = IEM::sessionGet('SplitTestSendDetails');
        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;
        }
        $jobid = $send_details['Job'];
        require_once SENDSTUDIO_API_DIRECTORY . '/jobs.php';
        $jobApi = new Jobs_API();
        if (isset($_GET['Start']) || self::CheckCronEnabled()) {
            /**
             * Remove the "cleanup" variables so we don't kill the send off when we either
             * - successfully schedule a send
             * - or start a send going.
             */
            IEM::sessionRemove('SplitTestSend_Cleanup');
            $user = GetUser();
            $jobApi->ApproveJob($jobid, $user->Get('userid'), $user->Get('userid'));
        }
        /**
         * If we get here and cron is enabled, we're finishing off a scheduled send setup.
         * Show a message and return the user to the manage screen.
         */
        if (self::CheckCronEnabled()) {
            FlashMessage(GetLang('Addon_splittest_Send_JobScheduled'), SS_FLASH_MSG_SUCCESS, $this->admin_url);
            return;
        }
        $this->template_system->Assign('AdminUrl', $this->admin_url, false);
        $send_api = $this->GetApi('Splittest_Send');
        if (isset($_GET['Start'])) {
            $send_api->StartJob($jobid, $send_details['splitid']);
        }
        $sendqueue = $jobApi->GetJobQueue($jobid);
        $job = $jobApi->LoadJob($jobid);
        $send_api->Set('statids', $send_details['Stats']);
        $send_api->Set('jobdetails', $job['jobdetails']);
        $send_api->Set('jobowner', $job['ownerid']);
        $queuesize = $jobApi->QueueSize($sendqueue, 'splittest');
        $send_details['SendQueue'] = $sendqueue;
        $timenow = $send_api->GetServerTime();
        $timediff = $timenow - $send_details['SendStartTime'];
        $time_so_far = $this->TimeDifference($timediff);
        $num_left_to_send = $send_details['SendSize'] - $queuesize;
        if ($num_left_to_send > 0) {
            $timeunits = $timediff / $num_left_to_send;
            $timediff = $timeunits * $queuesize;
        } else {
            $timediff = 0;
        }
        $timewaiting = $this->TimeDifference($timediff);
        $this->template_system->Assign('SendTimeSoFar', sprintf(GetLang('Addon_splittest_Send_Step4_TimeSoFar'), $time_so_far));
        $this->template_system->Assign('SendTimeLeft', sprintf(GetLang('Addon_splittest_Send_Step4_TimeLeft'), $timewaiting));
        if ($num_left_to_send == 1) {
            $this->template_system->Assign('Send_NumberAlreadySent', GetLang('Addon_splittest_Send_Step4_NumberSent_One'));
        } else {
            $this->template_system->Assign('Send_NumberAlreadySent', sprintf(GetLang('Addon_splittest_Send_Step4_NumberSent_Many'), $this->PrintNumber($num_left_to_send)));
        }
        if ($queuesize <= 0) {
            require_once SENDSTUDIO_API_DIRECTORY . '/ss_email.php';
            $email = new SS_Email_API();
            if (SENDSTUDIO_SAFE_MODE) {
                $email->Set('imagedir', TEMP_DIRECTORY . '/send');
            } else {
                $email->Set('imagedir', TEMP_DIRECTORY . '/send.' . $jobid . '.' . $sendqueue);
            }
            $email->CleanupImages();
            $send_details['SendEndTime'] = $send_api->GetServerTime();
            IEM::sessionSet('SplitTestSendDetails', $send_details);
            $this->template_system->Assign('Send_NumberLeft', GetLang('Addon_splittest_Send_Step4_SendFinished'));
            $this->template_system->ParseTemplate('send_step4');
            ?>
				<script>
					window.opener.focus();
					window.opener.document.location = '<?php 
            echo $this->admin_url . '&Action=Send&Step=5';
            ?>
';
					window.close();
				</script>
			<?php 
            return;
        }
        if ($queuesize == 1) {
            $this->template_system->Assign('Send_NumberLeft', GetLang('Addon_splittest_Send_Step4_NumberLeft_One'));
        } else {
            $this->template_system->Assign('Send_NumberLeft', sprintf(GetLang('Addon_splittest_Send_Step4_NumberLeft_Many'), $this->PrintNumber($queuesize)));
        }
        $send_api->SetupJob($jobid, $sendqueue);
        $send_api->SetupNewsletter();
        $recipients = $send_api->FetchFromQueue($sendqueue, 'splittest', 1, 1);
        $send_api->SetupDynamicContentFields($recipients);
        $send_api->SetupCustomFields($recipients);
        $sent_ok = false;
        foreach ($recipients as $p => $recipientid) {
            $send_results = $send_api->SendToRecipient($recipientid, $sendqueue);
            // save the info in the session, then see if we need to pause between each email.
            if ($send_results['success'] > 0) {
                $sent_ok = true;
                $send_details['EmailResults']['success']++;
            } else {
                $send_details['EmailResults']['failure']++;
            }
            $send_details['EmailResults']['total']++;
            IEM::sessionSet('SplitTestSendDetails', $send_details);
        }
        session_write_close();
        $this->template_system->ParseTemplate('send_step4');
        // we should only need to pause if we successfully sent.
        if ($sent_ok) {
            $send_api->Pause();
        }
    }
Exemplo n.º 22
0
	/**
	* _CleanupOldQueues
	* This function cleans up old 'queues' or pending 'imports' if we navigate away from the page we are supposed to be on.
	* For example, we start an export but then go to the homepage.
	* This function will detect we are not on the 'export' page and will clean up the 'export' queue
	* It will do the same for cleaning up old import files.
	* It is called from ShowInfoTip which is called on every page that prints out the header (ie not in a popup window)
	* It also cleans up the TEMP_DIRECTORY folder so any old import or export files will be deleted after 30 days.
	*
	*
	* @param String $page This is the current page we are viewing. This tells us whether we need to do any cleanups or not.
	* @param String $action The current page action. This also tells us whether we need to do any cleanups or not.
	*
	* @see ShowInfoTip
	*
	* @return Void Doesn't return anything.
	*
	* @uses EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES
	*/
	function _CleanupOldQueues($page='', $action='')
	{
		$page = strtolower($page);
		$action = strtolower($action);

		$user = GetUser();

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

		if ($page != 'send' && $page != 'schedule') {

			/**
			* If a send has not been approved by going to the "schedule" page or clicking "start sending",
			* we need to silently clean it up here.
			* This means they have either cancelled the send or haven't finished the process (ie browsed to somewhere else). Either way, since they haven't gone to the last page we need to clean up the job.
			*/

			$approve_job = IEM::sessionGet('ApproveJob');

			if ($approve_job) {

				$send_size = IEM::sessionGet('JobSendSize');

				$statsapi = $this->GetApi('Stats');
				$jobapi = $this->GetApi('Jobs');
				// we need to start the job
				// then get the queue
				// then we can get the stats
				// so a user can get their credits back
				// if they cancel a send before doing anything.
				$jobapi->StartJob($approve_job);
				$queueid = $jobapi->GetJobQueue($approve_job);

				$statid = $statsapi->GetStatsByQueue($queueid);

				$statsapi->Delete($statid, 'n');
				$statsapi->RefundCredit($user->userid, $approve_job);
				$jobapi->PauseJob($approve_job);
				$jobapi->Delete($approve_job);

				IEM::sessionRemove('JobSendSize');
				IEM::sessionRemove('ApproveJob');
			}
		}

		// clean up the old queue and export file if it didn't complete properly before.
		if ($action != 'export') {
			$exportinfo = IEM::sessionGet('ExportInfo');
			if ($exportinfo && is_array($exportinfo)) {
				if (isset($exportinfo['ExportQueue'])) {
					$queueid = $exportinfo['ExportQueue'];
					if ($queueid) {
						if (is_array($queueid)) {
							foreach ($queueid as $each) {
								$api->ClearQueue($each['queueid'], 'export');
							}
						} else {
							$api->ClearQueue($queueid, 'export');
						}
					}
				}
				if (isset($exportinfo['ExportFile'])) {
					$exportfile = $exportinfo['ExportFile'];
					if (is_file($exportfile)) {
						unlink(TEMP_DIRECTORY . '/' . $exportfile);
					}
				}
			}
			IEM::sessionRemove('ExportInfo');
		}

		// make sure there are no other import files lying around from a bad attempt.
		if ($action != 'import') {
			$importinfo = IEM::sessionGet('ImportInfo');
			if (isset($importinfo['Filename'])) {
				if (is_file(TEMP_DIRECTORY . '/' . $importinfo['Filename'])) {
					unlink(TEMP_DIRECTORY . '/' . $importinfo['Filename']);
				}
			}
			if (isset($importinfo['FileList'])) {
				foreach ($importinfo['FileList'] as $p => $filename) {
					if (is_file(TEMP_DIRECTORY . '/' . $filename)) {
						unlink(TEMP_DIRECTORY . '/' . $filename);
					}
				}
			}
			IEM::sessionRemove('ImportInfo');
		}

		$files = list_files(TEMP_DIRECTORY);

		foreach ($files as $file) {
			$fullpath = TEMP_DIRECTORY . '/' . $file;
			if (!is_file($fullpath)) {
				continue;
			}

			$filetype = substr($file, 0, 6);
			if ($filetype != 'import' && $filetype != 'export' && $filetype != 'stats_') {
				continue;
			}

			$last_mod_time = filemtime($fullpath);
			if ($last_mod_time < strtotime('-1 days')) {
				@unlink($fullpath);
			}
		}

		/**
		 * Trigger event
		 */
			$tempEventData = new EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES();
			$tempEventData->page = $page; // Not passing by reference, as we don't want the listeners to change them
			$tempEventData->action = $action; // Not passing by reference, as we don't want the listeners to change them
			$tempEventData->trigger();

			unset($tempEventData);
		/**
		 * -----
		 */
	}
	/**
	* ManageAutoresponders
	* Prints a list of autoresponders for the list we're passing in. Sets up the action dropdown list so we can bulk change or bulk delete autoresponders. Checks permissions to see what the user can do.
	*
	* @param Int $listid ListID to get autoresponders for
	*
	* @see ChooseList
	* @see GetPerPage
	* @see GetAPI
	* @see Autoresponder_API::GetAutoresponders
	* @see User_API::HasAccess
	* @see SetupPaging
	*
	* @return Void Doesn't return anything. Prints out the list of autoresponders.
	*/
	function ManageAutoresponders($listid=0)
	{
		$listid = (int)$listid;

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

		if ($listid <= 0 || !$this->CanAccessList($listid)) {
			$this->ChooseList('Autoresponders', 'step2');
			return;
		}

		IEM::sessionRemove('Autoresponders');

		$autodetails = array('list' => $listid);
		IEM::sessionSet('Autoresponders', $autodetails);

		$user = IEM::getCurrentUser();
		$perpage = $this->GetPerPage();

		$DisplayPage = $this->GetCurrentPage();
		$start = 0;
		if ($perpage != 'all') {
			$start = ($DisplayPage - 1) * $perpage;
		}

		$sortinfo = $this->GetSortDetails();

		$autoresponderapi = $this->GetApi();

		$NumberOfAutoresponders = $autoresponderapi->GetAutoresponders($listid, $sortinfo, true);
		$myautoresponders = $autoresponderapi->GetAutoresponders($listid, $sortinfo, false, $start, $perpage);

		$GLOBALS['SubAction'] = 'SubAction=Step2&list=' . $listid;
		$GLOBALS['Autoresponders_AddButton'] = $this->ParseTemplate('Autoresponder_Create_Button', true, false);

		$GLOBALS['List'] = $listid;

		$this->DisplayCronWarning();

		if ($NumberOfAutoresponders == 0) {
			$GLOBALS['Intro'] = GetLang('AutorespondersManage');
			if ($user->HasAccess('Autoresponders', 'Create')) {
				$GLOBALS['Message'] .= $this->PrintSuccess('NoAutoresponders', GetLang('AutoresponderCreate'));
			} else {
				$GLOBALS['Message'] .= $this->PrintSuccess('NoAutoresponders', GetLang('AutoresponderAssign'));
			}

			$this->ParseTemplate('Autoresponders_Manage_Empty');

			return;
		}

		if ($user->HasAccess('Autoresponders', 'Delete')) {
			$GLOBALS['Option_DeleteAutoresponder'] = '<option value="Delete">' . GetLang('DeleteAutoresponders') . '</option>';
		}

		if ($user->HasAccess('Autoresponders', 'Approve')) {
			$GLOBALS['Option_ActivateAutoresponder'] = '<option value="Approve">' . GetLang('ActivateAutoresponders') . '</option>';
			$GLOBALS['Option_ActivateAutoresponder'] .= '<option value="Disapprove">' . GetLang('DeactivateAutoresponders') . '</option>';
		}

		$GLOBALS['PAGE'] = 'Autoresponders&Action=Step2&list=' . $listid;

		$this->SetupPaging($NumberOfAutoresponders, $DisplayPage, $perpage);
		$GLOBALS['FormAction'] = 'Action=ProcessPaging&SubAction=Step2&list=' . $listid;
		$paging = $this->ParseTemplate('Paging', true, false);

		// reset the page for correct links for ordering.
		$GLOBALS['PAGE'] = 'Autoresponders&Action=Step2&list=' . $listid;

		$GLOBALS['list'] = $listid;

		$autoresponder_manage = $this->ParseTemplate('Autoresponders_Manage', true, false);

		$autoresponderdisplay = '';

		$max_email_size = (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024);

		foreach ($myautoresponders as $pos => $autoresponderdetails) {
			$autoresponderid = $autoresponderdetails['autoresponderid'];
			$GLOBALS['Name'] = htmlspecialchars($autoresponderdetails['name'], ENT_QUOTES, SENDSTUDIO_CHARSET);
			$GLOBALS['Created'] = $this->PrintDate($autoresponderdetails['createdate']);
			$GLOBALS['Format'] = GetLang('Format_' . $autoresponderapi->GetFormat($autoresponderdetails['format']));
			$GLOBALS['Owner'] = $autoresponderdetails['owner'];
			if ($autoresponderdetails['hoursaftersubscription'] < 1) {
				$GLOBALS['SentWhen'] = GetLang('Immediately');
			} else {
				if ($autoresponderdetails['hoursaftersubscription'] == 1) {
					$GLOBALS['SentWhen'] = GetLang('HoursAfter_One');
				} else {
					$GLOBALS['SentWhen'] = sprintf(GetLang('HoursAfter_Many'), $autoresponderdetails['hoursaftersubscription']);
				}
			}

			if ($autoresponderdetails['pause'] == 0) {
				$GLOBALS['AutoresponderAction']  = '<a href="index.php?Page=Autoresponders&Action=Pause&id=' . $autoresponderid . '&list=' . $listid . '">' . GetLang('Pause') . '</a>';
			} else {
				$GLOBALS['AutoresponderAction']  = '<a href="index.php?Page=Autoresponders&Action=Resume&id=' . $autoresponderid . '&list=' . $listid . '">' . GetLang('Resume') . '</a>';
			}

			$GLOBALS['AutoresponderAction']  .= '&nbsp;&nbsp;<a href="index.php?Page=Autoresponders&Action=View&id=' . $autoresponderid . '" target="_blank">' . GetLang('View') . '</a>';

			if ($user->HasAccess('Autoresponders', 'Edit')) {
				$GLOBALS['AutoresponderAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Autoresponders&Action=Edit&id=' . $autoresponderid . '&list=' . $listid . '">' . GetLang('Edit') . '</a>';
			} else {
				$GLOBALS['AutoresponderAction'] .= $this->DisabledItem('Edit');
			}

			if ($user->HasAccess('Autoresponders', 'Create')) {
				$GLOBALS['AutoresponderAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Autoresponders&Action=Copy&id=' . $autoresponderid . '&list=' . $listid . '">' . GetLang('Copy') . '</a>';
			} else {
				$GLOBALS['AutoresponderAction'] .= $this->DisabledItem('Copy');
			}

			if ($user->HasAccess('Autoresponders', 'Delete')) {
				$GLOBALS['AutoresponderAction'] .= '&nbsp;&nbsp;<a href="javascript:ConfirmDelete(' . $autoresponderid . ');">' . GetLang('Delete') . '</a>';
			} else {
				$GLOBALS['AutoresponderAction'] .= $this->DisabledItem('Delete');
			}

			if ($autoresponderdetails['active'] > 0) {
				$statusaction = 'deactivate';
				$activeicon = 'tick';
				$activetitle = GetLang('Autoresponder_Title_Disable');
			} else {
				$statusaction = 'activate';
				$activeicon = 'cross';
				$activetitle = GetLang('Autoresponder_Title_Enable');
			}
			$GLOBALS['id'] = $autoresponderid;

			$size_prob_found = false;
			if ($max_email_size > 0) {
				if ($autoresponderdetails['autorespondersize'] > $max_email_size) {
					$size_prob_found = true;
					$GLOBALS['ActiveAction'] = '<span title="' . GetLang('Autoresponder_Title_Disable_Too_Big') . '"><img src="images/cross.gif" border="0" alt="' . GetLang('Autoresponder_Title_Disable_Too_Big') . '" onclick="javascript: alert(\'' . GetLang('Autoresponder_Title_Disable_Too_Big_Alert') . '\');"></span>';
				}
			}

			if (!$size_prob_found) {
				if ($user->HasAccess('Autoresponders', 'Approve')) {
					$GLOBALS['ActiveAction'] = '<a href="index.php?Page=Autoresponders&Action=' . $statusaction . '&id=' . $autoresponderid . '&list=' . $listid . '" title="' . $activetitle . '"><img src="images/' . $activeicon . '.gif" border="0" alt="' . $activetitle . '"></a>';
				} else {
					$GLOBALS['ActiveAction'] = '<span title="' . $activetitle . '"><img src="images/' . $activeicon . '.gif" border="0" alt="' . $activetitle . '"></span>';
				}
			}

			$autoresponderdisplay .= $this->ParseTemplate('Autoresponders_Manage_Row', true, false);
		}
		$autoresponder_manage = str_replace('%%TPL_Autoresponders_Manage_Row%%', $autoresponderdisplay, $autoresponder_manage);
		$autoresponder_manage = str_replace('%%TPL_Paging%%', $paging, $autoresponder_manage);
		$autoresponder_manage = str_replace('%%TPL_Paging_Bottom%%', $GLOBALS['PagingBottom'], $autoresponder_manage);

		echo $autoresponder_manage;
	}
Exemplo n.º 24
0
	/**
	* Process
	* This handles working out what stage you are up to and so on with workflow.
	* Handles editing of schedules, pausing, resuming and deleting of schedules.
	* Deleting a scheduled event (especially) needs to update statistics if there are any emails left over in the queue.
	*
	* @see GetUser
	* @see User_API::HasAccess
	* @see SENDSTUDIO_CRON_ENABLED
	* @see GetApi
	* @see Jobs_API::PauseJob
	* @see Jobs_API::ResumeJob
	* @see Jobs_API::LoadJob
	* @see ManageSchedules
	* @see CheckJob
	* @see AdjustTime
	*/
	function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : null;
		if (!SENDSTUDIO_CRON_SEND) {
			$popup = (in_array($action, $this->PopupWindows)) ? true : false;
			$this->PrintHeader($popup);
			$GLOBALS['Error'] = GetLang('CronNotEnabled');
			$this->ParseTemplate('ErrorMsg');
			$this->PrintFooter();
			return;
		}
		
		$user = GetUser();
		$access = $user->HasAccess('Newsletters', 'Send');

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

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

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

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

		$approve_job = IEM::sessionGet('ApproveJob');
		if ($approve_job) {
			if (isset($_GET['A'])) {
				$jobapi->ApproveJob($approve_job, $user->Get('userid'));
				$GLOBALS['Message'] = $this->PrintSuccess('JobScheduledOK');
				IEM::sessionRemove('ApproveJob');
			}
		}

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

		switch ($action) {
			/**
			 * These methods are all called the same thing:
			 * 'ActionJob'
			 * The 'action' has an upper-case first letter
			 * then 'Job' has the same.
			 * They also all just take the jobid as the argument.
			 */
			case 'approve':
			case 'edit':
			case 'pause':
			case 'resend':
			case 'resume':
			case 'update':
				if (!$this->CanAccessJobs($jobid)) {
					$this->DenyAccess();
					return false;
				}

				$method = ucwords($action) . 'Job';
				call_user_func(array($this, $method), $jobid);
			break;

			case 'delete':
				$jobids = array();

				if (isset($_POST['jobs'])) {
					$jobids = $_POST['jobs'];
				} else {
					$jobids[] = $jobid;
				}

				if (!$this->CanAccessJobs($jobids)) {
					$this->DenyAccess();
					return false;
				}

				$this->DeleteJobs($jobids);

			break;

			default:
				$this->ManageSchedules();
		}
		$this->PrintFooter($popup);
	}
Exemplo n.º 25
0
    /**
     * ManageNewsletters
     * Prints out the newsletters for management. Depending on your access levels you can edit, delete, send, schedule and so on.
     *
     * @see GetPerPage
     * @see GetSortDetails
     * @see GetApi
     * @see User_API::Admin
     * @see Newsletter_API::GetNewsletters
     * @see SetupPaging
     * @see PrintDate
     * @see User_API::HasWriteAccess
     * @see Jobs_API::FindJob
     *
     * @return Void Doesn't return anything, just prints out the results and that's it.
     *
     * @uses EventData_IEM_NEWSLETTERS_MANAGENEWSLETTERS
     */
    function ManageNewsletters() {        
        $user = GetUser();
        
        $remove_temp_dir = IEM::sessionGet('Newsletters_creation['.$user->Get('userid').']');
        IEM::sessionSet('Newsletters_creation['.$user->Get('userid').']',null);
        IEM::sessionRemove('Newsletter_creation['.$user->Get('userid').']');
        if(!empty($remove_temp_dir)){
            $d_path = TEMP_DIRECTORY . DIRECTORY_SEPARATOR . "newsletters" . DIRECTORY_SEPARATOR . $user->Get('userid')."_tmp";
            if(is_dir($d_path)){remove_directory($d_path);}
            $GLOBALS['Message'] = $remove_temp_dir;    
        }

        $edit_msg = IEM::sessionGet('Newsletters_editing['.$user->Get('userid').']');
        IEM::sessionSet('Newsletters_editing['.$user->Get('userid').']',null);
        IEM::sessionRemove('Newsletters_editing['.$user->Get('userid').']');
        if(!empty($edit_msg)){
            $GLOBALS['Message'] = $edit_msg;    
        }        

        $delete_msg = IEM::sessionGet('Newsletters_deletion['.$user->Get('userid').']');
        IEM::sessionSet('Newsletters_deletion['.$user->Get('userid').']',null);
        IEM::sessionRemove('Newsletters_deletion['.$user->Get('userid').']');
        if(!empty($delete_msg)){
            $GLOBALS['Message'] = $delete_msg;    
        }         
        $perpage = $this->GetPerPage();

        $DisplayPage = $this->GetCurrentPage();
        $start = 0;
        if ($perpage != 'all') {
            $start = ($DisplayPage - 1) * $perpage;
        }

        $sortinfo = $this->GetSortDetails();

        $newsletterapi = $this->GetApi();

        $newsletterowner = ($user->Admin() || $user->AdminType() == 'n') ? 0 : $user->userid;
        $NumberOfNewsletters = $newsletterapi->GetNewsletters($newsletterowner, $sortinfo, true);
        $mynewsletters = $newsletterapi->GetNewsletters($newsletterowner, $sortinfo, false, $start, $perpage, true);

        if ($user->HasAccess('Newsletters', 'Create')) {
            $GLOBALS['Newsletters_AddButton'] = $this->ParseTemplate('Newsletter_Create_Button', true, false);
            $GLOBALS['Newsletters_Heading'] = GetLang('Help_NewslettersManage_HasAccess');
        }

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

        /**
         * Trigger event
         */
        $tempEventData = new EventData_IEM_NEWSLETTERS_MANAGENEWSLETTERS();
        $tempEventData->displaymessage = &$GLOBALS['Message'];
        $tempEventData->trigger();

        unset($tempEventData);
        /**
         * -----
         */
        if ($NumberOfNewsletters == 0) {
            if ($user->HasAccess('Newsletters', 'Create')) {
                $GLOBALS['Message'] .= $this->PrintSuccess('NoNewsletters', GetLang('NoNewsletters_HasAccess'));
            } else {
                $GLOBALS['Message'] .= $this->PrintSuccess('NoNewsletters', '');
            }
            $this->ParseTemplate('Newsletters_Manage_Empty');
            return;
        }

        $this->SetupPaging($NumberOfNewsletters, $DisplayPage, $perpage);
        $GLOBALS['FormAction'] = 'Action=ProcessPaging';
        $paging = $this->ParseTemplate('Paging', true, false);

        if ($user->HasAccess('Newsletters', 'Delete')) {
            $GLOBALS['Option_DeleteNewsletter'] = '<option value="Delete">' . GetLang('Delete') . '</option>';
        }

        if ($user->HasAccess('Newsletters', 'Approve')) {
            $GLOBALS['Option_ActivateNewsletter'] = '<option value="Approve">' . GetLang('ApproveNewsletters') . '</option>';
            $GLOBALS['Option_ActivateNewsletter'] .= '<option value="Disapprove">' . GetLang('DisapproveNewsletters') . '</option>';
            $GLOBALS['Option_ArchiveNewsletter'] = '<option value="Archive">' . GetLang('ArchiveNewsletters') . '</option>';
            $GLOBALS['Option_ArchiveNewsletter'] .= '<option value="Unarchive">' . GetLang('UnarchiveNewsletters') . '</option>';
        }

        $newsletter_manage = $this->ParseTemplate('Newsletters_Manage', true, false);

        $newsletterdisplay = '';

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

        foreach ($mynewsletters as $pos => $newsletterdetails) {
            $newsletterid = $newsletterdetails['newsletterid'];
            $GLOBALS['Name'] = htmlspecialchars($newsletterdetails['name'], ENT_QUOTES, SENDSTUDIO_CHARSET);
            $GLOBALS['Short_Name'] = htmlspecialchars($this->TruncateName($newsletterdetails['name'], 34), ENT_QUOTES, SENDSTUDIO_CHARSET);

            $GLOBALS['Created'] = $this->PrintDate($newsletterdetails['createdate']);
            $GLOBALS['Format'] = GetLang('Format_' . $newsletterapi->GetFormat($newsletterdetails['format']));
            $GLOBALS['Owner'] = $newsletterdetails['owner'];

            $GLOBALS['Subject'] = htmlspecialchars($newsletterdetails['subject'], ENT_QUOTES, SENDSTUDIO_CHARSET);
            $GLOBALS['Short_Subject'] = htmlspecialchars($this->TruncateName($newsletterdetails['subject'], 37), ENT_QUOTES, SENDSTUDIO_CHARSET);

            $GLOBALS['id'] = $newsletterid;

            $GLOBALS['NewsletterIcon'] = '<img src="images/m_newsletters.gif">';

            $GLOBALS['NewsletterAction'] = '<a href="index.php?Page=Newsletters&Action=View&id=' . $newsletterid . '" target="_blank">' . GetLang('View') . '</a>';

            $send_inprogress = false;
            $send_fully_completed = true;

            $job = false;
            if ($newsletterdetails['jobid'] > 0) {
                $job = $jobapi->LoadJob($newsletterdetails['jobid']);
            }

            $GLOBALS['LastSentTip'] = $GLOBALS['LastSentTip_Extra'] = $GLOBALS['Job'] = '';

            if ($newsletterdetails['starttime'] > 0) {
                $GLOBALS['LastSent'] = $this->PrintDate($newsletterdetails['starttime']);

                $GLOBALS['TipName'] = $this->GetRandomId();

                if ($newsletterdetails['finishtime'] > 0) {
                    $GLOBALS['LastSentTip'] = sprintf(GetLang('AlreadySentTo'), $this->FormatNumber($newsletterdetails['total_recipients']), $this->FormatNumber($newsletterdetails['sendsize']));
                    if ($newsletterdetails['total_recipients'] < $newsletterdetails['sendsize'] && $job) {
                        $send_fully_completed = false;
                        $GLOBALS['ResendTipName'] = $this->GetRandomId();
                        $GLOBALS['Job'] = $job['jobid'];
                        if ($job['resendcount'] < SENDSTUDIO_RESEND_MAXIMUM) {
                            $GLOBALS['NewsletterIcon'] = $this->ParseTemplate('Newsletters_Send_Resend_Tip', true, false);
                            $GLOBALS['LastSentTip_Extra'] = GetLang('AlreadySentTo_Partial');
                        }
                    }
                } else {
                    $GLOBALS['LastSentTip'] = sprintf(GetLang('AlreadySentTo_SoFar'), $this->FormatNumber($newsletterdetails['total_recipients']), $this->FormatNumber($newsletterdetails['sendsize']));
                }

                $already_sent_tip = $this->ParseTemplate('Newsletters_Send_Tip', true, false);

                $GLOBALS['LastSent'] = $already_sent_tip;
            } else {
                $GLOBALS['LastSent'] = GetLang('NotSent');
            }

            if ($user->HasAccess('Newsletters', 'Send')) {
                if ($newsletterdetails['active']) {
                    if (!$job || empty($job)) {
                        $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Send&id=' . $newsletterid . '">' . GetLang('Send') . '</a>';
                    } else {
                        $jobstate = $jobapi->GetJobStatus($job['jobstatus']);
                        switch ($job['jobstatus']) {
                            case 'i':
                                $send_inprogress = true;
                                if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
                                    $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Schedule">' . $jobstate . '</a>';
                                } else {
                                    $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Send&Action=PauseSend&Job=' . $job['jobid'] . '">' . $jobstate . '</a>';
                                }
                                break;
                            case 'p':
                                if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
                                    $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Schedule">' . $jobstate . '</a>';
                                } else {
                                    $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Send&Action=ResumeSend&Job=' . $job['jobid'] . '">' . $jobstate . '</a>';
                                }
                                break;
                            case 'w':
                                // this is only applicable for scheduled newsletters (waiting to send).
                                $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Schedule">' . GetLang('Waiting') . '</a>';
                                break;
                            default:
                                if ($send_fully_completed) {
                                    $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Send&id=' . $newsletterid . '">' . GetLang('Send') . '</a>';
                                } else {
                                    if ($job['resendcount'] < SENDSTUDIO_RESEND_MAXIMUM) {
                                        $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Send&Action=Resend&Job=' . $job['jobid'] . '">' . GetLang('Resend') . '</a>';
                                    } else {
                                        $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Resend', 'Newsletter_Send_Disabled_Resend_Maximum');
                                    }
                                }
                        }
                    }
                } else {
                    $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Send', 'Newsletter_Send_Disabled_Inactive');
                }
            } else {
                $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Send');
            }

            if ($user->HasAccess('Newsletters', 'Edit')) {
                if (!$send_inprogress) {
                    $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Newsletters&Action=Edit&id=' . $newsletterid . '">' . GetLang('Edit') . '</a>';
                } else {
                    $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Edit', 'Newsletter_Edit_Disabled_SendInProgress');
                }
            } else {
                $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Edit');
            }

            if ($user->HasAccess('Newsletters', 'Create')) {
                $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="index.php?Page=Newsletters&Action=Copy&id=' . $newsletterid . '">' . GetLang('Copy') . '</a>';
            } else {
                $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Copy');
            }

            if ($user->HasAccess('Newsletters', 'Delete')) {
                if (!$send_inprogress) {
                    $GLOBALS['NewsletterAction'] .= '&nbsp;&nbsp;<a href="javascript: ConfirmDelete(' . $newsletterid . ');">' . GetLang('Delete') . '</a>';
                } else {
                    $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Delete', 'Newsletter_Delete_Disabled_SendInProgress');
                }
            } else {
                $GLOBALS['NewsletterAction'] .= $this->DisabledItem('Delete');
            }

            if ($newsletterdetails['active'] > 0) {
                $statusaction = 'deactivate';
                $activeicon = 'tick';
                if ($user->HasAccess('Newsletters', 'Approve')) {
                    $activetitle = GetLang('Newsletter_Title_Disable');
                } else {
                    $activetitle = GetLang('NoAccess');
                }
            } else {
                $statusaction = 'activate';
                $activeicon = 'cross';
                if ($user->HasAccess('Newsletters', 'Approve')) {
                    $activetitle = GetLang('Newsletter_Title_Enable');
                } else {
                    $activetitle = GetLang('NoAccess');
                }
            }

            if ($user->HasAccess('Newsletters', 'Approve')) {
                if (!$send_inprogress) {
                    $GLOBALS['ActiveAction'] = '<a href="index.php?Page=Newsletters&Action=' . $statusaction . '&id=' . $newsletterid . '" title="' . $activetitle . '"><img src="images/' . $activeicon . '.gif" border="0"></a>';
                } else {
                    $activetitle = GetLang('Newsletter_ChangeActive_Disabled_SendInProgress');
                    $GLOBALS['ActiveAction'] = '<span title="' . $activetitle . '"><img src="images/' . $activeicon . '.gif" border="0"></span>';
                }
            } else {
                $GLOBALS['ActiveAction'] = '<span title="' . $activetitle . '"><img src="images/' . $activeicon . '.gif" border="0"></span>';
            }

            if ($newsletterdetails['archive'] > 0) {
                $statusaction = 'deactivatearchive';
                $activeicon = 'tick';
                $activetitle = GetLang('Newsletter_Title_Archive_Disable');
            } else {
                $statusaction = 'activatearchive';
                $activeicon = 'cross';
                $activetitle = GetLang('Newsletter_Title_Archive_Enable');
            }

            if ($user->HasAccess('Newsletters', 'Approve')) {
                $GLOBALS['ArchiveAction'] = '<a href="index.php?Page=Newsletters&Action=' . $statusaction . '&id=' . $newsletterid . '" title="' . $activetitle . '"><img src="images/' . $activeicon . '.gif" border="0"></a>';
            } else {
                $GLOBALS['ArchiveAction'] = '<span title="' . $activetitle . '"><img src="images/' . $activeicon . '.gif" border="0"></span>';
            }

            $newsletterdisplay .= $this->ParseTemplate('Newsletters_Manage_Row', true, false);
        }
        $newsletter_manage = str_replace('%%TPL_Newsletters_Manage_Row%%', $newsletterdisplay, $newsletter_manage);
        $newsletter_manage = str_replace('%%TPL_Paging%%', $paging, $newsletter_manage);
        $newsletter_manage = str_replace('%%TPL_Paging_Bottom%%', $GLOBALS['PagingBottom'], $newsletter_manage);

        echo $newsletter_manage;
    }
Exemplo n.º 26
0
	/**
	* ChooseList
	* This prints out the select box which makes you choose a list (to start any subscriber process).
	* If there is only one list, it will automatically redirect you to that particular list (depending on which area you're looking for).
	* Otherwise, it prints out the appropriate template for the area you're working with.
	*
	* @param String $action The area you're working with. This can be manage, export, import, banned and so on.
	* @param String $subaction Which step you're up to in the process.
	*
	* @see User_API::GetLists
	* @see User_API::CanCreateList
	*
	* @return Void Prints out the appropriate template, doesn't return anything.
	*/
	function ChooseList($action='Manage', $subaction=null)
	{
		$action = strtolower($action);
		$user = GetUser();
		$lists = $user->GetLists();

		$listids = array_keys($lists);

		if (sizeof($listids) < 1) {
			switch ($action) {
				case 'banned':
					if ($subaction == 'add') {
						$extra_message = GetLang('Banned_Add_NoList_Message');
					} else {
						$extra_message = GetLang('Banned_Manage_NoList_Message');
					}
					$GLOBALS['Intro_Help'] = GetLang('Help_SubscribersManage');
				break;

				case 'import':
					$extra_message = GetLang('Import_Add_NoList_Message');
					$GLOBALS['Intro_Help'] = GetLang('Help_SubscribersManage');
				break;

				case 'export':
					$extra_message = GetLang('Export_Add_NoList_Message');
					$GLOBALS['Intro_Help'] = GetLang('Help_SubscribersManage');
				break;

				case 'remove':
					$extra_message = GetLang('Remove_NoList_Message');
					$GLOBALS['Intro_Help'] = GetLang('Help_SubscribersManage');
				break;

				case 'add':
					$extra_message = GetLang('Add_NoList_Message');
					$GLOBALS['Intro_Help'] = GetLang('Help_SubscribersManage');
				break;

				default:
					$extra_message = GetLang('View_NoList_Message');
					$GLOBALS['Intro_Help'] = GetLang('Help_SubscribersManage');
			}

			$GLOBALS['Intro'] = GetLang('Subscribers_' . ucwords($action));
			$GLOBALS['Lists_AddButton'] = '';

			if ($user->CanCreateList() === true) {
				$GLOBALS['Message'] = $this->PrintSuccess('Subscriber_NoLists', $extra_message, GetLang('ListCreate'));
				$GLOBALS['Lists_AddButton'] = $this->ParseTemplate('List_Create_Button', true, false);
			} else {
				$GLOBALS['Message'] = $this->PrintSuccess('Subscriber_NoLists', $extra_message, GetLang('ListAssign'));
			}
			$this->ParseTemplate('Subscribers_No_Lists');
			return;
		}

		if ($listname = IEM::sessionGet('AddSubscriberMessage')) {
			$GLOBALS['Message'] = $this->PrintSuccess('SubscriberAddSuccessfulList', htmlspecialchars($listname, ENT_QUOTES, SENDSTUDIO_CHARSET));
			IEM::sessionRemove('AddSubscriberMessage');
		}

		if ($emptybannedmsg = IEM::sessionGet('EmptyBannedSubscriberMessage')) {
			$GLOBALS['Message'] = $this->PrintSuccess('SubscriberBanListEmpty', htmlspecialchars($emptybannedmsg, ENT_QUOTES, SENDSTUDIO_CHARSET));
			IEM::sessionRemove('EmptyBannedSubscriberMessage');
		}

		if ($bannedmsg = IEM::sessionGet('DeleteBannedSubscriberMessage')) {
			$GLOBALS['Message'] = $bannedmsg;
			IEM::sessionRemove('DeleteBannedSubscriberMessage');
		}

		$sortedlist = array();

		if ($action == 'banned') {
			$banned_list = $user->GetBannedLists($listids);

			$banned_listids = array_keys($banned_list);

			if ($user->HasAccess('Lists', 'Global')) {
				$sortedlist['global'] = array('name' => GetLang('Subscribers_GlobalBan'));
			}

			$sortedlist += $lists;

			foreach ($sortedlist as $name => $details) {
				$check_name = $name;
				if ($name == 'global') {
					$check_name = 'g';
				}
				$sortedlist[$name]['bancount'] = 0;
				if (in_array($check_name, $banned_listids)) {
					$sortedlist[$name]['bancount'] = $banned_list[$check_name];
				}
			}
		}

		if ($action != 'banned') {
			if ($action == 'manage' || $action == 'export') {
				$sortedlist = array('any' => array('name' => GetLang('AnyList')));
			}
			$sortedlist += $lists;
		}

		$selectlist = '';
		foreach ($sortedlist as $listid => $listdetails) {
			$subscriber_count = '';
			if (isset($listdetails['bancount'])) {
				if ($listdetails['bancount'] == 1) {
					$subscriber_count = GetLang('Ban_Count_One');
				} else {
					$subscriber_count = sprintf(GetLang('Ban_Count_Many'), $this->FormatNumber($listdetails['bancount']));
				}
			} else {
				if (isset($listdetails['subscribecount'])) {
					if ($listdetails['subscribecount'] == 1) {
						$subscriber_count = GetLang('Subscriber_Count_One');
					} else {
						$subscriber_count = sprintf(GetLang('Subscriber_Count_Many'), $this->FormatNumber($listdetails['subscribecount']));
					}
				}
			}

			if ($listid == 'any') {
				$sel = 'selected';
			} else {
				$sel = '';
			}

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

		$tempCount = count($sortedlist);
		if ($tempCount <= 10) {
			if ($tempCount < 3) {
				$tempCount = 3;
			}
			$GLOBALS['SelectListStyle'] = 'height: ' . ($tempCount * 25) . 'px;';
		}

		$GLOBALS['DisplaySegmentOption'] = 'none';
		if (in_array($action, array('manage', 'send')) && $user->HasAccess('Segments', 'View')) {
			$selectSegment = '';
			$segments = $user->GetSegmentList();
			$segmentAPI = $this->GetApi('Segment');
			foreach ($segments as $segmentid => $segmentdetails) {
				$tempCount = $segmentAPI->GetSubscribersCount($segmentdetails['segmentid']);

				if ($tempCount == 1) {
					$tempCount = GetLang('Subscriber_Count_One');
				} else {
					$tempCount = sprintf(GetLang('Subscriber_Count_Many'), $this->FormatNumber($tempCount));
				}

				$selectSegment .= 	'<option value="' . $segmentid . '">'
									. htmlspecialchars($segmentdetails['segmentname'], ENT_QUOTES, SENDSTUDIO_CHARSET)
									. $tempCount
									. '</option>';
			}
			$GLOBALS['SelectSegment'] = $selectSegment;

			$GLOBALS['DisplaySegmentOption'] = '';
		}

		switch ($action) {
			case 'search':
				$this->ParseTemplate('Subscriber_Search_Step1');
			break;
			case 'manage':
				$this->ParseTemplate('Subscriber_Manage_Step1');
			break;
			case 'add':
				$this->ParseTemplate('Subscribers_Add_Step1');
			break;
			case 'remove':
				$this->ParseTemplate('Subscribers_Remove_Step1');
			break;
			case 'import':
				$this->ParseTemplate('Subscribers_Import_Step1');
			break;
			case 'export':
				$this->ParseTemplate('Subscribers_Export_Step1');
			break;
			case 'banned':
				$this->ParseTemplate('Subscribers_Banned_Step1');
			break;
		}
	}