Пример #1
0
	/**
	* Process
	* Takes the appropriate action based on the action
	*
	* @return Void Doesn't return anything. Takes the appropriate action.
	*/
	function Process()
	{
		$GLOBALS['Message'] = '';

		if(is_null($this->user)){$this->user = IEM::userGetCurrent();}

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

		$type = (isset($_GET['Type'])) ? strtolower($_GET['Type']) : '';
		$typeId = (isset($_GET['TypeId'])) ? strtolower($_GET['TypeId']) : 0;
		
		//trying to get another users images? that shouldn't happen
		if($type == 'user' && $typeId != $this->user->userid){
			$GLOBALS['Message'] = 'Unable to load images for another user ID';
			exit();
		}

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

		switch ($action) {
			case 'remoteupload':
			$this->RemoteUpload($type, $typeId);
			break;
			case 'getimageslist':
			$this->GetImagesList($type, $typeId);
			break;
			case 'noflashupload':
			$this->NoFlashUpload();
			break;
			default:
			$this->PrintHeader();
			$this->ManageImages($this->user->userid);
		}

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

        $action = (isset($_GET['Action'])) ? strtolower(urldecode($_GET['Action'])) : null;
        $id = (isset($_GET['id'])) ? strtolower(urldecode($_GET['id'])) : null;
        $user = IEM::userGetCurrent();
        $final_action = $action;
        $secondary_actions = array('activate', 'deactivate', 'activatearchive', 'deactivatearchive');
        if (in_array($action, $secondary_actions)) {
            $final_action = 'approve';
        }

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

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


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

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

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

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

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

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

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

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

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

                $message = '';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


                        $result = $newsletter->Save();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		$page = array(
			'messages' => GetFlashMessages()
		);

		IEM::sessionSet('UsersGroups_Editor_RequestToken', $requestToken);

		if (!isset($record['permissions']) || !is_array($record['permissions'])) {
			$record['permissions'] = array();
		}

		if (!isset($record['access']) || !is_array($record['access'])) {
			$record['access'] = array();
		}

		$record['permissions_stupid_template'] = array();
		
		if (isset($record['permissions'])) {
			foreach ($record['permissions'] as $key => $value) {
				foreach ($value as $each) {
					$record['permissions_stupid_template'][] = "{$key}.{$each}";
				}
			}
		}
		
		$this->PrintHeader();
		
		$tpl = GetTemplateSystem();
		$tpl->Assign('PAGE', $page);
		$tpl->Assign('record', $record);
		$tpl->Assign('permissionList', $permissionList);
		$tpl->Assign('isSystemAdmin', $group->isAdmin());
		$tpl->Assign('isLastAdminWithUsers', $group->isLastAdminWithUsers());
		$tpl->Assign('availableLists', $availableLists, true);
		$tpl->Assign('availableSegments', $availableSegments, true);
		$tpl->Assign('availableTemplates', $availableTemplates, true);
		$tpl->Assign('requestToken', $requestToken);

		$tpl->ParseTemplate('UsersGroups_Form');

		$this->PrintFooter();

		return;
	}
