Ejemplo n.º 1
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");
                            IEM::sessionSet('Newsletters_editing['.$user->Get('userid').']',$GLOBALS['Message']);
                            IEM::redirectTo("Newsletters",array("Action" => "Manage"));
                        }
                        
                        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':
                        IEM::sessionSet('Newsletters_creation['.$user->Get('userid').']', true);
                        $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);
                            IEM::sessionRemove('Newsletters_creation['.$user->Get('userid').']');
                            $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);
                            IEM::sessionRemove('Newsletter_creation['.$user->Get('userid').']');                                                        
                            $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('NewsletterCreated', 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");
                            IEM::sessionRemove('Newsletters_creation['.$user->Get('userid').']');
                            IEM::sessionSet('Newsletters_creation['.$user->Get('userid').']',$GLOBALS['Message']);
                            IEM::redirectTo("Newsletters",array("Action" => "Manage"));
                        }
                        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);
        }
    }
Ejemplo n.º 2
0
	public function page_saveRecord()
	{
		$record = IEM::requestGetPOST('record', array());

        $record['groupname'] = htmlspecialchars($record['groupname']);

		$created = ((IEM::ifsetor($record['groupid'], 0, 'intval') == 0) ? true : false);

		/*
		 * Transform the permission so that it will be recognized by the API
		 */

		$permissions = IEM::ifsetor($record['permissions'], array());


		$new_permissions = array();
		if (!is_array($permissions)) {
			$permissions = array();
		}
		if (!empty($permissions)) {
			foreach ($permissions as $each) {
				$temp = explode('.', $each);

				// This can only handle 2 level permissions,
				// ie. autoresponders.create, autoresponders.delete, autoresponders.edit
				// will become $permissions['autoresponders'] = array('create', 'delete', 'edit');
				if (count($temp) != 2) {
					continue;
				}

				if (!isset($new_permissions[$temp[0]])) {
					$new_permissions[$temp[0]] = array();
				}

				$new_permissions[$temp[0]][] = $temp[1];
			}
		}

		$record['permissions'] = $new_permissions;

		if (empty($record)) {
			return $this->page_createGroup($record);
		}

		// Check if "Request Token" matches
		// This tries to prevent CSRF
		$token = IEM::sessionGet('UsersGroups_Editor_RequestToken', false);
		if (!$token || $token != IEM::requestGetPOST('requestToken', false)) {
			return $this->page_createGroup($record);
		}

		$status = API_USERGROUPS::saveRecord($record);
		if (!$status) {
			FlashMessage(GetLang('UsersGroups_From_Error_CannotSave'), SS_FLASH_MSG_ERROR);
			return $this->printEditor($record);
		}

		$messageVariable = 'UsersGroups_From_Success_Saved';
		if ($created) {
			$messageVariable = 'UsersGroups_From_Success_Created';
		}

		FlashMessage(GetLang($messageVariable), SS_FLASH_MSG_SUCCESS, IEM::urlFor('UsersGroups'));
	}
	/**
	* Process
	* Takes the appropriate action based on the action and user permissions
	*
	* @see GetUser
	* @see User_API::HasAccess
	* @see PrintHeader
	* @see PrintFooter
	*
	* @return Void Doesn't return anything. Takes the appropriate action.
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

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

		$secondary_actions = array('step2', 'sendpreview', 'view', 'processpaging', 'activate', 'deactivate', 'pause', 'resume', 'change', 'checkspam', 'viewcompatibility');
		if (in_array($action, $secondary_actions)) {
			$access = $user->HasAccess('Autoresponders');
		} else {
			$access = $user->HasAccess('Autoresponders', $action);
		}

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

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

		/**
		 * Check user permission to see whether or not they have access to the autoresponder
		 */
			$tempAPI = null;
			$tempCheckActions = array('activate', 'deactivate', 'copy', 'change', 'pause', 'resume', 'delete', 'step2', 'sendpreview', 'view', 'edit');
			$tempID = null;

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

			if (!is_null($tempID)) {
				$_GET['id'] = $tempID;
				$_POST['autoresponders'] = $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 ($action == 'processpaging') {
			$this->SetPerPage($_GET['PerPageDisplay']);
			$action = 'step2';
		}


		switch ($action) {
			case 'pause':
			case 'resume': 
				$autoresponderAPI = $this->GetApi();
				$autoresponderID = IEM::requestGetGET('id', 0, 'intval');
				$listID = IEM::requestGetGET('list', 0, 'intval');

				if ($action == 'pause') {
					$autoresponderAPI->PauseAutoresponder($autoresponderID);
				} else {
					$autoresponderAPI->ResumeAutoresponder($autoresponderID);
				}

				$this->ManageAutoresponders($listID);
			break;

			case 'viewcompatibility':
				$auto_info = IEM::sessionGet('Autoresponders');

				$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'] = $auto_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':
				$access = $user->HasAccess('Autoresponders', 'Approve');
				if (!$access) {
					$this->DenyAccess();
					break;
				}

				$id = (int)$_GET['id'];
				$autoapi = $this->GetApi();
				$autoapi->Load($id);
				if ($action == 'activate') {
					$prob_found = false;
					$max_size = (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024);
					if ($max_size > 0) {
						if ($autoapi->Get('autorespondersize') > $max_size) {
							$prob_found = true;
							if ($autoapi->Get('embedimages')) {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_Embed';
							} else {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_No_Embed';
							}
							$GLOBALS['Error'] = sprintf(GetLang($error_langvar), $this->EasySize($max_size, 0));
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						}
					}
					if (!$prob_found) {
						$allow_attachments = $this->CheckForAttachments($id, 'autoresponders');
						if ($allow_attachments) {
							$autoapi->Set('active', $user->Get('userid'));
							$GLOBALS['Message'] = $this->PrintSuccess('AutoresponderActivatedSuccessfully');
						} else {
							$GLOBALS['Error'] = GetLang('AutoresponderActivateFailed_HasAttachments');
							$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						}
					}
				} else {
					$autoapi->Set('active', 0);
					$GLOBALS['Message'] = $this->PrintSuccess('AutoresponderDeactivatedSuccessfully');
				}
				$autoapi->Save();

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

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

			case 'copy':
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$api = $this->GetApi();
				list($result, $files_copied) = $api->Copy($id);
				if (!$result) {
					$GLOBALS['Error'] = GetLang('AutoresponderCopyFail');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				} else {
					$api->Set('active', 0);
					$api->Save();
					$GLOBALS['Message'] = $this->PrintSuccess('AutoresponderCopySuccess');
					$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled');
					if (!$files_copied) {
						$GLOBALS['Error'] = GetLang('AutoresponderFilesCopyFail');
						$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
					}
				}
				if (isset($_GET['list'])) {
					$listid = (int)$_GET['list'];
				}

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

			case 'change':
				$subaction = strtolower($_POST['ChangeType']);
				$autolist = $_POST['autoresponders'];

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

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

			case 'delete':
				$id = (int)$_GET['id'];
				$autolist = array($id);
				$access = $user->HasAccess('Autoresponders', 'Delete');
				if ($access) {
					$this->DeleteAutoresponders($autolist);
				} else {
					$this->DenyAccess();
				}
			break;

			case 'step2':
				$listid = 0;
				if (isset($_GET['list'])) {
					$listid = (int)$_GET['list'];
				}

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

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

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

			case 'view':
				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				$type = strtolower(get_class($this));
				$autoresponderapi = $this->GetApi();
				if (!$autoresponderapi->Load($id)) {
					break;
				}

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

				$details = array();
				$details['htmlcontent'] = $autoresponderapi->GetBody('HTML');
				$details['textcontent'] = $autoresponderapi->GetBody('Text');
				$details['format'] = $autoresponderapi->format;
				$this->PreviewWindow($details);
			break;

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

				switch ($subaction) {
					case 'save':
					case 'complete':
						$user = IEM::getCurrentUser();
						$session_autoresponder = IEM::sessionGet('Autoresponders');

						$listid = $session_autoresponder['list'];

						if (!$session_autoresponder || !isset($session_autoresponder['autoresponderid'])) {
							$this->ManageAutoresponders($listid);
							break;
						}

						$text_unsubscribelink_found = true;
						$html_unsubscribelink_found = true;

						$id = $session_autoresponder['autoresponderid'];

						$autoapi = $this->GetApi();
						$autoapi->Load($id);

						$autoapi->Set('listid', $listid);

						if (isset($_POST['TextContent'])) {
							$textcontent = $_POST['TextContent'];
							$autoapi->SetBody('Text', $textcontent);
							$text_unsubscribelink_found = $this->CheckForUnsubscribeLink($textcontent, 'text');
							$session_autoresponder['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('UnableToUpdateAutoresponder');
								$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
								$this->EditAutoresponderStep4($id);
								break;
							}

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

						if (isset($_POST['subject'])) {
							$autoapi->Set('subject', $_POST['subject']);
						}

						foreach (array('name', 'format', 'searchcriteria', 'sendfromname', 'sendfromemail', 'replytoemail', 'bounceemail', 'tracklinks', 'trackopens', 'multipart', 'embedimages', 'hoursaftersubscription', 'charset', 'includeexisting', 'to_firstname', 'to_lastname') as $p => $area) {
							$autoapi->Set($area, $session_autoresponder[$area]);
						}

						$autoapi->Set('active', 0);

						$dest = strtolower(get_class($this));

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

						if ($movefiles_result) {
							if (isset($textcontent)) {
								$textcontent = $this->ConvertContent($textcontent, $dest, $id);
								$autoapi->SetBody('Text', $textcontent);
							}
							if (isset($htmlcontent)) {
								$htmlcontent = $this->ConvertContent($htmlcontent, $dest, $id);
								$autoapi->SetBody('HTML', $htmlcontent);
							}
						}

						// 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['AttachmentError'] = $attachments_status_msg;
								$GLOBALS['Error'] = $attachments_status_msg;
								$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
							}
						}

						list($autoresponder_size, $autoresponder_img_warnings) = $this->GetSize($session_autoresponder);
						$GLOBALS['Message'] .= $this->PrintSuccess('AutoresponderUpdated', sprintf(GetLang('Autoresponder_Size_Approximate'), $this->EasySize($autoresponder_size)));
						$max_size = (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024);

						if (SENDSTUDIO_EMAILSIZE_WARNING > 0) {
							$warning_size = SENDSTUDIO_EMAILSIZE_WARNING * 1024;
							if ($autoresponder_size > $warning_size && ($max_size > 0 && $autoresponder_size < $max_size)) {
								if ($session_autoresponder['embedimages']) {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_Embed';
								} else {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_No_Embed';
								}
								$GLOBALS['Message'] .= $this->PrintWarning($warning_langvar, $this->EasySize($warning_size));
							}
						}

						if ($max_size > 0 && $autoresponder_size >= $max_size) {
							if ($session_autoresponder['embedimages']) {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_Embed';
							} else {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_No_Embed';
							}
							$GLOBALS['Error'] = sprintf(GetLang($error_langvar), $this->EasySize($max_size, 0));

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

						$autoapi->Set('autorespondersize', $autoresponder_size);

						$result = $autoapi->Save();

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

						if ($autoresponder_img_warnings) {
							if ($session_autoresponder['embedimages']) {
								$warning_var = 'UnableToLoadImage_Autoresponder_List_Embed';
							} else {
								$warning_var = 'UnableToLoadImage_Autoresponder_List';
							}
							$GLOBALS['Message'] .= $this->PrintWarning($warning_var, $autoresponder_img_warnings);
						}

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

						if (!$text_unsubscribelink_found) {
							$GLOBALS['Message'] .= $this->PrintWarning('NoUnsubscribeLinkInTextContent');
						}
						
                        if(is_dir(TEMP_DIRECTORY . "/autoresponders/".$user->userid."_tmp")){remove_directory(TEMP_DIRECTORY . "/autoresponders/".$user->userid."_tmp");}


						if ($subaction == 'save') {
							$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled_Save');

							$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);

							$this->EditAutoresponderStep4($id);
							break;
						}

						$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled');

						$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);

						$this->ManageAutoresponders($listid);

					break;

					case 'step4':
						$sessionauto = IEM::sessionGet('Autoresponders');

						$sessionauto['sendfromname'] = $_POST['sendfromname'];
						$sessionauto['sendfromemail'] = $_POST['sendfromemail'];
						$sessionauto['replytoemail'] = $_POST['replytoemail'];
						$sessionauto['bounceemail'] = $_POST['bounceemail'];

						$sessionauto['charset'] = $_POST['charset'];

						$sessionauto['format'] = $_POST['format'];
						$sessionauto['hoursaftersubscription'] = (int)$_POST['hoursaftersubscription'];
						$sessionauto['trackopens'] = (isset($_POST['trackopens'])) ? true : false;
						$sessionauto['tracklinks'] = (isset($_POST['tracklinks'])) ? true : false;
						$sessionauto['multipart'] = (isset($_POST['multipart'])) ? true : false;
						$sessionauto['embedimages'] = (isset($_POST['embedimages'])) ? true : false;
						$sessionauto['includeexisting'] = (isset($_POST['includeexisting'])) ? true : false;

						$sessionauto['to_lastname'] = 0;
						if (isset($_POST['to_lastname'])) {
							$sessionauto['to_lastname'] = (int)$_POST['to_lastname'];
						}
						$sessionauto['to_firstname'] = 0;
						if (isset($_POST['to_firstname'])) {
							$sessionauto['to_firstname'] = (int)$_POST['to_firstname'];
						}

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep4($sessionauto['autoresponderid']);
					break;

					case 'step3':
						$sessionauto = IEM::sessionGet('Autoresponders');
						$sessionauto['name'] = $_POST['name'];
						$sessionauto['searchcriteria'] = array(
							'emailaddress' => '',
							'format' => '-1',
							'confirmed' => '1',
							'search_options' => array(),
							'customfields' => array()
						);

						if ($_POST['ShowFilteringOptions'] == 1) {
							$sessionauto['searchcriteria']['emailaddress'] = $_POST['emailaddress'];
							$sessionauto['searchcriteria']['format'] = $_POST['format'];
							$sessionauto['searchcriteria']['confirmed'] = $_POST['confirmed'];

							$search_options = (isset($_POST['Search_Options'])) ? $_POST['Search_Options'] : array();
							$sessionauto['searchcriteria']['search_options'] = $search_options;

							$customfields = (isset($_POST['CustomFields'])) ? $_POST['CustomFields'] : array();
							$sessionauto['searchcriteria']['customfields'] = $customfields;

							foreach ($sessionauto['searchcriteria']['customfields'] as $fieldid => $fieldvalue) {
								if (!$fieldvalue) {
									unset($sessionauto['searchcriteria']['customfields'][$fieldid]);
									continue;
								}
							}

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

								$sessionauto['searchcriteria']['link'] = $_POST['linkid'];
							}

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

								$sessionauto['searchcriteria']['newsletter'] = $_POST['newsletterid'];
							}
						}

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep3($sessionauto['autoresponderid']);
					break;

					default:
						$id = (int)$_GET['id'];

						IEM::sessionRemove('Autoresponders');
						$autosession = array('list' => (int)$_GET['list'], 'autoresponderid' => $id);
						IEM::sessionSet('Autoresponders', $autosession);

						$this->EditAutoresponderStep1($id);
				}
			break;

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

				switch ($subaction) {

					case 'save':
					case 'complete':
						$autoresponder = $this->GetApi();

						$user = IEM::getCurrentUser();
						$session_autoresponder = IEM::sessionGet('Autoresponders');

						if (!$session_autoresponder || !isset($session_autoresponder['name'])) {
							$this->ManageAutoresponders($listid);
							break;
						}

						$text_unsubscribelink_found = true;
						$html_unsubscribelink_found = true;

						$listid = $session_autoresponder['list'];

						$autoresponder->Set('listid', $listid);

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

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

						if (isset($_POST['subject'])) {
							$autoresponder->Set('subject', $_POST['subject']);
						}

						foreach (array('name', 'format', 'searchcriteria', 'sendfromname', 'sendfromemail', 'replytoemail', 'bounceemail', 'tracklinks', 'trackopens', 'multipart', 'embedimages', 'hoursaftersubscription', 'charset', 'includeexisting', 'to_firstname', 'to_lastname') as $p => $area) {
							$autoresponder->Set($area, $session_autoresponder[$area]);
						}

						$autoresponder->Set('active', 0);

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

						$result = $autoresponder->Create();

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

						/**
						* explicitly set the 'includeexisting' flag to false so we don't import the existing subscribers twice.
						* Create() & Save() both call ImportQueue if this flag is set, so ensure we don't do it twice.
						*/
						$autoresponder->Set('includeexisting', false);

						$session_autoresponder['autoresponderid'] = $result;
						IEM::sessionSet('Autoresponders', $session_autoresponder);

						if (SENDSTUDIO_ALLOW_ATTACHMENTS) {
							$dest = strtolower(get_class($this));
							$movefiles_result = $this->MoveFiles($dest, $result);
							if ($movefiles_result) {
								if (isset($textcontent)) {
									$textcontent = $this->ConvertContent($textcontent, $dest, $result);
									$autoresponder->SetBody('Text', $textcontent);
								}
								if (isset($htmlcontent)) {
									$htmlcontent = $this->ConvertContent($htmlcontent, $dest, $result);
									$autoresponder->SetBody('HTML', $htmlcontent);
								}
							}

							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);
							}
						}

						list($autoresponder_size, $autoresponder_img_warnings) = $this->GetSize($session_autoresponder);
						$GLOBALS['Message'] .= $this->PrintSuccess('AutoresponderUpdated', sprintf(GetLang('Autoresponder_Size_Approximate'), $this->EasySize($autoresponder_size)));
						$max_size = (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024);

						if (SENDSTUDIO_EMAILSIZE_WARNING > 0) {
							$warning_size = SENDSTUDIO_EMAILSIZE_WARNING * 1024;
							if ($autoresponder_size > $warning_size && ($max_size > 0 && $autoresponder_size < $max_size)) {
								if ($session_autoresponder['embedimages']) {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_Embed';
								} else {
									$warning_langvar = 'Autoresponder_Size_Over_EmailSize_Warning_No_Embed';
								}
								$GLOBALS['Message'] .= $this->PrintWarning($warning_langvar, $this->EasySize($warning_size));
							}
						}

						if ($max_size > 0 && $autoresponder_size >= $max_size) {
							if ($session_autoresponder['embedimages']) {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_Embed';
							} else {
								$error_langvar = 'Autoresponder_Size_Over_EmailSize_Maximum_No_Embed';
							}
							$GLOBALS['Error'] = sprintf(GetLang($error_langvar), $this->EasySize($max_size, 0));

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

						$autoresponder->Set('autorespondersize', $autoresponder_size);

						$autoresponder->Save();

						if ($autoresponder_img_warnings) {
							if ($session_autoresponder['embedimages']) {
								$warning_var = 'UnableToLoadImage_Autoresponder_List_Embed';
							} else {
								$warning_var = 'UnableToLoadImage_Autoresponder_List';
							}
							$GLOBALS['Message'] .= $this->PrintWarning($warning_var, $autoresponder_img_warnings);
						}

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

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

						if ($subaction == 'save') {
							$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled_Save');
							$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);
							$this->EditAutoresponderStep4($result);
							break;
						}

						$GLOBALS['Message'] .= $this->PrintWarning('AutoresponderHasBeenDisabled');

						$GLOBALS['Message'] = str_replace('<br><br>', '<br>', $GLOBALS['Message']);

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

					case 'step4':
						$sessionauto = IEM::sessionGet('Autoresponders');

						$sessionauto['sendfromname'] = $_POST['sendfromname'];
						$sessionauto['sendfromemail'] = $_POST['sendfromemail'];
						$sessionauto['replytoemail'] = $_POST['replytoemail'];
						$sessionauto['bounceemail'] = $_POST['bounceemail'];

						$sessionauto['charset'] = $_POST['charset'];

						$sessionauto['format'] = $_POST['format'];
						$sessionauto['hoursaftersubscription'] = (int)$_POST['hoursaftersubscription'];
						$sessionauto['trackopens'] = (isset($_POST['trackopens'])) ? true : false;
						$sessionauto['tracklinks'] = (isset($_POST['tracklinks'])) ? true : false;
						$sessionauto['multipart'] = (isset($_POST['multipart'])) ? true : false;
						$sessionauto['embedimages'] = (isset($_POST['embedimages'])) ? true : false;

						$sessionauto['includeexisting'] = (isset($_POST['includeexisting'])) ? true : false;

						$sessionauto['to_lastname'] = 0;
						if (isset($_POST['to_lastname'])) {
							$sessionauto['to_lastname'] = (int)$_POST['to_lastname'];
						}

						$sessionauto['to_firstname'] = 0;
						if (isset($_POST['to_firstname'])) {
							$sessionauto['to_firstname'] = (int)$_POST['to_firstname'];
						}

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

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep4();

					break;

					case 'step3':
						$sessionauto = IEM::sessionGet('Autoresponders');
						$sessionauto['name'] = $_POST['name'];
						$sessionauto['searchcriteria'] = array(
							'emailaddress' => '',
							'format' => '-1',
							'confirmed' => '1',
							'search_options' => array(),
							'customfields' => array()
						);

						if ($_POST['ShowFilteringOptions'] == 1) {
							$sessionauto['searchcriteria']['emailaddress'] = $_POST['emailaddress'];
							$sessionauto['searchcriteria']['format'] = $_POST['format'];
							$sessionauto['searchcriteria']['confirmed'] = $_POST['confirmed'];

							$search_options = (isset($_POST['Search_Options'])) ? $_POST['Search_Options'] : array();
							$sessionauto['searchcriteria']['search_options'] = $search_options;

							$customfields = (isset($_POST['CustomFields'])) ? $_POST['CustomFields'] : array();
							$sessionauto['searchcriteria']['customfields'] = $customfields;

							foreach ($sessionauto['searchcriteria']['customfields'] as $fieldid => $fieldvalue) {
								if (!$fieldvalue) {
									unset($sessionauto['searchcriteria']['customfields'][$fieldid]);
									continue;
								}
							}

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

								$sessionauto['searchcriteria']['link'] = $_POST['linkid'];
							}

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

								$sessionauto['searchcriteria']['newsletter'] = $_POST['newsletterid'];
							}
						}

						IEM::sessionSet('Autoresponders', $sessionauto);

						$this->EditAutoresponderStep3();
					break;

					case 'step2':
						$listid = 0;
						if (isset($_POST['list'])) {
							$listid = (int)$_POST['list'];
						}

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

						$auto = array('list' => $listid);

						IEM::sessionSet('Autoresponders', $auto);

						$this->EditAutoresponderStep1();
					break;

					default:
						IEM::sessionRemove('Autoresponders');
						$this->ChooseCreateList();
				}
			break;

			default:
				$this->SetCurrentPage(1);
				$this->ChooseList('Autoresponders', 'step2');
			break;
		}

		if (!in_array($action, $this->SuppressHeaderFooter)) {
			$this->PrintFooter($popup);
		}
	}
