Exemplo n.º 1
0
                SendResponse(false, "Unable to load field id '" . $details['fieldid'] . "'");
                exit;
            }

            // See if specific custom fields need data transformation
            switch ($customfields_api->fieldtype) {
                // Custom fields that require multiple values need to be converted to array
                case 'checkbox':
                    if (!is_array($details['value'])) {
                        $details['value'] = array($details['value']);
                    }
                break;
                
                 case 'date':
                    require_once(SENDSTUDIO_API_DIRECTORY.'/customfields_date.php');
                    $cfdateapi = new CustomFields_Date_API($details['fieldid']);
                    $details['value'] = $cfdateapi->CheckData($details['value'],true);
                    if($details['value'] !== false){$details['value'] = $details['value'][0]."/".$details['value'][1]."/".$details['value'][2];}
                 break;

                // All other custom fields
                default:
                break;
            }

            if($details['value'] !== false){
                $valid_value = $customfields_api->ValidData($details['value']);
            }else{
                $valid_value = false;
            }
            if (!$valid_value) {
	/**
	 * _send
	 *
	 * Send email campaign that is triggered by the "trigger email".
	 *
	 * @param Array $triggerrecord Trigger record
	 * @param Array $queuerecord Queue record
	 * @param Array $newsletter Newsletter record
	 * @return Array Returns a status result that contains the sending result, and the email address that get sent
	 */
	private function _send($triggerrecord, $queuerecord, $newsletter)
	{
		static $prevUserID = 0;
		static $prevQueueID = 0;
		static $userPause = 0;
		static $subscriberAPI = null;

		$triggerid = $triggerrecord['triggeremailsid'];
		$newsletterid = $newsletter['newsletterid'];
		$recipientid = $queuerecord['recipient'];
		$user = null;
		$email = null;
		$customfields = array();

		$return = array(
			'email'		=> '',
			'message'	=> '',
			'listid'	=> 0,
			'result'	=> false
		);

		if (is_null($subscriberAPI)) {
			$subscriberAPI = new Subscribers_API();
		}

		/**
		 * Get owner of trigger email
		 */
			$user = $this->_cacheUser($triggerrecord['ownerid']);
			if (empty($user)) {
				trigger_error('Cannot get trigger owner record', E_USER_NOTICE);
				return $return;
			}
		/**
		 * -----
		 */

		/**
		 * Get email object, and setup
		 * This will setup emails and setup everything that it needs to have according to the newsletter record.
		 */
			$email = new SS_Email_API();

			$email->Set('CharSet', SENDSTUDIO_CHARSET);
			if (!SENDSTUDIO_SAFE_MODE) {
				$email->Set('imagedir', TEMP_DIRECTORY . '/triggeremails.' . $triggerrecord['queueid']);
			} else {
				$email->Set('imagedir', TEMP_DIRECTORY . '/send');
			}

			if (SENDSTUDIO_FORCE_UNSUBLINK) {
				$email->ForceLinkChecks(true);
			}

			$email->Set('Subject', $newsletter['subject']);

			/**
			 * Setup attachments
			 */
				$email->ClearAttachments();
				$tempAttachments = SendStudio_Functions::GetAttachments('newsletters', $newsletterid, true);
				if ($tempAttachments) {
					$path = $tempAttachments['path'];
					$files = $tempAttachments['filelist'];
					foreach ($files as $p => $file) {
						$email->AddAttachment($path . DIRECTORY_SEPARATOR . $file);
					}
				}
			/**
			 * -----
			 */

			/**
			 * Set up the contents of the newsletter and the formatting (ie. multipart/html only/text only)
			 */
				$format = $newsletter['format'];

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

				if ($format == 'b' || $format == 't') {
					if ($newsletter['textbody']) {
						$email->AddBody('text', $newsletter['textbody']);
						$email->AppendBody('text', $user->Get('textfooter'));
						$email->AppendBody('text', stripslashes(SENDSTUDIO_TEXTFOOTER));
					}
				}

				if ($format == 'b' || $format == 'h') {
					if ($newsletter['htmlbody']) {
						$email->AddBody('html', $newsletter['htmlbody']);
						$email->AppendBody('html', $user->Get('htmlfooter'));
						$email->AppendBody('html', stripslashes(SENDSTUDIO_HTMLFOOTER));
					}
				}

				if ($format == 'b') {
					if ($newsletter['textbody'] && $newsletter['htmlbody']) {
						$email->Set('Multipart', true);
					} else {
						$email->Set('Multipart', false);
					}
				}
			/**
			 * -----
			 */

			// Setup custom fields
			$customfields = $email->GetCustomFields();

			if (!is_a($email, 'SS_Email_API')) {
				trigger_error('Cannot instantiate email object to be used to send emails', E_USER_NOTICE);
				return $return;
			}

			$email->Debug = $this->_debugMode;
		/**
		 * -----
		 */


		/**
		 * Set up email object for any headers and SMTP server details.
		 * These setup will take account of each trigger records (ie. owner and user as well as stats and other sending related headers)
		 */
			/**
			 * Calculate pause time to make sure it complies with the throttling
			 */
				$pause = $pausetime = 0;
				if ($user->perhour > 0) {
					$pause = $user->perhour;
				}

				// in case the system rate is less than the user rate, lower it.
				if (SENDSTUDIO_MAXHOURLYRATE > 0) {
					if ($pause == 0) {
						$pause = SENDSTUDIO_MAXHOURLYRATE;
					} else {
						$pause = min($pause, SENDSTUDIO_MAXHOURLYRATE);
					}
				}

				if ($pause > 0) {
					$pausetime = 3600 / $pause;
				}
				$userPause = $pausetime;
				$this->_log('UserPause is set to ' . $pausetime);
			/**
			 * -----
			 */

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

			if ($user->smtpserver) {
				$email->SetSmtp($user->smtpserver, $user->smtpusername, $user->smtppassword, $user->smtpport);
			}

			// If queue has changed since previous send, update email class for queue related information
			$email->TrackOpens((array_key_exists('trackopens', $triggerrecord['triggeractions']['send']) && $triggerrecord['triggeractions']['send']['trackopens'] == '1'));
			$email->TrackLinks((array_key_exists('tracklinks', $triggerrecord['triggeractions']['send']) && $triggerrecord['triggeractions']['send']['tracklinks'] == '1'));

			$email->Set('statid',			$triggerrecord['statid']);

			$email->Set('FromName',			$triggerrecord['triggeractions']['send']['sendfromname']);
			$email->Set('FromAddress',		$triggerrecord['triggeractions']['send']['sendfromemail']);
			$email->Set('ReplyTo',			$triggerrecord['triggeractions']['send']['replyemail']);
			$email->Set('BounceAddress',	$triggerrecord['triggeractions']['send']['bounceemail']);

			$email->Set('EmbedImages',		((array_key_exists('embedimages', $triggerrecord['triggeractions']['send'])) && $triggerrecord['triggeractions']['send']['embedimages'] == '1'));
			$email->Set('Multipart',		((array_key_exists('multipart', $triggerrecord['triggeractions']['send'])) && $triggerrecord['triggeractions']['send']['multipart'] == '1'));
		/**
		 * -----
		 */


		/**
		 * Set up recipient
		 */
			$subscriberinfo = $subscriberAPI->LoadSubscriberList($recipientid, 0, true);
            
			if (empty($subscriberinfo)) {
				trigger_error('Cannot fetch recipient details', E_USER_NOTICE);
				return $return;
			}

			$listinfo = $this->_cacheListGet($subscriberinfo['listid']);
			if (empty($listinfo)) {
                trigger_error('Unable to load recipient list details', E_USER_NOTICE);
				return $return;
			}

			// List ID for the particualar subscriber
			$email->Set('listids', $subscriberinfo['listid']);

			$subscriberinfo['ipaddress'] = $subscriberinfo['confirmip'];
			if (!$subscriberinfo['ipaddress']) {
				$subscriberinfo['ipaddress'] = $subscriberinfo['requestip'];
			}
			if (!$subscriberinfo['ipaddress']) {
				$subscriberinfo['ipaddress'] = '';
			}

			$subscriberinfo['subscriberid'] = $recipientid;
			$subscriberinfo['newsletter'] = $triggerrecord['triggeractions']['send']['newsletterid'];
			$subscriberinfo['listid'] = $subscriberinfo['listid'];
			$subscriberinfo['statid'] = $triggerrecord['statid'];
			$subscriberinfo['listname'] = $listinfo['name'];
			$subscriberinfo['companyname'] = $listinfo['companyname'];
			$subscriberinfo['companyaddress'] = $listinfo['companyaddress'];
			$subscriberinfo['companyphone'] = $listinfo['companyphone'];

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

				/**
				* If the subscriber has no custom fields coming from the database, then set up blank placeholders.
				* If they have no custom fields in the database, they have no records in the 'all_customfields' array - so we need to fill it up with blank entries.
				*/
				foreach ($customfields as $fieldid => $fieldname) {
					$subscriberinfo['CustomFields'][] = array(
						'fieldid' => $fieldid,
						'fieldname' => $fieldname,
						'fieldtype' => 'text',
						'defaultvalue' => '',
						'fieldsettings' => '',
						'subscriberid' => $recipientid,
						'data' => ''
					);
				}
			} else {
                require_once(SENDSTUDIO_API_DIRECTORY.'/customfields_date.php');
 
                foreach($subscriberinfo['CustomFields'] as $ar_key => $ar_value){
                    if($ar_value['fieldtype'] == 'date'){
                        $cfdateapi = new CustomFields_Date_API($ar_value['fieldid']);
                        $real_order = $cfdateapi->GetRealValue($ar_value['data']);
                        $subscriberinfo['CustomFields'][$ar_key]['data'] = $real_order;
                    }
                }           
			}

			// TODO refactor
				$name = '';
				$firstname_field = $triggerrecord['triggeractions']['send']['firstnamefield'];
				if ($firstname_field) {
					foreach ($subscriberinfo['CustomFields'] as $p => $details) {
						if ($details['fieldid'] == $firstname_field && $details['data'] != '') {
							$name = $details['data'];
							break;
						}
					}
				}

				$lastname_field = $triggerrecord['triggeractions']['send']['lastnamefield'];
				if ($lastname_field) {
					foreach ($subscriberinfo['CustomFields'] as $p => $details) {
						if ($details['fieldid'] == $lastname_field && $details['data'] != '') {
							$name .= ' ' . $details['data'];
							break;
						}
					}
				}

				if (trim($name) == '') {
					$name = false;
				}
			// --

	            // SetupDynamicContentFields
	            $dctEventListId = (is_array($subscriberinfo['listid']))?$subscriberinfo['listid']:array($subscriberinfo['listid']);
	            $dctEvent =new EventData_IEM_ADDON_DYNAMICCONTENTTAGS_REPLACETAGCONTENT();
	            $dctEvent->lists = $dctEventListId;
	            $dctEvent->info = array($subscriberinfo);
	            $dctEvent->trigger();
	            // --

			$email->ClearRecipients();
			$email->AddRecipient($subscriberinfo['emailaddress'], $name, $subscriberinfo['format'], $subscriberinfo['subscriberid']);
			$email->AddDynamicContentInfo($dctEvent->contentTobeReplaced);
			$email->AddCustomFieldInfo($subscriberinfo['emailaddress'], $subscriberinfo);

			$status = $email->Send(true, true);
			if (!$status['success']) {
				list($return['email'], $return['message']) = $status['fail'][0];
                trigger_error("Failed sending trigger email to {$return['email']}: {$return['message']}");
				return $return;
			}

			$return['listid'] = $subscriberinfo['listid'];
			$return['email'] = $subscriberinfo['emailaddress'];
		/**
		 * -----
		 */

		// Set previous user
		$prevUserID = $user->userid;

		// Set previous queue
		$prevQueueID = $triggerrecord['queueid'];

		$return['result'] = true;

		return $return;
	}