Пример #5
0
	/**
	 * _GenerateSegmentRuleQuery
	 * Generate segment rule query by populating "tables", "joins", and "conditions" that needed to be added to the query
	 *
	 * @param Array $rules Segment rule
	 * @param String $connector Connector for the query (this can be 'AND' or 'OR')
	 * @param Array &$tables A reference to an array that will contains "tables" that needed to be added to the query string
	 * @param Array &$joins A reference to an array that will contains "join" condition that needed to be added to the query string
	 * @param Array &$conditions A reference to an array that will contains "where" conditions that needed to be added to the query string
	 * @param Array $listids An array of list ID
	 *
	 * @return Boolean Returns TRUE if process was successful, FALSE otherwise
	 *
	 * @uses SENDSTUDIO_TABLEPREFIX
	 * @uses Subscribers_API::_GenerateSegmentRuleQuery()
	 * @uses Subscribers_API::_TranslateSegmentOperator()
	 * @uses Subscribers_API::_GenerateSegmentRuleQuery_Customfield()
	 * @uses Db::Quote()
	 * @uses Db::Query()
	 * @uses Db::FreeResult()
	 * @uses API::_subqueryCapable()
	 *
	 * @access private
	 */
	function _GenerateSegmentRuleQuery($rules, $connector, &$tables, &$joins, &$conditions, $listids)
	{
		$firstCondition = true;
		$previousConnector = $connector;

		array_push($conditions, $connector . ' (');

		foreach ($rules as $k => $eachRule) {
			if (!$firstCondition) {
				array_push($conditions, $previousConnector);
			}

			switch ($eachRule['type']) {
				case 'group':
					$status = $this->_GenerateSegmentRuleQuery($eachRule['rules'], '', $tables, $joins, $conditions, $listids);
					if ($status === false) {
						trigger_error('Failed to process rule grouping', E_USER_WARNING);
						return false;
					}
					break;

				case 'rule':
					// Numeric "ruleName" means the rule is using a custom field.
					if (is_numeric($eachRule['rules']['ruleName'])) {
						$operator = $eachRule['rules']['ruleOperator'];

						/**
						 * The operator: isempty and isnotempty; will check whether or not
						 * a contact has filled in a praticualar custom field.
						 */
						switch ($operator) {
							case 'isempty':
								$tempQuery = 	'SELECT s.subscriberid AS subscriberid'
								. ' FROM ' . SENDSTUDIO_TABLEPREFIX . 'list_subscribers s'
								. ' LEFT JOIN ' . SENDSTUDIO_TABLEPREFIX . 'subscribers_data d'
								. ' ON s.subscriberid = d.subscriberid'
								. ' AND d.fieldid = ' . intval($eachRule['rules']['ruleName'])
								. ' WHERE d.fieldid IS NULL OR d.data = ""';
								break;

							case 'isnotempty':
								$tempQuery = 	'SELECT s.subscriberid AS subscriberid'
								. ' FROM ' . SENDSTUDIO_TABLEPREFIX . 'list_subscribers s'
								. ' JOIN ' . SENDSTUDIO_TABLEPREFIX . 'subscribers_data d'
								. ' ON s.subscriberid = d.subscriberid'
								. ' AND d.fieldid = ' . intval($eachRule['rules']['ruleName'])
								. ' AND d.data <> ""';
								break;

							default:
								$condition = $this->_GenerateSegmentRuleQuery_Customfield($eachRule);

								if ($condition === false) {
									trigger_error('Failed to process custom field condition', E_USER_WARNING);
									return false;
								}

								$tempQuery = 	'SELECT d.subscriberid AS subscriberid'
								. ' FROM ' . SENDSTUDIO_TABLEPREFIX . 'subscribers_data d'
								. ' WHERE ' . $condition;
								break;
						}

						$tempInclusion = 'IN';
						if (in_array($operator, array('notequalto', 'notlike'))) {
							$tempInclusion = 'NOT IN';
						}

						if ($this->_subqueryCapable()) {
							array_push($conditions, 'subscribers.subscriberid ' . $tempInclusion . ' (' . $tempQuery . ')');
						} else {
							$records = array('0');
							$rs = $this->Db->Query($tempQuery);
							while ($row = $this->Db->Fetch($rs)) {
								$records[] = (int)$row['subscriberid'];
							}

							$this->Db->FreeResult($rs);
							array_push($conditions, 'subscribers.subscriberid ' . $tempInclusion . ' ('. implode(',', $records) .')');
						}
					} else {
						switch ($eachRule['rules']['ruleName']) {
							// Filter by email
							case 'email':
								$tempValue =  $eachRule['rules']['ruleValues'][0];

								if (in_array($eachRule['rules']['ruleOperator'], array('like', 'notlike'))) {
									// Check whether or not use has already included their %, if not add % automatically
									$tempPosition = strpos($tempValue, '%');
									if (($tempPosition !== 0) && ($tempPosition !== (strlen($tempValue) - 1))) {
										$tempValue = '%' . $tempValue . '%';
									}
								}

								array_push($conditions,	'subscribers.emailaddress '
								. $this->_TranslateSegmentOperator($eachRule['rules']['ruleOperator'])
								. " '" . $this->Db->Quote($tempValue) . "'");
								break;

								// Filter by format preference
							case 'format':
								array_push($conditions, 'subscribers.format'
								. $this->_TranslateSegmentOperator($eachRule['rules']['ruleOperator'])
								. " '" . ($eachRule['rules']['ruleValues'][0] == 'h'? 'h' : 't') . "'");
								break;

								// Filter by subscriber status (active/bounced/unsubscribed)
							case 'status':
								$tempValue = false;
								$tempOperator = $eachRule['rules']['ruleOperator'];

								switch ($eachRule['rules']['ruleValues'][0]) {
									case 'b':
										if ($tempOperator == 'equalto') {
											$tempValue = 'subscribers.bounced > 0';
										} else {
											$tempValue = 'subscribers.bounced = 0';
										}
										break;

									case 'u':
										if ($tempOperator == 'equalto') {
											$tempValue = 'subscribers.unsubscribed > 0';
										} else {
											$tempValue = 'subscribers.unsubscribed = 0';
										}
										break;

									case 'a':
										if ($tempOperator == 'equalto') {
											$tempValue = '(subscribers.unsubscribed=0 AND subscribers.bounced=0)';
										} else {
											$tempValue = '(subscribers.unsubscribed<>0 OR subscribers.bounced<>0)';
										}
										break;
								}

								if ($tempValue == false) {
									trigger_error('Unknown "Status" was specified in rule', E_USER_WARNING);
									return false;
								}

								array_push($conditions, $tempValue);
								break;

								// Filter by confirmation status (confirmed or unconfirmed)
							case 'confirmation':
								array_push($conditions, 'subscribers.confirmed '
								. $this->_TranslateSegmentOperator($eachRule['rules']['ruleOperator'])
								. " '" . intval($eachRule['rules']['ruleValues'][0]) . "'");
								break;

								// Filter by subscribed date
							case 'subscribe':
								$tempOperator = $this->_TranslateSegmentOperator($eachRule['rules']['ruleOperator'], true);
								$tempValues = $eachRule['rules']['ruleValues'];

								/**
								 * Make sure that the time is always in chronological order
								 * (as there is only 2 times, we don't need to deply any sorting method --- This will do nicely)
								 */
								if (count($tempValues) == 2) {
									list($tempDay, $tempMonth, $tempYear) = explode('/', $tempValues[0]);
									$tempValue1 = mktime(null, null, null, $tempMonth, $tempDay, $tempYear);

									list($tempDay, $tempMonth, $tempYear) = explode('/', $tempValues[1]);
									$tempValue2 = mktime(null, null, null, $tempMonth, $tempDay, $tempYear);

									if ($tempValue1 < $tempValue2) {
										$tempValues = array($tempValues[0], $tempValues[1]);
									} else {
										$tempValues = array($tempValues[1], $tempValues[0]);
									}
								}
								/**
								 * -----
								 */
                                $user = IEM::userGetCurrent();
                                $DateConverter = new ConvertDate(SENDSTUDIO_SERVERTIMEZONE, $user->Get('usertimezone'));
								// Convert date into unix timestamp
								$tempTime = array();
								if (count($tempValues) == 2) {
									list($tempDay, $tempMonth, $tempYear) = explode('/', $tempValues[0]);
									array_push($tempTime, $DateConverter->ConvertToGMTFromServer(0, 0, 0, $tempMonth, $tempDay, $tempYear));

									list($tempDay, $tempMonth, $tempYear) = explode('/', $tempValues[1]);
									array_push($tempTime, $DateConverter->ConvertToGMTFromServer(23, 59, 59, $tempMonth, $tempDay, $tempYear));
								} else {
									list($tempDay, $tempMonth, $tempYear) = explode('/', $tempValues[0]);
									//array_push($tempTime, $DateConverter->ConvertToGMTFromServer(0, 0, 0, $tempMonth, $tempDay, $tempYear));
									array_push($tempTime, $DateConverter->ConvertToGMTFromServer(23, 59, 59, $tempMonth, $tempDay, $tempYear));
								}

								$tempCondition = array();
								foreach ($tempTime as $index => $each) {
									array_push($tempCondition, ('subscribers.subscribedate '
									. (is_array($tempOperator)? $tempOperator[$index] : $tempOperator)
									. ' ' . $each));
								}

								$tempOperator = ' AND ';
								if ($eachRule['rules']['ruleOperator'] == 'notequalto') {
									$tempOperator = ' OR ';
								}

								array_push($conditions, '(' . implode($tempOperator, $tempCondition) . ')');
								break;

								// Filter by "have clicked" or "have not clicked" link
							case 'link':
								$tempValue = intval($eachRule['rules']['ruleValues'][0]);

								if ($eachRule['rules']['ruleOperator'] == 'equalto') {
									if (!array_key_exists('lc', $tables)) {
										$tables['lc'] = '';
										$tables['subscribers'] .= ' LEFT JOIN ' . SENDSTUDIO_TABLEPREFIX . 'stats_linkclicks AS lc ON subscribers.subscriberid=lc.subscriberid';
									}

									if ($tempValue > -1) {
										array_push($conditions, 'lc.linkid=' . $tempValue);
									} else {
										array_push($conditions, 'lc.linkid IS NOT NULL');
									}
								} else {
									$query = 	'SELECT lc.subscriberid AS subscriberid FROM ' . SENDSTUDIO_TABLEPREFIX . 'stats_linkclicks AS lc'
									. (($tempValue > -1)? ' WHERE lc.linkid=' . $tempValue : '');

									if ($this->_subqueryCapable()) {
										array_push($conditions, 'subscribers.subscriberid NOT IN (' . $query . ')');
									} else {
										$records = array('0');
										$rs = $this->Db->Query($query);
										while ($row = $this->Db->Fetch($rs)) {
											$records[] = (int)$row['subscriberid'];
										}

										$this->Db->FreeResult($rs);
										array_push($conditions, 'subscribers.subscriberid NOT IN ('. implode(',', $records) .')');
									}
								}
								break;

								// Filter subsribers by "opened" and "have not opened" a campaign
							case 'campaign':
								if ($eachRule['rules']['ruleOperator'] == 'equalto') {
									if (!array_key_exists('seo', $tables)) {
										$tables['seo'] = ', [|PREFIX|]stats_emailopens AS seo';
										$tables['sn'] = 'JOIN [|PREFIX|]stats_newsletters AS sn'
										. ' ON seo.statid = sn.statid';
										array_push($joins, 'subscribers.subscriberid = seo.subscriberid');
									}

									$tempNewsletterID = intval($eachRule['rules']['ruleValues'][0]);
									if ($tempNewsletterID == -1) {
										array_push($conditions, 'sn.newsletterid <> 0');
									} else {
                                        //fix for when there are multiple "opened" a campaign rules to use "OR" instead of "AND"
                                        //otherwise we'll end up with a query condition like "(newsletter.id=1 AND newsletter.id=2)"
                                        if (!empty($rules[($k+1)])) {
                                            $nextRule = $rules[($k+1)];
                                            if ($nextRule['rules']['ruleName'] == 'campaign' && $nextRule['rules']['ruleOperator'] == 'equalto') {
                                                $eachRule['connector'] = 'OR';
                                            }
                                        }
										array_push($conditions, 'sn.newsletterid = ' . $tempNewsletterID);
									}
								} else {
									$query =	'SELECT subscriberid FROM [|PREFIX|]stats_emailopens AS seo'
									. ', [|PREFIX|]stats_newsletters AS sn'
									. ' WHERE sn.statid=seo.statid'
									. (($eachRule['rules']['ruleValues'][0] != -1)? ' AND sn.newsletterid=' . intval($eachRule['rules']['ruleValues'][0]) : '');

									if ($this->_subqueryCapable()) {
										array_push($conditions, 'subscribers.subscriberid NOT IN (' . $query . ')');
									} else {
										$records = array('0');
										$rs = $this->Db->Query($query);
										while ($row = $this->Db->Fetch($rs)) {
											$records[] = (int)$row['subscriberid'];
										}

										$this->Db->FreeResult($rs);
										array_push($conditions, 'subscribers.subscriberid NOT IN ('. implode(',', $records) .')');
									}
								}
								break;

								// Filter subscriber by "subscriber ID"
							case 'subscriberid':
								$tempValue =  $eachRule['rules']['ruleValues'][0];

								array_push($conditions,	'subscribers.subscriberid '
								. $this->_TranslateSegmentOperator($eachRule['rules']['ruleOperator'])
								. intval($tempValue));
								break;

							default:
								trigger_error('Unknown rule name', E_USER_WARNING);
								return false;
								break;
						}
					}
					break;

				default:
					trigger_error('Unknown rule type -- Must either be group or rule', E_USER_WARNING);
					return false;
					break;
			}

			$previousConnector = $eachRule['connector'];
			$firstCondition = false;
		}

		array_push($conditions, ')');

		return true;
	}