Ejemplo n.º 4
0
        if ($editMode) {
            $param_userid = IEM::ifsetor($function_params['userid'], false);
            if (!$param_userid) {
                SendResponse(false, 'userid cannot be empty.');
                exit();
            }

            $status = $user->Load($param_userid, true);
            if (!$status) {
                SendResponse(false, 'Cannot load user record.');
                exit();
            }
        }

        // ----- Check if username is available to be used
        $param_username = IEM::ifsetor($function_params['username'], false);
        if (!$param_username) {
            SendResponse(false, 'username cannot be empty.');
            exit();
        }

        $existingUser = $user->Find($param_username);

        if ($existingUser !== false) {
            $tempError = true;

            if ($editMode && $existingUser == $function_params['userid']) {
                $tempError = false;
            }

            if ($tempError) {
Ejemplo n.º 5
0
    /**
     * Load
     * Loads up the user and sets the appropriate class variables. Calls LoadPermissions to load up access to areas and items.
     *
     * @param Int $userid The userid to load up. If the userid is not present then it will not load up. If the userid doesn't exist in the database, then this will also return false.
     * @param Boolean $load_permissions Whether to load the users permissions or not. This defaults to true (so they are loaded) but the stats area doesn't need to load up permissions so it will pass in false.
     *
     * @see LoadPermissions
     *
     * @return Boolean Will return false if the userid is not present, or the user can't be found, otherwise it set the class vars and return true.
     */
    function Load($userid=0, $load_permissions=true) {
        $userid = intval($userid);

        if ($userid <= 0) {
            return false;
        }

        $query = "SELECT * FROM [|PREFIX|]users WHERE userid={$userid}";
        $result = $this->Db->Query($query);
        if (!$result) {
            return false;
        }

        $user = $this->Db->Fetch($result);
        if (empty($user)) {
            return false;
        }

        $this->userid = $user['userid'];
        $this->groupid = $user['groupid'];
        $this->trialuser = IEM::ifsetor($user['trialuser'], '0');
        $this->username = $user['username'];
        $this->unique_token = isset($user['unique_token']) ? $user['unique_token'] : '';
        $this->status = ($user['status'] == 1) ? true : false;
        $this->admintype = $user['admintype'];
        $this->listadmintype = $user['listadmintype'];
        $this->templateadmintype = $user['templateadmintype'];
        $this->editownsettings = ($user['editownsettings'] == 1) ? true : false;
        $this->infotips = ($user['infotips'] == 1) ? true : false;
        $this->fullname = $user['fullname'];
        $this->emailaddress = $user['emailaddress'];
        $this->usertimezone = $user['usertimezone'];
        $this->textfooter = $user['textfooter'];
        $this->htmlfooter = $user['htmlfooter'];

        $this->smtpserver = $user['smtpserver'];
        $this->smtpusername = $user['smtpusername'];
        $this->smtppassword = base64_decode($user['smtppassword']);
        $this->smtpport = (int) $user['smtpport'];
        if ($this->smtpport <= 0) {
            $this->smtpport = 25;
        }

        $this->lastloggedin = (int) $user['lastloggedin'];
        $this->createdate = (int) $user['createdate'];
        $this->forgotpasscode = $user['forgotpasscode'];


        if (isset($user['usewysiwyg'])) {
            $wysiwyg = intval($user['usewysiwyg']);
            if ($wysiwyg == 0) {
                $this->usewysiwyg = 0;
            } else {
                $this->usewysiwyg = 1;
                if ($wysiwyg == 2) {
                    $this->usexhtml = false;
                }
            }
        }

        if (isset($user['xmltoken']) && isset($user['xmlapi'])) {
            if ($user['xmlapi'] == 1) {
                $this->xmlapi = 1;
            }

            if ($user['xmltoken'] != null && $user['xmltoken'] != '') {
                $this->xmltoken = $user['xmltoken'];
            }
        }

        // The following options may have been added after an upgrade and may not yet exist.

        $this->eventactivitytype = IEM::ifsetor($user['eventactivitytype'], array());
        $this->user_language = IEM::ifsetor($user['user_language']);
        $this->enableactivitylog = IEM::ifsetor($user['enableactivitylog']);
        $this->gettingstarted = IEM::ifsetor($user['gettingstarted']);
        $this->segmentadmintype = IEM::ifsetor($user['segmentadmintype']);

        // Only set the google details if they are available.
        if (isset($user['googlecalendarusername'])) {
            $this->googlecalendarusername = $user['googlecalendarusername'];
            $this->googlecalendarpassword = $user['googlecalendarpassword'];
        }

        if (isset($user['credit_warning_percentage'])) {
            $this->credit_warning_percentage = $user['credit_warning_percentage'];
            $this->credit_warning_fixed = $user['credit_warning_fixed'];
            $this->credit_warning_time = $user['credit_warning_time'];
        }


        // Loading user admin notification settings

        $this->adminnotify_email = IEM::ifsetor($user['adminnotify_email'], '');
        $this->adminnotify_send_flag = IEM::ifsetor($user['adminnotify_send_flag'], 0);
        $this->adminnotify_send_threshold = IEM::ifsetor($user['adminnotify_send_threshold'], 0);
        $this->adminnotify_send_emailtext = IEM::ifsetor($user['adminnotify_send_emailtext'], '');
        $this->adminnotify_import_flag = IEM::ifsetor($user['adminnotify_import_flag'], 0);
        $this->adminnotify_import_threshold = IEM::ifsetor($user['adminnotify_import_threshold'], 0);
        $this->adminnotify_import_emailtext = IEM::ifsetor($user['adminnotify_import_emailtext'], '');

        if ($load_permissions) {
            $this->LoadPermissions($userid);
        }

        if ($user['settings'] != '') {
            $this->settings = unserialize($user['settings']);
        }

        if (is_null($this->segmentadmintype)) {
            $this->segmentadmintype = $this->AdminType();
        }

        return true;
    }
Ejemplo n.º 6
0
				case 'radiobutton':
					$placeholders[] = '%%CustomField_' . $customfield['fieldid'] . '_' . $customfield['data'] . '%%';
					$placeholder_values[] = ' CHECKED';
				break;

				case 'dropdown':
					$placeholders[] = '%%CustomField_' . $customfield['fieldid'] . '_' . $customfield['data'] . '%%';
					$placeholder_values[] = ' SELECTED';
				break;

				case 'date':
					$exploded_date = explode('/', $customfield['data']);
					foreach (array('dd', 'mm', 'yy') as $p => $datepart) {
						// If date is not available, then do not continue with the selection
						$item = IEM::ifsetor($exploded_date[$p], '');
						if (empty($item)) {
							continue;
						}

						$placeholders[] = '%%CustomField_'.$customfield['fieldid'].'_'.$item.'_'.$datepart.'%%';
						$placeholder_values[] = ' SELECTED';
					}
				break;

				default:
					$placeholders[] = '%%CustomField_' . $customfield['fieldid'] . '%%';
					$placeholder_values[] = htmlspecialchars($customfield['data'], ENT_QUOTES, SENDSTUDIO_CHARSET);
			}

			$customfields_done[] = $customfield['fieldid'];
Ejemplo n.º 7
0
	/**
	 * testBounceSettings
	 * Produces the contents of the thickbox used when checking bounce login details.
	 * If specified, it will try all possible combinations of extra settings to get a connection.
	 *
	 * @param boolean $in_place If set to true, will update the extra settings in place and not redirect.
	 *
	 * @return void Does not return anything.
	 */
	private function testBounceSettings($in_place = false)
	{
		$tpl = GetTemplateSystem();
		$bd = self::hold('TestBounceDetails');

		$upto_combo = IEM::ifsetor($bd['upto_combo'], 0);
		$combinations = array($bd['extra_settings']);
		// If extra settings aren't specified, we need to auto-detect.
		if (!$bd['extra_settings']) {
			$combinations = $this->generateConnectionCombinations();
		}

		if ($upto_combo > count($combinations)) {
			// Handle the case where checking has finished but no solution has been found.
			self::handle('error_report', $in_place);
		}

		if ($upto_combo == 0) {
			// Reset error log.
			self::hold('ConnectionErrors', array());
			// Check the sever can actually be connected to (manually, so we can customise the timeout).
			$message = sprintf(GetLang('Bounce_Connecting_To'), $bd['server']);
			self::updateProgressBar(0, $message);
			list($success, $error) = self::testConnection($bd);
			if (!$success) {
				$error_log[] = $error;
				self::hold('ConnectionErrors', $error_log);
				self::handle('error_report', $in_place);
			}
		}

		// Update progress window status.
		$percent_processed = floor($upto_combo / count($combinations) * 100);
		self::updateProgressBar($percent_processed);

		// Attempt a login with one of the settings combinations.
		list($success, $count_or_error) = self::testCombination($bd, $combinations[$upto_combo]);

		if ($success) {
			// Store the email count for the next step.
			self::hold('EmailCount', $count_or_error);

			// Save the successfull extra settings.
			$bd['extra_settings'] = $combinations[$upto_combo];
			self::hold('TestBounceDetails', $bd);

			// Redirect to the next step.
			self::updateProgressBar(100);
			self::handle('success', $in_place);
		}

		// Combination failed - record error and try the next combination.
		$error_message = $combinations[$upto_combo] . ': ' . $count_or_error;
		$error_log[] = $error_message;
		self::hold('ConnectionErrors', $error_log);

		$error = self::getRealError($error_message);

		if ($error['fatal'] || count($combinations) == 1) {
			// No point continuing to try after a fatal error.
			self::updateProgressBar(100);
			self::handle('error_report', $in_place);
		}

		$bd['upto_combo']++;
		self::hold('TestBounceDetails', $bd);
		self::handle('next_combo', $in_place);
	}
Ejemplo n.º 8
0
/**
 * GetRealIp
 * Gets the IP from the users web browser. It checks if there is a proxy etc in front of the browser.
 *
 * NOTE: This will return the connection IP address rather than the real address behind a proxy.
 * The reason for the change is that getting client's IP address VIA proxy header is NOT reliable enough.
 * At least this way we have a record of the connection IP address instead of a possible bogus IP.
 *
 * @param Boolean $override_settings If this is passed in and true, this will skip the check for ip tracking being enabled. Currently this is only used by the user functions to always grab a users ip address when they generate a new xml api token.
 *
 * @return String The IP address of the user.
 *
 * @todo refactor this
 */
function GetRealIp($override_settings=false)
{
		$iptracking = true;
		if (defined('SENDSTUDIO_IPTRACKING') && !SENDSTUDIO_IPTRACKING) {
			$iptracking = false;
		}


		if (!$override_settings && !$iptracking) {
			return null;
		}

		$ip = IEM::ifsetor($_SERVER['REMOTE_ADDR'], false);
		if (!$ip) {
			return null;
		}

		// Handle IPv6.
		if (strpos($ip, ':') !== false) {
			// IPv6's deprecated IPv4 compatibility mode.
			// See http://www.mail-archive.com/swinog@lists.swinog.ch/msg03443.html.
			if (!preg_match('/\:\:ffff\:([\d\.]+)/i', $ip, $matches)) {
				return $ip;
			}
			$ip = $matches[1]; // Continue checking.
		}

		// ----- Make sure that this is a valid IP
			$ip = ip2long($ip);
			if ($ip !== false && $ip !== -1 && $ip !== 0) {
				$ip = long2ip($ip);
			} else {
				$ip = '';
			}
		// -----

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

		$this->LoadLanguageFile('Stats');

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

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

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

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

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

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

			default:
				$chart_area = 'Newsletter';
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			break;

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

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

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

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

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

			break;

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

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

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

					$total = array_sum($domain_details);

					$graph_pos = 1;

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

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

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

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

							$graph_pos++;
						}
					}

					break;
				}

				$opens = $unopened = $bounces = 0;

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

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

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

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

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

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

				$opens_percent = $unopened_percent = $bounces_percent = 0;

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

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

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

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

				$opens_percent = $opens / 100;

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

		}

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

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

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

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

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

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

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

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

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

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

			// Restore error handling
			error_reporting(E_ALL);
			restore_error_handler();
		} else {
			// gets chart data as xml for amcharts
			SendChartData($this->chart);
		}
	}