Exemplo n.º 3
0
	/**
	* CleanVersion
	* Cleans up placeholders from the content passed in. If no subscriber information is passed in, it will replace placeholders with '#' so for example an unsubscribe link can't be clicked on from an rss feed if you are not a valid subscriber.
	*
	* @param String $content The content to "clean up".
	* @param Array $subscriberinfo The subscriber information to use to clean up the content. If this is not present, placeholders will be replaced with a '#'.
	*
	* @return String The new content either with proper placeholders or invalid placeholders.
	*/
	function CleanVersion($content='', $subscriberinfo=array())
	{
        $content = str_ireplace('%%todaysdate%%', date(GetLang('TodaysDate')), $content);        
		if (empty($subscriberinfo) || !isset($subscriberinfo['subscriberid'])) {
            $content = str_ireplace('%basic:archivelink%', '#', $content);
            $content = str_ireplace('%%mailinglistarchive%%', "#", $content);
            $content = str_ireplace('%%webversion%%', '#', $content);
			$content = preg_replace('/%basic:unsublink%/i', '#', $content);
			$content = preg_replace('/%%unsubscribelink%%/i', '#', $content);
			$content = preg_replace('/%%confirmlink%%/i', '#', $content);
			$content = preg_replace('/%basic:confirmlink%/i', '#', $content);
			$content = preg_replace('/%%sendfriend_(.*)%%/i', '#', $content);
			$content = preg_replace('/%%modifydetails_(.*)%%/i', '#', $content);
			return $content;
		}        
        $content = str_ireplace('%basic:unsublink%', '%%unsubscribelink%%', $content);
        $content = str_ireplace('http://%%unsubscribelink%%/', '%%unsubscribelink%%', $content);
        $content = str_ireplace('%basic:archivelink%', '%%mailinglistarchive%%', $content);
		$customfields = $subscriberinfo['CustomFields'];
        require_once(SENDSTUDIO_API_DIRECTORY.'/customfields_date.php');
		foreach ($customfields as $p => $details) {            
            if(empty($details)){continue;}
                if(isset($details['fieldtype'])){
                    switch ($details['fieldtype']) {
                        case 'checkbox':
                            // unserialize checkbox, ready for displaying in correct format.
                            $data = $details['data'];
                            $value = @unserialize($data);
                            if (is_array($value) && sizeof($value)) {
                                $data = implode(',', $value);
                                $details['data'] = $data;
                            }
                        break;
                        
                        case 'date':
                            $cfdateapi = new CustomFields_Date_API($details['fieldid']);
                            $real_order = $cfdateapi->GetRealValue($details['data']);
                            if($real_order !== false){$details['data'] = $real_order;}
                        break;
                }
            }
            $fieldname = '%%' . str_replace(' ', '\\s+', preg_quote(strtolower($details['fieldname']), '/')) . '%%';
            if (!is_null($details['data'])) {$content = preg_replace('/'. $fieldname . '/i', $details['data'], $content);}
		}
		        
		$content = str_ireplace('%lists%', '%%listname%%', $content);
		$content = str_ireplace(array('%basic:email%', '%email%'), '%%emailaddress%%', $content);

	    $basefields = array('emailaddress', 'confirmed', 'format', 'subscribedate', 'listname', 'ipaddress', 'companyname', 'companyaddress', 'companyphone');
		foreach ($basefields as $p => $field) {
			$field = strtolower($field);

			if (!isset($subscriberinfo[$field])) {
				continue;
			}
			$fielddata = $subscriberinfo[$field];
			if ($field == 'subscribedate') {
				$fielddata = date(GetLang('DateFormat'), $fielddata);
			}
			$fieldname = '%%' . $field . '%%';
			$content = str_replace($fieldname, $fielddata, $content);
			unset($fielddata);
		}

		$web_version_link = SENDSTUDIO_APPLICATION_URL . '/display.php?M=' . $subscriberinfo['subscriberid'];
		$web_version_link .= '&C=' . $subscriberinfo['confirmcode'];

		if (isset($subscriberinfo['listid'])) {
			$web_version_link .= '&L=' . $subscriberinfo['listid'];
		}

		if (isset($subscriberinfo['newsletter'])) {
			$web_version_link .= '&N=' . $subscriberinfo['newsletter'];
		}

		if (isset($subscriberinfo['autoresponder'])) {
			$web_version_link .= '&A=' . $subscriberinfo['autoresponder'];
		}

		$content = str_ireplace('%%webversion%%', $web_version_link, $content);

		$mailinglist_archives_link = SENDSTUDIO_APPLICATION_URL . '/rss.php?M=' . $subscriberinfo['subscriberid'];
		$mailinglist_archives_link .= '&C=' . $subscriberinfo['confirmcode'];

		if (isset($subscriberinfo['listid'])) {
			$mailinglist_archives_link .= '&L=' . $subscriberinfo['listid'];
		}

		$content = str_ireplace('%%mailinglistarchive%%', $mailinglist_archives_link, $content);


		$confirmlink = SENDSTUDIO_APPLICATION_URL . '/confirm.php?E=' . $subscriberinfo['emailaddress'];
		if (isset($subscriberinfo['listid'])) {
			$confirmlink .= '&L=' . $subscriberinfo['listid'];
		}

		$confirmlink .= '&C=' . $subscriberinfo['confirmcode'];

		$content = str_replace(array('%%confirmlink%%', '%%CONFIRMLINK%%'), $confirmlink, $content);

		$content = str_replace(array('%basic:confirmlink%', '%BASIC:CONFIRMLINK%'), $confirmlink, $content);

		$unsubscribelink = SENDSTUDIO_APPLICATION_URL . '/unsubscribe.php?';  

        $linkdata = "&M={$subscriberinfo['subscriberid']}";  

		// so we can track where someone unsubscribed from, we'll add that into the url.
		if (isset($subscriberinfo['newsletter'])) {
			$linkdata .= "&N={$subscriberinfo['statid']}";
		}

		if (isset($subscriberinfo['autoresponder'])) {
			$linkdata .= "&A={$subscriberinfo['statid']}";
		}

		if (isset($subscriberinfo['listid'])) {
            $linkdata .= "&L={$subscriberinfo['listid']}";		    		      		   			
		}        

		$linkdata .= "&C={$subscriberinfo['confirmcode']}";
        
        $unsubscribelink .= $linkdata;
        
        $content = str_ireplace('%%unsubscribelink%%', $unsubscribelink, $content);

		$replaceurl = SENDSTUDIO_APPLICATION_URL . '/modifydetails.php?' . $linkdata . '&F=$1';
		$content = preg_replace('~(?:http://)?%%modifydetails_(\d*?)%%/?~i', $replaceurl, $content);

		$replaceurl = SENDSTUDIO_APPLICATION_URL . '/sendfriend.php?' . $linkdata . '&F=$1';
		if (isset($subscriberinfo['newsletter'])) {
			$replaceurl .= '&i=' . $subscriberinfo['newsletter'];
		} elseif (isset($subscriberinfo['autoresponder'])) {
			$replaceurl .= '&i=' . $subscriberinfo['autoresponder'];
		}
		$content = preg_replace('~(?:http://)?%%sendfriend_([0-9]+)%%/?~i', $replaceurl, $content);

		return $content;
	}