Пример #6
0
	/**
	* MoveFiles
	* Moves uploaded images from temporary storage under a user's id - to it's final location - under the type and it's id. Eg newsletter/1.
	*
	* @param String $destination The destination (eg newsletter or template).
	* @param Int $id The destinations id.
	*
	* @see CreateDirectory
	* @see list_files
	*
	* @return Boolean Returns false if it can't create the paths or it can't copy the necessary files. Returns true if everything worked ok.
	*/
	function MoveFiles($destination=false, $id=0)
	{
		if (!$destination) {return false;}

                if($id <= 0){ return false; }
                
                $user = IEM::userGetCurrent();
                
                $tempid = $user->userid . "_tmp";
                
		$destinationdir = TEMP_DIRECTORY . '/' . $destination . '/' . $id;
		$tempdir = TEMP_DIRECTORY . '/' . $destination . '/' . $tempid;

                if(!file_exists($destinationdir)){
                    $createdir = CreateDirectory($destinationdir,TEMP_DIRECTORY,0777);
                    if (!$createdir) {return false;}
                }
		//Get files from the 'temporary' folder, /destination/userid_tmp/, and move them to the final location
                if(CopyDirectory($tempdir, $destinationdir)){remove_directory($tempdir);}
		
		return true;
	}
Пример #7
0
 public static function langLoad($language)
 {
     $user = IEM::userGetCurrent();
     $user_language = 'default';
     $language = strtolower($language);
     // If it has been loaded before, return
     if (in_array($language, self::$_langLoaded)) {
         return true;
     }
     // If user have their own language preference, use that
     if (!empty($user->user_language)) {
         $users_language = $user->user_language;
     }
     // If their language preference not available, we use the default
     if (empty($users_language) || !is_dir(IEM_PATH . "/language/{$users_language}")) {
         $users_language = 'default';
     }
     // ----- Include language file
     $langfile = IEM_PATH . "/language/{$users_language}/{$language}.php";
     if (!is_file($langfile)) {
         trigger_error("No Language file for {$language} area", E_USER_WARNING);
         return false;
     }
     include_once $langfile;
     // -----
     self::$_langLoaded[] = $language;
     return true;
 }
Пример #8
0
	/**
	* SetFolderMode
	* Sets the viewing mode to either the normal non-folder list mode or
	* folder mode.
	*
	* @param String $mode Either 'list' (normal) or 'folder'.
	*
	* @uses GetPageName
	* @uses GetUser
	* @uses User_API::GetSettings
	* @uses User_API::SetSettings
	*
	* @return Boolean True if the setting was saved, otherwise false.
	*/
	public function SetFolderMode($mode)
	{
		$mode = strtolower($mode);

		if (!in_array($mode, array('list', 'folder'))) {
			return false;
		}

		$user = IEM::userGetCurrent();
		$page = $this->GetPageName();

		$display_settings = $user->GetSettings('DisplaySettings');
		if (!isset($display_settings['FolderMode']) || !is_array($display_settings['FolderMode'])) {
			$display_settings['FolderMode'] = array();
		}
		$display_settings['FolderMode'][$page] = $mode;

		$user->SetSettings('DisplaySettings', $display_settings);
		$user->SaveSettings();

		return true;
	}
Пример #9
0
    /**
     * ReduceEmails
     * Reduces the maximum amount of emails the current user can send.
     *
     * @param Int $reduce_emails_by The number of emails to reduce by.
     *
     * @return Boolean True if the reduction was completed successfully, otherwise false.
     */
    function ReduceEmails($reduce_emails_by=0) {
        if ($this->userid <= 0) {
            return false;
        }

        $userid = intval($this->userid);
        $reduce_emails_by = intval($reduce_emails_by);

        if ($reduce_emails_by == 0) {
            return true;
        }

        if ($this->hasUnlimitedTotalCredit()) {
            return true;
        }

        $this->GetDb();

        $currentUser = IEM::userGetCurrent();

        if ($currentUser->userid == $this->userid) {
            IEM::userFlushCache();
        }

        return true;
    }
Пример #10
0
		/**
		 * _TriggerEmailsStats_Permission
		 * Check whether or not current user have the permission to access
		 *
		 * @param Integer $id ID of the trigger emails
		 * @return Boolean Returns TRUE if user is able to access record, FALSE otherwise
		 */
		function _TriggerEmailsStats_Access($id)
		{
			$id = intval($id);
			$user = IEM::userGetCurrent();

			if ($id == 0) {
				return false;
			}

			// Admin can access all
			if ($user->Admin()) {
				return true;
			}

			// Only admin user and the owner of the trigger can access them.
			$api = $this->GetApi('Triggeremails');
			$record = $api->GetRecordByID($id);
			return ($user->userid === $record['ownerid']);
		}
Пример #11
0
 /**
  * SetPerPage
  * This is an internal only method which sets the number of results to show per page for a particular addon per user.
  *
  * Each addon (and each user) can have different per-page settings.
  *
  * @param Int $perpage The new perpage limit for the current addon. The default is 10 and if an invalid number is passed through, 10 is also the new number set.
  *
  * @uses addon_id
  * @uses GetUser
  * @uses User_API::GetSettings
  * @uses User_API::SetSettings
  *
  * @return Int Returns the new perpage limit set.
  */
 protected function SetPerPage($perpage = 10)
 {
     $perpage = (int) $perpage;
     if ($perpage < 1) {
         $perpage = 10;
     }
     $user = IEM::userGetCurrent();
     $display_settings = $user->GetSettings('DisplaySettings');
     if (!isset($display_settings['NumberToShow']) || !is_array($display_settings['NumberToShow'])) {
         $display_settings['NumberToShow'] = array();
     }
     $display_settings['NumberToShow'][$this->addon_id] = $perpage;
     $user->SetSettings('DisplaySettings', $display_settings);
     $user->SaveSettings();
     return $perpage;
 }
Пример #12
0
	/**
	* Process
	* All the action happens here.
	* If you are not logged in, it will print the login form.
	* Submitting that form will then try to authenticate you.
	* If you are successfully authenticated, you get redirected back to the main index page (quickstats etc).
	* Otherwise, will show an error message and the login form again.
	*
	* @see ShowLoginForm
	* @uses AuthenticationSystem::Authenticate()
	*
	* @return Void Doesn't return anything. Checks the action and passes it off to the appropriate area.
	*/
	function Process()
	{
		$action = IEM::requestGetGET('Action', '', 'strtolower');
		switch ($action) {
			case 'forgotpass':
				$this->ShowForgotForm();
			break;

			case 'changepassword':
				if (!IEM::sessionGet('ForgotUser')) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				$userapi = GetUser(-1);
				$loaded = $userapi->Load(IEM::sessionGet('ForgotUser'));

				if (!$loaded) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				$password = IEM::requestGetPOST('ss_password', false);
				$confirm = IEM::requestGetPOST('ss_password_confirm', false);

				if ($password == false || ($password != $confirm)) {
					$this->ShowForgotForm_Step2($userapi->Get('username'), 'login_error', GetLang('PasswordsDontMatch'));
					break;
				}

				$userapi->password = $password;
				$userapi->Save();

				$code = md5(uniqid(rand(), true));

				$userapi->ResetForgotCode($code);

				$this->ShowLoginForm('login_success', GetLang('PasswordUpdated'));
			break;

			case 'sendpass':
				$user = GetUser(-1);
				$username = IEM::requestGetPOST('ss_username', '');

				/**
				 * Fix vulnerabilities with MySQL
				 * Documented here: http://www.suspekt.org/2008/08/18/mysql-and-sql-column-truncation-vulnerabilities/
				 *
				 * Basically MySQL is truncating values in a column
				 */
					$username = preg_replace('/\s+/', ' ', $username);
					$username = trim($username);
				/**
				 * -----
				 */

				$founduser = $user->Find($username);
				if (!$founduser) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Forgot'));
					break;
				}

				$user->Load($founduser, false);

				$code = md5(uniqid(rand(), true));

				$user->ResetForgotCode($code);

				$link = SENDSTUDIO_APPLICATION_URL . '/admin/index.php?Page=Login&Action=ConfirmCode&user='******'&code=' . $code;

				$message = sprintf(GetLang('ChangePasswordEmail'), $link);

				$email_api = $this->GetApi('Email');
				$email_api->Set('CharSet', SENDSTUDIO_CHARSET);
				$email_api->Set('Multipart', false);
				$email_api->AddBody('text', $message);
				$email_api->Set('Subject', GetLang('ChangePasswordSubject'));

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

				$email_api->SetSmtp(SENDSTUDIO_SMTP_SERVER, SENDSTUDIO_SMTP_USERNAME, @base64_decode(SENDSTUDIO_SMTP_PASSWORD), SENDSTUDIO_SMTP_PORT);

				$user_fullname = $user->Get('fullname');

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

				$email_api->Send();

				$this->ShowForgotForm_Step2($username,'login_success', sprintf(GetLang('ChangePassword_Emailed'), $user->emailaddress));
			break;

			case 'confirmcode':
				$user = IEM::requestGetGET('user', false, 'intval');
				$code = IEM::requestGetGET('code', false, 'trim');

				if (empty($user) || empty($code)) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				$userapi = GetUser(-1);
				$loaded = $userapi->Load($user, false);

				if (!$loaded || $userapi->Get('forgotpasscode') != $code) {
					$this->ShowForgotForm('login_error', GetLang('BadLogin_Link'));
					break;
				}

				IEM::sessionSet('ForgotUser', $user);

				$this->ShowForgotForm_Step2($userapi->Get('username'));
			break;

			case 'login':
				$auth_system = new AuthenticationSystem();
				$username = IEM::requestGetPOST('ss_username', '');
				$password = IEM::requestGetPOST('ss_password', '');
				$result = $auth_system->Authenticate($username, $password);
				if ($result === -1) {
					$this->ShowLoginForm('login_error', GetLang('PleaseWaitAWhile'));
					break;
				} elseif ($result === -2) {
					$this->ShowLoginForm('login_error', GetLang('FreeTrial_Expiry_Login'));
					break;
				} elseif (!$result) {
					$this->ShowLoginForm('login_error', GetLang('BadLogin'));
					break;
				} elseif ($result && defined('IEM_SYSTEM_ACTIVE') && !IEM_SYSTEM_ACTIVE) {
					$msg = (isset($result['admintype']) && $result['admintype'] == 'a') ? 'ApplicationInactive_Admin' : 'ApplicationInactive_Regular';
					$this->ShowLoginForm('login_error', GetLang($msg));
					break;
				}

				$rememberdetails = IEM::requestGetPOST('rememberme', false);
				$rememberdetails = (bool)$rememberdetails;
                                
                                $user = false;
                                $rand_check = false;

				IEM::userLogin($result['userid']);

				$oneyear = 365 * 24 * 3600; // one year's time.

				$redirect = $this->_validateTakeMeToRedirect(IEM::requestGetPOST('ss_takemeto', 'index.php'));

				if ($rememberdetails) {
					if (!$user) { $user = IEM::userGetCurrent(); }
					if (!$rand_check) { $rand_check = uniqid(true); }
					$usercookie_info = array('user' => $user->userid, 'time' => time(), 'rand' => $rand_check, 'takemeto' => $redirect);
					IEM::requestSetCookie('IEM_CookieLogin', $usercookie_info, $oneyear);
					$usercookie_info = array('takemeto' => $redirect);
					IEM::requestSetCookie('IEM_LoginPreference', $usercookie_info, $oneyear);
				}



				header('Location: ' . SENDSTUDIO_APPLICATION_URL . '/admin/' . $redirect);
				exit();
			break;

			default:
				$msg = false; $template = false;
				if ($action == 'logout') {
					$this->LoadLanguageFile('Logout');
				}
				$this->ShowLoginForm($template, $msg);
			break;
		}
	}
Пример #13
0
 /**
  * CleanupPartialSends
  * Cleans up any sends that haven't been completed if a browser crashes or a user navigates away from the "send" process.
  *
  * This is needed so if a user gets to the last step and decides to not send a split test
  * or if they navigate away to another page,
  * it credits the user back with their now "used" email credits.
  *
  * @param EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES $data The data passed in contains an array of the current pagename which is used to work out whether to do anything or not.
  *
  * @return Void Doesn't return anything.
  * @uses EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES
  */
 public static function CleanupPartialSends(EventData_IEM_SENDSTUDIOFUNCTIONS_CLEANUPOLDQUEUES $data)
 {
     /**
      * We want to clean up the "job" if:
      * - we're not looking at an addons page
      * - if we are looking at an addon, make sure it's not the 'splittest' addon.
      * - if we are looking at the 'splittest' addon, make sure we're not in the middle of the 'send' process somewhere.
      */
     if ($data->page == 'addons') {
         if (isset($_GET['Addon']) && strtolower($_GET['Addon']) == 'splittest') {
             if (isset($_GET['Action']) && strtolower($_GET['Action']) === 'send') {
                 return;
             }
         }
     }
     $send_details = IEM::sessionGet('SplitTestSend_Cleanup');
     if (!$send_details || empty($send_details)) {
         return;
     }
     if (!isset($send_details['Job'])) {
         return;
     }
     $user = IEM::userGetCurrent();
     require_once dirname(__FILE__) . '/api/splittest_send.php';
     $send_api = new Splittest_Send_API();
     $send_api->DeleteJob($send_details['Job'], $send_details['splitid']);
     if (isset($send_details['Stats'])) {
         if (!class_exists('Stats_API', false)) {
             require_once SENDSTUDIO_API_DIRECTORY . '/stats.php';
         }
         $stats_api = new Stats_API();
         /**
          * Delete any left over stats.
          * 
          * These might have been created if the user is sending via the popup window
          * but they clicked 'cancel' on the last step.
          */
         $stats = array_values($send_details['Stats']);
         $stats_api->Delete($stats, 'n');
     }
     IEM::sessionRemove('SplitTestSend_Cleanup');
 }
Пример #14
0
	/**
	* Process
	* This works out where you are up to in the send process and takes the appropriate action. Most is passed off to other methods in this class for processing and displaying the right forms.
	*
	* @return Void Doesn't return anything.
	*/
	function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : null;
		$user = IEM::userGetCurrent();
		$access = $user->HasAccess('Newsletters', 'send');

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

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

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

		switch ($action) {
			case 'viewsenderrors':
				$job = (isset($_GET['Job'])) ? (int)$_GET['Job'] : 0;
				if (!$this->CanAccessJobs($job)) {
					$this->DenyAccess();
					return;
				}
				echo $this->PrintSendFailureReport($job);
			break;

			case 'view_report':
				$queueid = IEM::sessionGet('ReportQueue');

				$report_type = (isset($_GET['ReportType'])) ? strtolower($_GET['ReportType']) : null;
				switch ($report_type) {
					case '1':
						$GLOBALS['Heading'] = GetLang('SendProblem_Report_Subscriber_Problem_Heading');
						$GLOBALS['Intro'] = GetLang('SendProblem_Report_Subscriber_Problem_Intro');
					break;

					case '10':
						$GLOBALS['Heading'] = GetLang('SendProblem_Report_Email_Problem_Heading');
						$GLOBALS['Intro'] = GetLang('SendProblem_Report_Email_Problem_Intro');
					break;

					case '20':
						$GLOBALS['Heading'] = GetLang('SendProblem_Report_MailServer_Problem_Heading');
						$GLOBALS['Intro'] = GetLang('SendProblem_Report_MailServer_Problem_Intro');
					break;

					case '30':
						$GLOBALS['Heading'] = GetLang('SendProblem_Report_SMTPMailServer_Problem_Heading');
						$GLOBALS['Intro'] = GetLang('SendProblem_Report_SMTPMailServer_Problem_Intro');
					break;

					default:
						$GLOBALS['Heading'] = GetLang('SendProblem_Report_Invalid_Heading');
						$GLOBALS['Intro'] = GetLang('SendProblem_Report_Invalid_Intro');
						$GLOBALS['EmailList'] = GetLang('SendProblem_InvalidReportURL');
						$this->ParseTemplate('SendProblem_Report_Results_View');
					break 2;
				}

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

				$email_list = '';
				$problem_email_addresses = $api->GetUnsentSubscribers($queueid, $report_type);
				foreach ($problem_email_addresses as $emailaddress) {
					$email_list .= htmlspecialchars($emailaddress, ENT_QUOTES, SENDSTUDIO_CHARSET) . "\n";
				}
				$GLOBALS['EmailList'] = $email_list;
				$this->ParseTemplate('SendProblem_Report_Results_View');

			break;


			case 'pausesend':
				$job = (int)$_GET['Job'];
				if (!$this->CanAccessJobs($job)) {
					$this->DenyAccess();
					return;
				}

				$api = $this->GetApi('Jobs');
				$paused = $api->PauseJob($job);
				if ($paused) {
					$GLOBALS['Message'] = $this->PrintSuccess('Send_Paused_Success');
				} else {
					$GLOBALS['Error'] = GetLang('Send_Paused_Failure');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				}
				$this->ParseTemplate('Send_Step5_Paused');
			break;

			case 'sendfinished':
				$job = (int)$_GET['Job'];
				if (!$this->CanAccessJobs($job)) {
					$this->DenyAccess();
					return;
				}

				$send_details = IEM::sessionGet('SendDetails');

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

				$statsapi->MarkNewsletterFinished($send_details['StatID'], $send_details['SendSize']);

				$timetaken = $send_details['SendEndTime'] - $send_details['SendStartTime'];
				$timedifference = $this->TimeDifference($timetaken);

				$GLOBALS['SendReport_Intro'] = sprintf(GetLang('SendReport_Intro'), $timedifference);

				$sendreport = '';
				if ($send_details['EmailResults']['success'] > 0) {
					if ($send_details['EmailResults']['success'] == 1) {
						$sendreport .= $this->PrintSuccess('SendReport_Success_One');
					} else {
						$sendreport .= $this->PrintSuccess('SendReport_Success_Many', $this->FormatNumber($send_details['EmailResults']['success']));
					}
				}

				$this->PrintSendFailureReport($job, $sendreport);

				$api = $this->GetApi('Jobs');
				$api->FinishJob($job);
				$api->ClearQueue($send_details['SendQueue'], 'send');
			break;

			case 'send':
				IEM::sessionRemove('ApproveJob');
				API_USERS::creditEvaluateWarnings($user->GetNewAPI());

				$jobid = (int)$_GET['Job'];

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

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

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

				if (!isset($_GET['Started'])) {
					$jobApi->StartJob($jobid);
				}

				$sendqueue = $jobApi->GetJobQueue($jobid);

				$send_api = $this->GetApi('Send');

				$job = $jobApi->LoadJob($jobid);

				$send_api->Set('statid', $send_api->LoadStats($jobid));

				$send_api->Set('jobdetails', $job['jobdetails']);
				$send_api->Set('jobowner', $job['ownerid']);

				if (isset($_GET['Resend'])) {
					// this function handles moving everyone onto the 'live' queue etc so we don't need to worry about any of that.
					$send_api->ResendJob_Setup($jobid);
				}

				$queuesize = $jobApi->QueueSize($sendqueue, 'send');

				$send_details = IEM::sessionGet('SendDetails');

				$send_details['SendQueue'] = $sendqueue;

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

				$timediff = ($timenow - $send_details['SendStartTime']);

				$time_so_far = $this->TimeDifference($timediff);

				$num_left_to_send = $send_details['SendSize'] - $queuesize;

				if ($num_left_to_send > 0) {
					$timeunits = $timediff / ($num_left_to_send);
					$timediff = ($timeunits * $queuesize);
				} else {
					$timediff = 0;
				}
				$timewaiting = $this->TimeDifference($timediff);

				$GLOBALS['SendTimeSoFar'] = sprintf(GetLang('Send_TimeSoFar'), $time_so_far);
				$GLOBALS['SendTimeLeft'] = sprintf(GetLang('Send_TimeLeft'), $timewaiting);

				if ($queuesize <= 0) {
					$email = $this->GetApi('Email');
					if (SENDSTUDIO_SAFE_MODE) {
						$email->Set('imagedir', TEMP_DIRECTORY . '/send');
					} else {
						$email->Set('imagedir', TEMP_DIRECTORY . '/send.' . $jobid . '.' . $sendqueue);
					}
					$email->CleanupImages();

					$send_details['SendEndTime'] = AdjustTime(0, true, null, true);
					IEM::sessionSet('SendDetails', $send_details);

					$GLOBALS['Send_NumberLeft'] = GetLang('SendFinished');
					$this->ParseTemplate('Send_Step5');
					?>
						<script>
							window.opener.focus();
							window.opener.document.location = 'index.php?Page=Send&Action=SendFinished&Job=<?php echo $jobid; ?>&r=<?php echo time(); ?>';
							window.close();
						</script>
					<?php
					break;
				}

				if ($queuesize == 1) {
					$GLOBALS['Send_NumberLeft'] = GetLang('Send_NumberLeft_One');
				} else {
					$GLOBALS['Send_NumberLeft'] = sprintf(GetLang('Send_NumberLeft_Many'), $this->FormatNumber($queuesize));
				}

				if ($num_left_to_send == 1) {
					$GLOBALS['Send_NumberAlreadySent'] = GetLang('Send_NumberSent_One');
				} else {
					$GLOBALS['Send_NumberAlreadySent'] = sprintf(GetLang('Send_NumberSent_Many'), $this->FormatNumber($num_left_to_send));
				}

				$send_api->SetupJob($jobid, $sendqueue);

				$recipients = $send_api->FetchFromQueue($sendqueue, 'send', 1, 1);

				$send_api->SetupDynamicContentFields($recipients);

				$send_api->SetupCustomFields($recipients);

				$sent_ok = false;

				foreach ($recipients as $p => $recipientid) {
					$send_results = $send_api->SendToRecipient($recipientid, $sendqueue);

					// save the info in the session, then see if we need to pause between each email.
					if ($send_results['success'] > 0) {
						$sent_ok = true;
						$send_details['EmailResults']['success']++;
					} else {
						$send_details['EmailResults']['failure']++;
					}
					$send_details['EmailResults']['total']++;
					IEM::sessionSet('SendDetails', $send_details);
				}

				$GLOBALS['JobID'] = $jobid;

				$template = $this->ParseTemplate('Send_Step5', true);
				$template .= $this->PrintFooter(true, true);
				echo $template;

				// we should only need to pause if we successfully sent.
				if ($sent_ok) {
					$send_api->Pause();
				}
				exit;
			break;

			case 'step4':
				$newsletter_chosen = $_POST['newsletter'];
				if ($newsletter_chosen == 0) {
					$this->SelectNewsletter(GetLang('Send_Step4_ChooseNewsletter'));
					break;
				}

				if (!$this->CanAccessNewsletter($newsletter_chosen)) {
					$this->DenyAccess();
					break;
				}

				$send_details = IEM::sessionGet('SendDetails');

				$send_details['Multipart'] = (isset($_POST['sendmultipart'])) ? 1 : 0;
				$send_details['TrackOpens'] = (isset($_POST['trackopens'])) ? 1 : 0;
				$send_details['TrackLinks'] = (isset($_POST['tracklinks'])) ? 1 : 0;
				$send_details['EmbedImages'] = (isset($_POST['embedimages'])) ? 1 : 0;
				$send_details['Newsletter'] = $_POST['newsletter'];
				$send_details['SendFromName'] = $_POST['sendfromname'];
				$send_details['SendFromEmail'] = $_POST['sendfromemail'];
				$send_details['ReplyToEmail'] = (isset($_POST['replytoemail'])) ? $_POST['replytoemail'] : $send_details['SendFromEmail'];
				$send_details['BounceEmail'] = (isset($_POST['bounceemail'])) ? $_POST['bounceemail'] : $send_details['SendFromEmail'];

				$newsletterapi = $this->GetApi('Newsletters');
				$newsletterapi->Load($send_details['Newsletter']);
				$archive = $newsletterapi->Archive();
				if(empty($archive)) {
					$GLOBALS['Messages'] = $this->PrintWarning('SendNewsletterArchive_DeactivatedWarning');
				}

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

				$send_details['To_FirstName'] = $to_firstname;

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

				$send_details['To_LastName'] = $to_lastname;

				$send_details['Charset'] = SENDSTUDIO_CHARSET;

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

				$send_details['SendStartTime'] = AdjustTime(0, true, null, true);

				$send_details['EmailResults']['success'] = 0;
				$send_details['EmailResults']['total'] = 0;
				$send_details['EmailResults']['failure'] = 0;

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

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

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

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

				$subscriber_count = $send_details['SendSize'];

				$approved = $user->Get('userid');

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

				$newsletter_size = 0;
				$html_size = utf8_strlen($newsletterApi->Get('htmlbody'));
				$text_size = utf8_strlen($newsletterApi->Get('textbody'));

				// if you are sending multipart, then put both parts together to work out an approximate size.
				if ($send_details['Multipart']) {
					$newsletter_size += $html_size + $text_size;
				} else {
					// if you are not sending multipart, then try to work out the html part (as a guide for maximum size).
					if ($html_size > 0) {
						$newsletter_size += $html_size;
					} else {
						$newsletter_size += $text_size;
					}
				}

				$attachments = $this->GetAttachments('newsletters', $send_details['Newsletter'], true);
				if (isset($attachments['filelist'])) {
					foreach ($attachments['filelist'] as $p => $attachment) {
						$file = $attachments['path'] . '/' . $attachment;
						// base64 encoding adds about 30% overhead so we need to add it here.
						$newsletter_size += 1.3 * filesize($file);
					}
				}

				$email_api = $this->GetApi('Email');

				$problem_images = array();

				// we'll do a quick check for the images in the html content to make sure they all work.
				$email_api->Set('EmbedImages', true);
				$email_api->AddBody('html', $newsletterApi->Get('htmlbody'));
				$images = $email_api->GetImages();
				if (is_array($images) && !empty($images)) {
					$max_image_count = $this->max_image_count;

					$counter = 0;
					$total_image_size = 0;
					$image_exceed_threshold = (count($images) > $max_image_count);

					foreach ($images as $md5 => $image_url) {
						list($img, $error) = $email_api->GetImage($image_url);
						$image_size = 1.3 * strlen($img);
						if ($img) {
							if ($send_details['EmbedImages']) {
								// base64 encoding adds about 30% overhead so we need to add it here.
								$newsletter_size += $image_size;
							}
						} else {
							$problem_images[] = array('img' => $image_url, 'error' => $error);
						}

						// Images exceed "max image count" threshold....
						// We will need to do something about it so that the application doesn't timeout
						if ($image_exceed_threshold) {
							$total_image_size += $image_size;

							if (++$counter >= $max_image_count) {
								$temp = sprintf(GetLang('CannotVerifyAllImages_ExceedThreshold'), $max_image_count);
								$temp .= sprintf(GetLang('CannotVerifyAllImages_OnlyThresholdImagesVerified'), $max_image_count);

								$problem_images[] = $temp;
								if ($send_details['EmbedImages']) {
									$problem_images[] = sprintf(GetLang('CannotVerifyAllImages_SendSizeEstimated'));

									$average_image_size = ($total_image_size / $max_image_count);
									$total_image_count = count($images);
									$newsletter_size += abs($average_image_size * ($total_image_count - $max_image_count));
								}
								break;
							}
						}
					}
				}

				$img_warning = '';

				if (!empty($problem_images)) {
					foreach ($problem_images as $problem_details) {
						if (is_array($problem_images)) {
							$img_warning .= sprintf(GetLang('UnableToLoadImage'), $problem_details['img'], $problem_details['img'], $problem_details['error']);
						} else {
							$img_warning .= "- {$problem_details}<br/>";
						}
					}
				}

				if ($img_warning) {
					if ($send_details['EmbedImages']) {
						$warning_var = 'UnableToLoadImage_Newsletter_List_Embed';
					} else {
						$warning_var = 'UnableToLoadImage_Newsletter_List';
					}
					$GLOBALS['ImageWarning'] = $this->PrintWarning($warning_var, $img_warning);
				}

				if (SENDSTUDIO_EMAILSIZE_MAXIMUM > 0) {
					if ($newsletter_size >= (SENDSTUDIO_EMAILSIZE_MAXIMUM*1024)) {
						$this->SelectNewsletter(sprintf(GetLang('Newsletter_Size_Over_EmailSize_Maximum'), $this->EasySize(SENDSTUDIO_EMAILSIZE_MAXIMUM*1024, 0)));
						break;
					}
				}

				if (($subcount = IEM::sessionGet('SendSize_Many_Extra', false)) === false) {
					$subcount = $subscriber_count;
				}

				$GLOBALS['ApproximateSendSize'] = sprintf(GetLang('Newsletter_SendSize_Approximate'), $this->EasySize($newsletter_size, 0), $this->EasySize($newsletter_size * $subcount, 1));

				if (SENDSTUDIO_EMAILSIZE_WARNING > 0) {
					if ($newsletter_size > (SENDSTUDIO_EMAILSIZE_WARNING*1024)) {
						$GLOBALS['EmailSizeWarning'] = $this->PrintWarning('Newsletter_Size_Over_EmailSize_Warning_Send', $this->EasySize((SENDSTUDIO_EMAILSIZE_WARNING*1024), 0));
					}
				}

				if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
					$sendtime = $_POST['sendtime'];

					if (isset($_POST['sendimmediately']) && $_POST['sendimmediately'] == '1') {
						/*
						* Set the date/time to now if sendimmediately was ticked
						*/
						$time_now = AdjustTime(0, true, null, true);
						$sendtime = AdjustTime($time_now, false, 'h:iA');
						$_POST['datetime']['year'] = AdjustTime($time_now,false,'Y');
						$_POST['datetime']['month'] = AdjustTime($time_now,false,'n');
						$_POST['datetime']['day'] = AdjustTime($time_now,false,'j');
					}

					/*
					* the sendtime is in this format:
					* hr:minAM
					* so we need to look at the character positions rather than exploding on the separator.
					*/
					$hr = substr($sendtime, 0, 2);
					$minute = substr($sendtime, 3, 2);
					$ampm = substr($sendtime, -2);

					if (strtolower($ampm) == 'pm') {
						if ($hr != 12) {
							$hr = $hr + 12;
						}
					}

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

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

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

					$five_mins_ago = $statsapi->GetServerTime() - (5*60);

					if ($check_schedule_time < $five_mins_ago) {
						$this->SelectNewsletter(GetLang('Send_Step4_CannotSendInPast'));
						break;
					}

					$send_criteria = $send_details['SendCriteria'];

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

					$scheduletime = AdjustTime($server_schedule_time, true);
					
					/**
					* Since we're using scheduled sending, we need to check user stats for when this is scheduled to send.
					*/
					$check_stats = $statsapi->CheckUserStats($user, $subscriber_count, $scheduletime);

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

					if (!$ok_to_send) {
						echo $this->PrintError($not_ok_to_send_reason);
						// Please refer to Mitch about why I comment this out
						//$this->FilterRecipients($send_details['Lists'], GetLang($not_ok_to_send_reason));
						break;
					}

					$send_details['SendStartTime'] = $scheduletime;

					/**
					 * Store required tracker variables in send details
					 */
					if (check($this, 'mailTrack', true)) {
						if ($this->GetApi('module_TrackerFactory', false)) {
							$list = module_Tracker::GetRequestOptionNamesForAllTracker();
							foreach ($list as $each) {
								if (isset($_POST[$each])) {
									$send_details[$each] = $_POST[$each];
								}
							}
						}
					}
					
				}

				/**
				* see if they have hit refresh on this last step.
				* if they have, then there will already be an approvejob session variable.
				*
				* If there is one there already, clean it up.
				* Give the user back their email credits and delete the stats etc.
				*/
				$job_already_started = IEM::sessionGet('ApproveJob');

				if ($job_already_started) {

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

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

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

					$statsapi->Delete($statid, 'n');
					$jobapi->PauseJob($job_already_started);
					$jobapi->Delete($job_already_started);

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

				$jobcreated = $jobapi->Create('send', $scheduletime, $user->userid, $send_details, 'newsletter', $send_details['Newsletter'], $send_details['Lists'], $approved);

				IEM::sessionSet('ApproveJob', $jobcreated);

				IEM::sessionSet('JobSendSize', $subscriber_count);

				// if we're not using scheduled sending, create the queue and start 'er up!
				if (!SENDSTUDIO_CRON_ENABLED || SENDSTUDIO_CRON_SEND <= 0) {
					/**
					* Record the user stats for this send.
					* We have to do it here so you can't schedule multiple sends and then it records everything.
					*/
					$statsapi->RecordUserStats($user->userid, $jobcreated, $subscriber_count, $scheduletime);
					
					$subscriberApi = $this->GetApi('Subscribers');

					$sendqueue = $subscriberApi->CreateQueue('Send');

					$jobapi->StartJob($jobcreated);

					$queuedok = $jobapi->JobQueue($jobcreated, $sendqueue);

					$send_criteria = $send_details['SendCriteria'];

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

					if (isset($send_details['Segments']) && is_array($send_details['Segments'])) {
						$subscriberApi->GetSubscribersFromSegment($send_details['Segments'], false, $queueinfo, 'nosort');
					} else {
						$subscriberApi->GetSubscribers($send_criteria, array(), false, $queueinfo, $user->userid);
					}

					if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
						$subscriberApi->Db->OptimizeTable(SENDSTUDIO_TABLEPREFIX . "queues");
					}

					$subscriberApi->RemoveDuplicatesInQueue($sendqueue, 'send', $send_details['Lists']);

					$subscriberApi->RemoveBannedEmails($send_details['Lists'], $sendqueue, 'send');

					$subscriberApi->RemoveUnsubscribedEmails($send_details['Lists'], $sendqueue, 'send');

					if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
						$subscriberApi->Db->OptimizeTable(SENDSTUDIO_TABLEPREFIX . "queues");
					}

					$send_details['SendSize'] = $subscriberApi->QueueSize($sendqueue, 'send');

					$newsletterstats = $send_details;
					$newsletterstats['Job'] = $jobcreated;
					$newsletterstats['Queue'] = $sendqueue;
					$newsletterstats['SentBy'] = $queueinfo['ownerid'];

					$statid = $statsapi->SaveNewsletterStats($newsletterstats);

					/**
					 * Process tracker request hwere because cron was not enabled
					 * @todo Result for the call to module_Tracker::ParseOptionsForAllTracker() is not being processed and being ignored
					 */
					if (check($this, 'TrackAllLinks', true)) {
						if ($this->GetApi('module_TrackerFactory', false)) {
							$temp = array_merge($_POST, array(	'statid'		=> $statid,
																'stattype'		=> 'newsletter',
																'newsletterid'	=> $send_details['Newsletter']));

							$status = module_Tracker::ParseOptionsForAllTracker($temp);
						}
					}

					$send_details['StatID'] = $statid;

					/**
					* So we can link user stats to send stats, we need to update it.
					*/
					$statsapi->UpdateUserStats($user->userid, $jobcreated, $statid);

					$jobapi->PauseJob($jobcreated);

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

					$GLOBALS['JobID'] = $jobcreated;
				}

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

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

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

				$last_sent_details = $newsletterApi->GetLastSent($send_details['Newsletter']);

				$last_sent = $last_sent_details['starttime'];
				if ($last_sent <= 0 && $send_details['SendSize'] > 5) {
					$GLOBALS['SentToTestListWarning'] = $this->PrintWarning('SendToTestListWarning');
				}

				$SendInfo = IEM::sessionGet('SendInfoDetails');

				if (SENDSTUDIO_CRON_ENABLED && SENDSTUDIO_CRON_SEND > 0) {
					/**
					* Record the user stats for this send.
					* We have to do it here so you can't schedule multiple sends and then it records everything.
					*/
					$statsapi->RecordUserStats($user->userid, $jobcreated, $subscriber_count, $scheduletime);
					
					$GLOBALS['Send_ScheduleTime'] = sprintf(GetLang('JobScheduled'), $this->PrintTime($scheduletime));
					$GLOBALS['Send_TotalRecipients'] = sprintf(GetLang('Send_TotalRecipients_Cron'), $this->FormatNumber($SendInfo['Count']));

					$this->ParseTemplate('Send_Step4_Cron');
					break;
				}

				$GLOBALS['Send_TotalRecipients'] = sprintf(GetLang('Send_TotalRecipients'), $this->FormatNumber($newsletterApi->QueueSize($sendqueue, 'send')));

				$this->ParseTemplate('Send_Step4');
			break;

			case 'step3':
				$this->Step3();
			break;

			case 'step2':
				$filteringOption = 0;
				$lists = array();
				$segments = array();

				if (isset($_POST['ShowFilteringOptions'])) {
					$filteringOption = intval($_POST['ShowFilteringOptions']);
					if ($filteringOption != 0) {
						$user->SetSettings('ShowFilteringOptions', $filteringOption);
					}
				}

				if ($filteringOption == 3 && !$user->HasAccess('Segments', 'Send')) {
					$filteringOption = 1;
				}

				switch ($filteringOption) {
					// This is when a list is selected
					case 1:
					case 2:
						if (isset($_POST['lists'])) {
							$lists = $_POST['lists'];
						}
					break;

					// This is when a segment is selected
					case 3:
						if (isset($_POST['segments']) && is_array($_POST['segments'])) {
							$segments = $_POST['segments'];
						}
					break;

					// A list/segment can be selected using "GET" request
					default:
						if (isset($_GET['list'])) {
							$lists = array((int)$_GET['list']);
							$filteringOption = 1;
							$user->SetSettings('ShowFilteringOptions', 1);
						} elseif (isset($_GET['segment'])) {
							$segments = array(intval($_GET['segment']));
							$filteringOption = 3;
							$user->SetSettings('ShowFilteringOptions', 3);
						}
					break;

				}

				if ($filteringOption == 1 || $filteringOption == 2) {
					if (empty($lists)) {
						$GLOBALS['Error'] = GetLang('Send_Step1_ChooseListToSendTo');
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						$this->ChooseList('Send', 'step2', false);
						break;
					}

					if (!$user->Admin()) {
						$availabeLists = $user->GetLists();

						if (is_array($availabeLists)) {
							$availabeLists = array_keys($availabeLists);
						} else {
							$this->ChooseList('Send', 'step2', false);
							break;
						}

						$intersects = array_intersect($lists, $availabeLists);
						if (count($lists) != count($intersects)) {
							$this->ChooseList('Send', 'step2', false);
							break;
						}
					}
				}

				if ($filteringOption == 1) {
					$this->FilterRecipients($lists);
				} elseif ($filteringOption == 2) {
					$send_details = IEM::sessionGet('SendDetails');

					$send_details['Lists'] = $lists;
					$send_details['SendCriteria'] = array('Confirmed' => 1);
					$send_details['SendSize'] = null;
					$send_details['BackStep'] = 1;

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

					$this->Step3();
				} else {
					if (empty($segments)) {
						$GLOBALS['Error'] = GetLang('Send_Step1_ChooseSegmentToSendTo');
						$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
						$this->ChooseList('Send', 'step2', false);
						break;
					}

					if (!$user->Admin()) {
						$availableSegments = $user->GetSegmentList();

						if (!empty($availableSegments)) {
							$availableSegments = array_keys($availableSegments);
						}

						foreach ($segments as $segment) {
							if (!in_array($segment, $availableSegments)) {
								$this->DenyAccess();
								exit();
							}
						}
					}

					$send_details = IEM::sessionGet('SendDetails');

					$send_details['Lists'] = null;
					$send_details['SendCriteria'] = array();
					$send_details['SendSize'] = null;
					$send_details['Segments'] = $segments;

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

					$this->Step3();
				}
			break;

			case 'resumesend':
				$this->ResumeSend();
			break;

			case 'resend':
				$this->ResendJob();
			break;

			default:
				IEM::sessionRemove('SendDetails');

				$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
				if (!$this->CanAccessNewsletter($id)) {
					$id = 0;
				}

				$senddetails['NewsletterChosen'] = $id;

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

				$newsletterapi = $this->GetApi('Newsletters');

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

				$newsletters = $newsletterapi->GetLiveNewsletters($newsletterowner);
				if (empty($newsletters)) {
					$all_newsletters = $newsletterapi->GetNewsletters($newsletterowner, array(), true);
					if ($all_newsletters < 1) {
						if ($user->HasAccess('Newsletters', 'Create')) {
							$GLOBALS['Message'] = $this->PrintSuccess('NoNewsletters', GetLang('NoNewsletters_HasAccess'));

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

						} else {
							$GLOBALS['Message'] = $this->PrintSuccess('NoNewsletters', '');
						}
					} else {
						if ($user->HasAccess('Newsletters', 'Approve')) {
							$GLOBALS['Message'] = $this->PrintSuccess('NoLiveNewsletters', GetLang('NoLiveNewsletters_HasAccess'));
						} else {
							$GLOBALS['Message'] = $this->PrintSuccess('NoLiveNewsletters', '');
						}
					}
					$this->ParseTemplate('Newsletters_Send_Empty');
					break;
				}
				$this->ChooseList('Send', 'step2', false);
			break;
		}
		$this->PrintFooter($popup);
	}
Пример #15
0
 public static function langLoad($language)
 {
     $user = IEM::userGetCurrent();
     $user_language = 'default';
     $language = strtolower($language);
     if (in_array($language, self::$_langLoaded)) {
         return true;
     }
     if (!empty($user->user_language)) {
         $users_language = $user->user_language;
     }
     if (empty($users_language) || !is_dir(IEM_PATH . "/language/{$users_language}")) {
         $users_language = 'default';
     }
     $langfile = IEM_PATH . "/language/{$users_language}/{$language}.php";
     if (!is_file($langfile)) {
         trigger_error("No Language file for {$language} area", E_USER_WARNING);
         return false;
     }
     include_once $langfile;
     self::$_langLoaded[] = $language;
     return true;
 }
Пример #16
0
	/**
	* Constructor
	* Initialize the image directory
	*
	* @return Void
	*/
	function __construct() {
		if(is_null($this->user)){$this->user = IEM::userGetCurrent();}
		$userid = $this->user->userid;
		$this->imageDirectory = '/user/'   . $userid;
		//added userimageDirectory as a permanent place holder for the user's folder -  imageDirectory will change inside Init
		$this->userimageDirectory = '/user/'   . $userid;
		//---
		if(!file_exists(TEMP_DIRECTORY  . $this->imageDirectory)){
			CreateDirectory(TEMP_DIRECTORY  . $this->imageDirectory, TEMP_DIRECTORY, 0777);
		}
	}