We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 28373
    • 204 Posts
    Here is the snippet code

    <?php
    /*
     *  Written by: Wendy Novianto
     *  Contact: [email protected]
     *  Created: 1/19/2006
     *  Last Edited: 1/27/2006
     *  For: MODx cms (modxcms.com)
     *  Name: Newsletter
     *  Description: <strong>Version 0.2b</strong> - Newsletter Snippets to send modx documents or plain text to web users groups
     *  Example:
     *      Default Display: (Make sure to configure the form in a chunk) - Default mode to signup
     *        [!Newsletter? &mode=`signup` &tplSignupForm=`SignupForm`!] - Display subscription form
     *        [!Newsletter? &mode=`signout` &tplSignoutForm=`SignoutForm`!] - Display unsubscribe form
     *        [!Newsletter? &mode=`doc`!] - Display newsletter admin for sending out page/document
     *                                    - Can be accessed using &npid on querystring, which refer to document id to be sent
     *        [!Newsletter? &mode=`msg`!] - Display newsletter admin for sending out plain text
     *
     *      To display send document link on individual page (You need administration prviledge to have this anchor appeared
     *      It's suggested to use cache for anchor, to optimize the site speed.
     *        [[Newsletter? &anchor=`12`]]
     *
     *      NOTE: - Notice the uncached calling to the snippet, so that the generated html is not being cached by MODx
     *            - All newsletter calling with mode can be achieved the same way with querystring &mode
     *            - Please customize all the forms provided with chunks, which can be added on snippet calling,
     *              and pay attention to the hidden field on the forms, which contain important configuration for newsletter
     *            - More information on snippet parameters, please read the code section on "SETTING UP SNIPPET PARAMETERS"
     *            - Don't forget to create document group and web group to restrict usage of the newsletter
     *            - Please include &emailGroup parameter in snippet calling for specific web group to be used, or it will
     *              caused several security issue.
     */
    
    /*
                                 License
    
    DBCalendar - A MODx module that provides newsletter support to be added
                as part of the features
    Copyright (C) 2006  Wendy Novianto
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    
    */
    
    // Newsletter v0.1 for MODx
    // Author: Luca Allulli 2005
    //
    // Modified by Wendy Novianto ([email protected])
    
    
    
    /*------------------------------------
    	SETTING UP SNIPPET PARAMETERS
    */
    
    // -- $disableGet (false)
    // -- -- To remove the ability of accessing other newsletter mode querystring 'mode'
    if(isset($disableGet) && strtolower($disableGet) == 'true') $disableGet = true;
    else $disableGet = false;
    
    // -- $rte (true)
    // -- -- To use RichText Editor with msg mode
    // -- -- Default to rteeditor
    if(!isset($rte)) $rte = 'true';
    
    // -- $rteWidth (100%)
    // -- -- RichText Editor Width
    if(!isset($rteWidth)) $rteWidth = '100%';
    
    // -- $rteHeight (400)
    // -- -- RichText Editor Width
    if(!isset($rteHeight)) $rteHeight = '400';
    
    // -- $anchor (false)
    // -- -- To enabled snippet in displaying anchor [document_id | false] - (default to false)
    if(!isset($anchor) || !is_numeric($anchor)) $anchor = false;
    
    // -- $anchorMsg
    // -- -- Anchor Template to be displayed
    // -- -- put {+URL+} as the link, and you can insert whatever template that you want (It's not a chunk)
    if(!isset($tplAnchorMsg)) $anchorMsg = '<a href="{+URL+}">Send Newsletter</a>';
    else $anchorMsg = $modx-getChunk($tplAnchorMsg);
    
    // -- $mode (signup)
    // -- -- To set default view for newsletter form [msg | doc] - (default to msg)
    if(!isset($mode)) $mode = 'signup';
    else $mode = strtolower($mode);
    if(isset($_GET['mode']) && !$disableGet) {
    	switch($_GET['mode']) {
    		case 'doc':
    			$mode = 'doc';
    			break;
    		case 'msg':
    			$mode = 'msg';
    			break;
    		case 'signup':
    			$mode = 'signup';
    			break;
    		case 'signout':
    			$mode = 'signout';
    			break;
    		default:
    			break;
    	}
    }
    
    // -- $accessMgr (true)
    // -- -- Allowed manager groups [true | false]
    if(!isset($accessMgr)) $accessMgr = true;
    
    // -- $accessWeb
    // -- -- Allowed web groups access [List of group name seperated by '|']
    if(!isset($accessWeb)) $accessWeb = '';
    
    // -- $removeUser (false)
    // -- -- To remove the ability of accessing other newsletter mode querystring 'mode'
    if(isset($removeUser) && strtolower($removeUser) == 'true') $removeUser = true;
    else $removeUser = false;
    
    // -- $emailGroup
    // -- -- Allowed web group to be sent [name_of_webgroup | *] (default to *)
    // -- -- This will be used as a users subscription group as well
    // -- -- * means every user on the webgroup
    // -- -- name_of_webgroup means any webgroup names separated with coma (ex: group1, group2)
    // -- -- Please defined the allow web group on your snippet calling for added security!
    if(!isset($emailGroup)) $emailGroup = '*';
    else {
    	$emailGroup = split(',', trim($emailGroup)); // Split the email group
    	for($i = 0; $i < count($emailGroup); $i++) $emailGroup[$i] = trim($emailGroup[$i]); // Cleaning up space
    }
    
    // -- $docGroup
    // -- -- Allowed document group to be emailed [name_doc_group | *] (default to *)
    // -- -- * means every document group
    // -- -- name_doc_group means any document group separated by coma (ex: docgroup1, docgroup2)
    if(!isset($docGroup)) $docGroup = '*';
    else {
    	$docGroup = split(',', trim($docGroup)); // Split the email group
    	for($i = 0; $i < count($docGroup); $i++) $docGroup[$i] = trim($docGroup[$i]); // Cleaning up space
    }
    
    // -- $extraField
    // -- -- Coma separated column/form name
    // -- -- Used when a new user signup to the system, it's to gather certain information
    // -- -- to be stored on user attribute table.
    // -- -- The input name on signup has to be the same with the attribute column name on database.
    if(!isset($extraField)) $extraField = array();
    else {
    	$extraField = split(',', trim($extraField)); // Split the email group
    	for($i = 0; $i < count($extraField); $i++) $extraField[$i] = trim($extraField[$i]); // Cleaning up space
    }
    
    // -- $tplFormMsg
    // -- -- Chunk Template for Newsletter Message Form
    // -- -- Use for sending a plain message as an email content
    // -- -- {+WebUserList+}, {+FormMessage+}, {+RichTextEditorCode+}
    // -- -- Textarea with name 'contentmsg' can be substitued with RichTextEditor, &rte set to true
    if(!isset($tplFormMsg)) $tplFormMsg = '';
    $tplDefaultFormMsg = '
    <form method="post" action="[~[*id*]~]?mode=msg">
    	<input type="hidden" name="opcode" value="SubmitNewsMsg" />
    	<input type="hidden" name="from" value="[email protected]" />
    	<select name="type">
    		<option value="text">Text</option>
    		<option value="html">HTML</option>
    	</select>
    	<div>To (WebUser Group):</div><div>{+WebUserList+}</div>
    	<div>To:</div><div><textarea name="toemail"></textarea></div>
    	<div>Subject:</div><div><input name="subject" /></div>
    	<div>Document:</div><div><textarea id="contentmsg" name="contentmsg" style="width:100%; height:300px;">{+FormMessage+}</textarea></div>
    	{+RichTextEditorCode+}
    	<div>
    		<input type="submit" name="submit" value="Send" />
    		<input type="reset" name="reset" value="Reset" />
    	</div>
    </form>
    ';
    
    
    // -- $tplFormDoc
    // -- -- Chunk Template for Newsletter Document/Page Form
    // -- -- Use for sending a page/document as an email content
    // -- -- {+WebUserList+}, {+DocumentList+}
    if(!isset($tplFormDoc)) $tplFormDoc = '';
    $tplDefaultFormDoc = '
    <form method="post" action="[~[*id*]~]?mode=doc">
    	<input type="hidden" name="opcode" value="SubmitNewsDoc" />
    	<input type="hidden" name="from" value="[email protected]" />
    	<select name="type">
    		<option value="text">Text</option>
    		<option value="html">HTML</option>
    	</select>
    	<div>To (WebUser Group):</div><div>{+WebUserList+}</div>
    	<div>To:</div><div><textarea name="toemail"></textarea></div>
    	<div>Subject:</div><div><input name="subject" /></div>
    	<div>Document:</div><div>{+DocumentList+}</div>
    	<div>
    		<input type="submit" name="submit" value="Send" />
    		<input type="reset" name="reset" value="Reset" />
    	</div>
    </form>
    ';
    
    // -- $tplMsgSucceed
    // -- -- Chunk Template for Succeed Message
    if(!isset($tplMsgSucceed)) $tplMsgSucceed = '';
    $tplDefaultMsgSucceed = '
    Your message had been sent!
    ';
    
    // -- $tplMsgDenied
    // -- -- Chunk template for denied message of not allowed access
    if(!isset($tplMsgDenied)) $tplMsgDenied = '';
    $tplDefaultMsgDenied = '
    You are not allowed to access this area!
    ';
    
    // -- $tplSignupForm
    // -- -- Chunk template for Newsletter Signup Form
    // -- -- You can insert user to multiple group using coma separated group name on the group value field
    // -- -- Input Name: group - is optional, if it's set to none, it will use $emailGroup, if is set,
    // -- --                     you can use whatever select box or input box, and the selected value will be
    // -- --                     subscribed (coma delimited for plain text using input box)
    // -- -- Input Name: username - is optional, if it's not included, it will use email input as the username
    // -- -- You can add more fields that are available in the user attributes, as long as you define it first
    // -- -- in the snippet calling, for added security.
    if(!isset($tplSignupForm)) $tplSignupForm = '';
    $tplDefaultSignupForm = '
    <form method="post" action="[~[*id*]~]?mode=signup">
    	<input type="hidden" name="opcode" value="SignUp" />
    	<div>Group:</div>
    	<div>
    		<select name="group">
    			<option value="Test: Newsletter">Test Group</option>
    		</select>
    	</div>
    	<div>Email Address:</div><div><input name="email" /></div>
    	<div>
    		<input type="submit" name="submit" value="Subscribe" />
    	</div>
    </form>
    ';
    
    // -- $tplSignoutForm
    // -- -- Chunk template for Newsletter Signout Form
    // -- -- Input Name: group - is optional, if it's set to none, it will use $emailGroup, if is set,
    // -- --                     you can use whatever select box or input box, and the selected value will be
    // -- --                     unsubscribed (coma delimited for plain text using input box)
    // -- -- Input Name: removed - is optional, if it's set to true, it will completely remove the user account
    // -- --                       from MODx web user database. If it's set to none, it won't remove the account,
    // -- --                       only the web groups subscription will remove.
    if(!isset($tplSignoutForm)) $tplSignoutForm = '';
    $tplDefaultSignoutForm = '
    <form method="post" action="[~[*id*]~]?mode=signout">
    	<input type="hidden" name="opcode" value="SignOut" />
    	<div>Group:</div>
    	<div>
    		<select name="group">
    			<option value="Test: Newsletter">Test Group</option>
    		</select>
    	</div>
    	<div>Email Address:</div><div><input name="email" /></div>
    	<div>
    		<input type="submit" name="submit" value="Unsubscribe" />
    	</div>
    </form>
    ';
    
    // -- $tplSignupSucceed
    // -- -- Chunk template for successful subscription
    if(!isset($tplSignupSucceed)) $tplSignupSucceed = '';
    $tplDefaultSignupSucceed = '
    <div>
    Congratulation, you\'ve been subscribed to the system.
    </div>
    ';
    
    // -- $tplSignoutSucceed
    // -- -- Chunk template for successful subscription
    if(!isset($tplSignoutSucceed)) $tplSignoutSucceed = '';
    $tplDefaultSignoutSucceed = '
    <div>
    You\'ve been unsubscribed from the system.
    </div>
    ';
    
    // -- tplErrorMessage
    // -- -- Chunk template for the main template of signup/signout error message
    if(!isset($tplErrorMsg)) $tplErrorMsg = '';
    $tplDefaultErrorMsg = '
    <div>
    {+Content+}
    </div>
    ';
    
    // -- tplErrorMessageLoop
    // -- -- Chunk template for the main template of signup/signout error message
    if(!isset($tplErrorMsgLoop)) $tplErrorMsg = '';
    $tplDefaultErrorMsgLoop = '
    <div>{+Message+}</div>
    ';
    
    
    
    /*-----------------------
    	HELPER FUNCTIONS
    */
    
    // Function Sanity Check
    global $function_NewsletterFlag;
    if(!isset($function_NewsletterFlag)) {
    	// Mail function wrapper specific for newsletter
    	// -- $to will be an array returned from select box
    	function mailNewsletter($from, $toemail, $tousers, $subject, $content, $type='text') {
    		global $modx;
    		// Generate Headers
    		if(strtolower($type) == 'html') $contentType = 'text/html; charset=iso-8859-1';
    		else $contentType = 'text/plain';
    		$headers = "MIME-Version: 1.0\r\n";
    		$headers .= "Content-type: ".$contentType."\r\n";
    		$headers .= "From: ".$from;
    		// Parse $toemail to emails array
    		if(trim($toemail) != '') {
    			$toemail = split(';', $toemail); // Transform $toemail into list of emails array
    			for($i = 0; $i < count($toemail); $i++) $toemail[$i] = trim($toemail[$i]); // Stripping white space
    		}
    		else {
    			$toemail = '';
    		}
    		// Parse $tousers to emails array
    		$touemail = array();
    		foreach($tousers as $touser) {
    			// Fetch all Users' email
    			if($touser == '*') {
    				// Getting Web User Email From Database
    				// -- Generate SQL
    				$tbl = $modx->dbConfig['table_prefix'];
    				$sql = "SELECT DISTINCT(wu.id), wu.username, wua.fullname, wua.email FROM ".$tbl.'web_users AS wu ';
    				$sql .= 'LEFT JOIN '.$tbl.'web_user_attributes AS wua ON wua.internalKey = wu.id ';
    				$sql .= 'ORDER BY wu.username ASC;';
    				// -- Execute SQL query
    				$usersrs = $modx->dbQuery($sql);  # Execute the Query
    				$userslimit = $modx->recordCount($usersrs);  # Number of users found
    				// -- Fill emailed array with email from this web group
    				for($i = 0; $i < $userslimit; $i++) {
    					$users = $modx->fetchRow($usersrs);
    					$touemail[] = $users['email'];
    				}
    			}
    			// Fetch all web group users' email
    			else if(substr($touser, 0, 2) == '**') {
    				// Getting Web User Email From Database
    				// -- Generate SQL
    				$tbl = $modx->dbConfig['table_prefix'];
    				$sql = "SELECT DISTINCT(wu.id), wu.username, wua.fullname, wua.email, wgn.name FROM ".$tbl.'web_users AS wu ';
    				$sql .= 'LEFT JOIN '.$tbl.'web_user_attributes AS wua ON wua.internalKey = wu.id ';
    				$sql .= 'LEFT JOIN '.$tbl.'web_groups AS wg ON wg.webuser = wu.id ';
    				$sql .= 'LEFT JOIN '.$tbl.'webgroup_names AS wgn ON wgn.id = wg.webgroup ';
    				$sql .= 'WHERE wgn.name = \''.substr($touser, 2).'\' ';
    				$sql .= 'ORDER BY wgn.name ASC, wu.username ASC;';
    				// -- Execute SQL query
    				$usersrs = $modx->dbQuery($sql);  # Execute the Query
    				$userslimit = $modx->recordCount($usersrs);  # Number of users found
    				// -- Fill emailed array with email from this web group
    				for($i = 0; $i < $userslimit; $i++) {
    					$users = $modx->fetchRow($usersrs);
    					$touemail[] = $users['email'];
    				}
    			}
    			// Fetch specific user's email
    			else {
    				$touemail[] = $touser;
    			}
    		}
    		// Send Out Email
    		if(is_array($toemail)) {
    			// -- Remove duplicate email ($toemail)
    			$toemail = array_flip($toemail);
    			$toemail = array_flip($toemail);
    			// -- Email $toemail ($toemail)
    			for($i = 0; $i < count($toemail); $i++) {
    				mail($toemail[$i], $subject, $content, $headers);
    			}
    		}
    		if(count($touemail) > 0) {
    			// -- Remove duplicate email ($tousers)
    			$touemail = array_flip($touemail);
    			$touemail = array_flip($touemail);
    			// -- Email $touemail ($tousers)
    			for($i = 0; $i < count($touemail); $i++) {
    				mail($touemail[$i], $subject, $content, $headers);
    			}
    		}
    		// Return flag
    		return true;
    	}
    
    	// Parser function to parse document page into html string
    	function parseWebPage($url) {
    		$ch = curl_init();
    		curl_setopt($ch, CURLOPT_URL, $url);
    		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    		$store = curl_exec ($ch);
    		$xml = curl_exec ($ch);
    		curl_close ($ch);
    		return $xml;
    	}
    
    	// API Addition to check manager doc groups with current docs
    	function isMemberOfMgrGroup($docid=1){
    		global $modx;
    		// Check super manager
    		if($_SESSION['mgrRole'] == 1)
    			return true;
    		// Fetch current document groups
    		$sql = '';
    		$result = $modx->db->select('document_group', $modx->getFullTableName("document_groups"), 'document = '.$docid);
    		$counter = 0;
    		while($tempResult = mysql_fetch_array($result)) {
    			$docGroups[$counter] = $tempResult['document_group'];
    			$counter++;
    		}
    ?>
    


    Admin note: wrapped in code and PHP tags. Strip PHP tags to use.
      • 28373
      • 204 Posts
      and


      <?php
      		// Fetch current manager groups
      		$mgrGroups = $_SESSION['mgrDocgroups'];
      		if(!is_array($mgrGroups)) return false;
      		// Check doc groups and mgr groups
      		if(!is_array($docGroups)) return false;
      		foreach($docGroups as $k=>$v)
      			if(in_array(trim($v),$mgrGroups)) return true;
      		return false;
      	}
      
      	// Function to generate random password
      	function genPassword($length){ 
      		srand((double)microtime()*1000000);
      		$vowels = array("a", "e", "i", "o", "u"); 
      		$cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr", 
      		"cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl"); 
      		$num_vowels = count($vowels); 
      		$num_cons = count($cons); 
      		for($i = 0; $i < $length; $i++){ 
      			$password .= $cons[rand(0, $num_cons - 1)] . $vowels[rand(0, $num_vowels - 1)]; 
      		} 
      		return substr($password, 0, $length); 
      	}
      	
      	// Function Sanity Check
      	$function_NewsletterFlag = true;
      }
      
      
      
      /*-------------------------------
      	EXECUTING SNIPPET SYSTEM
      */
      
      // Check user permission
      $allowAdmin = false;
      // -- Web Group Check
      $WebGroup = explode('|', $accessWeb);
      if($modx->isMemberOfWebGroup($WebGroup))
      	$allowAdmin = true;
      // -- Manager Group Check
      if(isMemberOfMgrGroup($modx->documentIdentifier))
      	$allowAdmin = true;
      
      // --
      // Display snippet as an anchor tag for sending specific document/page
      // --
      if($anchor) {
      	if($allowAdmin) {
      		$sendlink = $modx->makeUrl($anchor, '', '?mode=msg&npid='.$modx->documentIdentifier);
      		$output = str_replace('{+URL+}', $sendlink, $anchorMsg);
      		echo $output;
      	}
      }
      // --
      // Displaying administration area
      // --
      else if($mode == 'doc' || $mode == 'msg') {
      	// Disallow access to newsletter
      	if(!$allowAdmin) {
      		// Output denied message
      		if($tplMsgDenied != '') $tplDefaultMsgDenied = $modx->getChunk($tplMsgDenied);
      		echo $tplDefaultMsgDenied; // Outputing form
      	}
      	// Allow access to newsletter
      	else {
      		//
      		// Send the newsletter & display message after postback to show result of message sending
      		//
      		if(isset($_POST['opcode']) && isset($_POST['type']) && (strtolower($_POST['type']) == 'text' || strtolower($_POST['type']) == 'html') && isset($_POST['from']) && isset($_POST['toemail']) && isset($_POST['tousers']) && isset($_POST['subject']) && (isset($_POST['contentmsg']) || isset($_POST['contentdocs']))) {
      			switch($_POST['opcode']) {
      				case 'SubmitNewsMsg':
      					if(mailNewsletter($_POST['from'], $_POST['toemail'], $_POST['tousers'], $_POST['subject'], $_POST['contentmsg'], strtolower($_POST['type']))) {
      						// Output succeed message
      						if($tplMsgSucceed != '') $tplDefaultMsgSucceed = $modx->getChunk($tplMsgSucceed);
      						echo $tplDefaultMsgSucceed; // Outputing form
      					}
      					break;
      				case 'SubmitNewsDoc':
      					$succeedFlag = true;
      					foreach($_POST['contentdocs'] as $docid) {
      						$url = $modx->config['site_url'].ltrim($modx->makeUrl($docid), '/');
      						$webPageHtml = parseWebPage($url);
      						if(!mailNewsletter($_POST['from'], $_POST['toemail'], $_POST['tousers'], $_POST['subject'], $webPageHtml, strtolower($_POST['type']))) {
      							$succeedFlag = false;
      						}
      					}
      					if($succeedFlag) {
      						// Output succeed message
      						if($tplMsgSucceed != '') $tplDefaultMsgSucceed = $modx->getChunk($tplMsgSucceed);
      						echo $tplDefaultMsgSucceed; // Outputing form
      					}
      					break;
      				default:
      					break;
      			}
      		}
      		//
      		// Display snippet as newsletter send form
      		//
      		else {
      			// Getting Web User List From Database ($outputUsers)
      			// -- Generate SQL
      			$tbl = $modx->dbConfig['table_prefix'];
      			$sql = "SELECT DISTINCT(wu.id), wu.username, wua.fullname, wua.email, wgn.name FROM ".$tbl.'web_users AS wu ';
      			$sql .= 'LEFT JOIN '.$tbl.'web_user_attributes AS wua ON wua.internalKey = wu.id ';
      			$sql .= 'LEFT JOIN '.$tbl.'web_groups AS wg ON wg.webuser = wu.id ';
      			$sql .= 'LEFT JOIN '.$tbl.'webgroup_names AS wgn ON wgn.id = wg.webgroup';
      			// -- -- Generate where clause to fetch certain users' web group
      			if(!is_array($emailGroup) && $emailGroup == '*') {
      				$sql .= ' ';
      			}
      			else if(count($emailGroup) > 0) {
      				for($i = 0; $i < count($emailGroup); $i++) {
      					if($i == 0) $sql .= ' WHERE ';
      					$sql .= 'wgn.name = \''.$emailGroup[$i].'\'';
      					if($i >= 0 && $i < count($emailGroup)-1) $sql .= ' OR ';
      					if($i >= count($emailGroup)-1) $sql .= ' ';
      				}
      			}
      			// -- -- Generate order by clause
      			$sql .= 'ORDER BY wgn.name ASC, wu.username ASC;';
      			// -- Execute SQL query
      			$usersrs = $modx->dbQuery($sql);  # Execute the Query
      			$userslimit = $modx->recordCount($usersrs);  # Number of users found
      			// Fetch user and generate user list in select box
      			$outputUsers = '<select name="tousers[]" size="10" multiple class="users">'."\n";
      			// -- Fill the select box with optional option (ex: send all users - *)
      			$outputUsers .= '<option value="*">All Users</option>'."\n";
      			if(is_array($emailGroup)) {
      				// -- Fill the select box with send to certain group option (**group_name)
      				for($i = 0; $i < count($emailGroup); $i++) {
      					if($emailGroup[$i] != '*')
      						$outputUsers .= '<option value="**'.$emailGroup[$i].'">'.$emailGroup[$i].'</option>'."\n";
      				}
      			}
      			else {
      				// Getting Web Group List (**group_name)
      				// -- Generate SQL
      				$tbl = $modx->dbConfig['table_prefix'];
      				$sql = 'SELECT id, name FROM '.$tbl.'webgroup_names ORDER BY name ASC;';
      				// -- Execute SQL query
      				$groupsrs = $modx->dbQuery($sql);  # Execute the Query
      				$groupslimit = $modx->recordCount($groupsrs);  # Number of users found
      				// -- Fill the select box with send to certain group option (**group_name)
      				for($i = 0; $i < $groupslimit; $i++) {
      					$groups = $modx->fetchRow($groupsrs);
      					$outputUsers .= '<option value="**'.$groups['name'].'">'.$groups['name'].'</option>'."\n";
      				}
      			}
      			// -- Fill the select box with send to specific users option
      			for($i = 0; $i < $userslimit; $i++) {
      				$users = $modx->fetchRow($usersrs);
      				$outputUsers .= '<option value="'.$users['email'].'">'.$users['username'].'</option>'."\n";
      			}
      			$outputUsers .= '</select>'."\n";
      			//
      			// Display Newsletter as a Plain Text/Editable for the content
      			//
      			if($mode == 'msg') {
      				// Check RichText Editor enabled or not
      				if(isset($_GET['npid']) && is_numeric($_GET['npid'])) {
      					$url = $modx->config['site_url'].ltrim($modx->makeUrl($_GET['npid']), '/');
      					$webPageHtml = parseWebPage($url);
      				}
      				else {
      					$webPageHtml = '';
      				}
      				// Format html content into the right format, depending on the needs
      				//if(strtolower($rte) == 'true')
      				//	$webPageHtml = htmlspecialchars($webPageHtml);
      				// Invoke RichTextEditor event, if rte enabled
      				$rteOutput = '';
      				if(strtolower($rte) == 'true') {
      					$replace_richtexteditor = array("contentmsg");
      					if(is_array($replace_richtexteditor)) {
      						$evtOut = $modx->invokeEvent("OnRichTextEditorInit",
      									array(
      										'editor'    => $modx->config['which_editor'],
      										'elements'  => $replace_richtexteditor,
      										'width'     => $rteWidth,
      										'height'    => $rteHeight
      									));
      						if(is_array($evtOut)) $rteOutput = implode("",$evtOut);				
      					}
      				}
      				// Form Output
      				if($tplFormMsg != '') $tplDefaultFormMsg = $modx->getChunk($tplFormMsg);
      				$tplDefaultFormMsg = str_replace('{+WebUserList+}', $outputUsers, $tplDefaultFormMsg); // Put user list on template
      				$tplDefaultFormMsg = str_replace('{+FormMessage+}', $webPageHtml, $tplDefaultFormMsg); // Put HTML Contet parsed from website on it
      				$tplDefaultFormMsg = str_replace('{+RichTextEditorCode+}', $rteOutput, $tplDefaultFormMsg); // Put necessary js code for RichTextEditor
      				echo $tplDefaultFormMsg; // Outputing form
      			}
      			//
      			// Display Newsletter use document as the content
      			//
      			else {
      				//Getting Documents List ($outputDocs)
      				// -- Generate SQL
      				$tbl = $modx->dbConfig['table_prefix'];
      				$sql = 'SELECT DISTINCT(sc.id), sc.pagetitle, sc.longtitle FROM '.$tbl.'site_content AS sc ';
      				$sql .= 'LEFT JOIN '.$tbl.'document_groups AS dg ON dg.document = sc.id ';
      				$sql .= 'LEFT JOIN '.$tbl.'documentgroup_names AS dgn ON dgn.id = dg.document_group ';
      				// -- -- Generate where clause to fetch certain users' web group
      				if(count($docGroup) == 1 && $docGroup[0] == '*') {
      					$sql .= ' ';
      				}
      				else if(count($docGroup) > 0) {
      					for($i = 0; $i < count($docGroup); $i++) {
      						if($i == 0) $sql .= 'WHERE ';
      						$sql .= 'dgn.name = \''.$docGroup[$i].'\'';
      						if($i > 0 && $i < count($docGroup)-1) $sql .= ' AND ';
      						if($i >= count($docGroup)-1) $sql .= ' ';
      					}
      				}
      				// -- -- Generate order by clause
      				$sql .= 'ORDER BY sc.pagetitle ASC;';
      				// -- Execute SQL query
      				$docsrs = $modx->dbQuery($sql);  # Execute the Query
      				$docslimit = $modx->recordCount($docsrs);  # Number of users found
      				// Fetch doc group and generate doc group list in select box
      				$outputDocs = '<select name="contentdocs[]" size="10" multiple class="docs">'."\n";
      				// -- Fill the select box with send to specific users option
      				for($i = 0; $i < $docslimit; $i++) {
      					$docs = $modx->fetchRow($docsrs);
      					$selected = ((isset($_GET['npid']) && $_GET['npid'] == $docs['id']) ? 'selected ' : ' ');
      					$outputDocs .= '<option '.$selected.'value="'.$docs['id'].'">'.$docs['pagetitle'].'</option>'."\n";
      				}
      				$outputDocs .= '</select>'."\n";
      				// Form Output
      				if($tplFormDoc != '') $tplDefaultFormDoc = $modx->getChunk($tplFormDoc);
      				$tplDefaultFormDoc = str_replace('{+WebUserList+}', $outputUsers, $tplDefaultFormDoc); // Put user list on template
      				$tplDefaultFormDoc = str_replace('{+DocumentList+}', $outputDocs, $tplDefaultFormDoc); // Put document list on template
      				echo $tplDefaultFormDoc; // Outputing form
      			}
      		}
      	}
      }
      // --
      // Displaying signup/signout form
      // --
      else {
      	//
      	// Do member newsletter processing (signup/signout)
      	//
      	if(isset($_POST['opcode']) && isset($_POST['email'])) {
      		switch($_POST['opcode']) {
      			case 'SignUp':
      				if($mode == 'signup') {
      					// Checking for error input
      					unset($outError);
      					// -- Verify email
      					if(trim($_POST['email']) == '' || !ereg("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", trim($_POST['email']))){
      						$outError[] = "E-mail address doesn't seem to be valid!";
      					}
      					else {
      						$email = trim($_POST['email']);
      					}
      					// Getting form input data & Validating data
      					if(!isset($outError)) {
      						// -- Generate required field for creating web user account
      						if(isset($_POST['username']) && trim($_POST['username'])) $username = trim($_POST['username']);
      						else $username = trim($_POST['email']);
      						$password = genPassword(8);
      						$email = trim($_POST['email']);
      						$extraFieldValue = '';
      						for($i = 0; $i < count($extraField); $i++) {
      							$extraFieldValue .= ' , ';
      							if(isset($_POST[$extraField[$i]]))
      								$extraFieldValue .= "'".trim($_POST[$extraField[$i]])."'";
      							else
      								$extraFieldValue .= "''";
      						}
      						// -- Check for web group
      						if(!is_array($emailGroup) && trim($emailGroup) == '*') {
      							$groups = array();
      						}
      						else {
      							$groups = $emailGroup;
      						}
      						// -- Check for form group
      						// -- -- Handle simple text with coma delimited web groups from form input
      						if(isset($_POST['group']) && !is_array($_POST['group']) && trim($_POST['group']) != '') {
      							$postGroup = split(',', $_POST['group']);
      							for($i = 0; $i < count($postGroup); $i++) $postGroup[$i] = trim($postGroup[$i]);
      							if(count($groups) > 0) {
      								$tempGroup = array();
      								for($i = 0; $i < count($postGroup); $i++) {
      									if(in_array($postGroup[$i], $groups)) $tempGroup[] = $postGroup[$i];
      								}
      								$groups = $tempGroup;
      							}
      							else {
      								$groups = $postGroup;
      							}
      						}
      						// -- -- Handle array input from select box
      						else if(isset($_POST['group']) && is_array($_POST['group'])) {
      							$postGroup = $_POST['group'];
      							for($i = 0; $i < count($postGroup); $i++) $postGroup[$i] = trim($postGroup[$i]);
      							if(count($groups) > 0) {
      								$tempGroup = array();
      								for($i = 0; $i < count($postGroup); $i++) {
      									if(in_array($postGroup[$i], $groups)) $tempGroup[] = $postGroup[$i];
      								}
      								$groups = $tempGroup;
      							}
      							else {
      								$groups = $postGroup;
      							}
      						}
      						// -- Check for duplicate email
      						$sql = "SELECT internalKey FROM ".$modx->getFullTableName("web_user_attributes")." WHERE email='".$email."';";
      						if(!$rs = $modx->db->query($sql)){
      							$outError[] = "An error occured while attempting to check email subscription.";
      						} 
      						$limit = $modx->db->getRecordCount($rs);
      						if($limit > 0) {
      							$emailRegistered = true;
      							if($row = $modx->fetchRow($rs)) {
      								$key = $row["internalKey"];
      							}
      						}
      						else {
      							// Check for username availability
      							$sql = "SELECT id FROM ".$modx->getFullTableName("web_users")." WHERE username='".$username."';";
      							$bs = $modx->dbQuery($sql);
      							if(!bs) $outError[] = 'An error occured while attempting to fetch user\' information';
      							else {
      								$limit = $modx->db->getRecordCount($bs);
      								if($limit > 0) $outError[] = 'The username had been taken by a different user with the same email address';
      							}
      							$emailRegistered = false;
      
      						}
      						// Inserting user to database
      						if(!isset($outError)) {
      							// -- Create the user account
      							if(!$emailRegistered) {
      								// -- -- Building extra column
      								$sqlCol = '';
      								for($i = 0; $i < count($extraField); $i++) {
      									$sqlCol .= ' , ';
      									$sqlCol .= $extraField[$i];
      								}
      								$sql = "INSERT INTO ".$modx->getFullTableName("web_users")." (username, password) 
      										VALUES('".$username."', md5('".$password."'));";
      								$rs = $modx->db->query($sql);
      								if(!$rs){
      									$outError[] = "An error occured while attempting to save the user.";
      								}
      								$key = $modx->db->getInsertId(); // Now get the id
      								// -- Saave user attribute for new user
      								if(!isset($outError)) {
      									$sql = "INSERT INTO ".$modx->getFullTableName("web_user_attributes")." (internalKey, email".$sqlCol.") 
      											VALUES($key, '$email'$extraFieldValue);";
      									$rs = $modx->db->query($sql);
      									if(!$rs){
      										$outError[] = "An error occured while attempting to save user's attributes.";
      									}
      								}
      							}
      							if(!isset($outError)) {
      								// -- Add user to web groups
      								if(count($groups) > 0) {
      									$ds = $modx->dbQuery("SELECT id FROM ".$modx->getFullTableName("webgroup_names")." WHERE name IN ('".implode("','",$groups)."')");
      									if(!$ds) $outError[] = 'An error occured while attempting to update user\'s web groups';
      									else {
      										while ($row = $modx->fetchRow($ds)) {
      											$wg = $row["id"];
      											$modx->dbQuery("DELETE FROM ".$modx->getFullTableName("web_groups")." WHERE webgroup = '".$wg."' AND webuser = '".$key."';");
      											$modx->dbQuery("REPLACE INTO ".$modx->getFullTableName("web_groups")." (webgroup,webuser) VALUES('$wg','$key')");
      										}
      									}
      								}
      							}
      						}
      					}
      					if(isset($outError)) {
      						// Output error message
      						if($tplErrorMsgLoop != '') $tplDefaultErrorMsgLoop = $modx->getChunk($tplErrorMsgLoop);
      						$errorList = '';
      						foreach($outError as $msg) {
      							$errorList .= str_replace('{+Message+}', $msg, $tplDefaultErrorMsgLoop);
      						}
      						if($tplErrorMsg != '') $tplDefaultErrorMsg = $modx->getChunk($tplErrorMsg);
      						$tplDefaultErrorMsg = str_replace('{+Content+}', $errorList, $tplDefaultErrorMsg);
      						echo $tplDefaultErrorMsg; // Outputing message
      					}
      					else {
      						if($tplSignupSucceed != '') $tplDefaultSignupSucceed = $modx->getChunk($tplSignupSucceed);
      						echo $tplDefaultSignupSucceed; // Outputing message
      					}
      				}
      				break;
      			case 'SignOut':
      				if($mode == 'signout') {
      					// Checking for error input
      					unset($outError);
      					// -- Verify email
      					if(trim($_POST['email']) == '' || !ereg("^[-!#$%&'*+./0-9=?A-Z^_`a-z{|}~]+", trim($_POST['email']))){
      						$outError[] = "E-mail address doesn't seem to be valid!";
      					}
      					else {
      						$email = trim($_POST['email']);
      					}
      					if(!isset($outError)) {
      						// -- Check for web group
      						if(!is_array($emailGroup) && trim($emailGroup) == '*') {
      							$groups = array();
      						}
      						else {
      							$groups = $emailGroup;
      						}
      						// -- Check for form group
      						// -- -- Handle simple text with coma delimited web groups from form input
      						if(isset($_POST['group']) && !is_array($_POST['group']) && trim($_POST['group']) != '') {
      							$postGroup = split(',', $_POST['group']);
      							for($i = 0; $i < count($postGroup); $i++) $postGroup[$i] = trim($postGroup[$i]);
      							if(count($groups) > 0) {
      								$tempGroup = array();
      								for($i = 0; $i < count($postGroup); $i++) {
      									if(in_array($postGroup[$i], $groups)) $tempGroup[] = $postGroup[$i];
      								}
      								$groups = $tempGroup;
      							}
      							else {
      								$groups = $postGroup;
      							}
      						}
      						// -- -- Handle array input from select box
      						else if(isset($_POST['group']) && is_array($_POST['group'])) {
      							$postGroup = $_POST['group'];
      							for($i = 0; $i < count($postGroup); $i++) $postGroup[$i] = trim($postGroup[$i]);
      							if(count($groups) > 0) {
      								$tempGroup = array();
      								for($i = 0; $i < count($postGroup); $i++) {
      									if(in_array($postGroup[$i], $groups)) $tempGroup[] = $postGroup[$i];
      								}
      								$groups = $tempGroup;
      							}
      							else {
      								$groups = $postGroup;
      							}
      						}
      						// Deleting user from database
      						if(!isset($outError)) {
      							// -- Get user id
      							$sql = "SELECT internalKey FROM ".$modx->getFullTableName("web_user_attributes")." WHERE email='".$email."';";
      							if(!$rs = $modx->db->query($sql)){
      								$outError[] = "An error occured while attempting to check email subscription.";
      							} 
      							$limit = $modx->db->getRecordCount($rs);
      							if($limit > 0) {
      								$emailRegistered = true;
      								if($row = $modx->fetchRow($rs)) {
      									$key = $row["internalKey"];
      								}
      								else {
      									$outError[] = 'The email address provided is not registered on the system.';
      								}
      							}
      							else {
      								$outError[] = 'The email address provided is not registered on the system.';
      							}
      
      }
      							// -- Delete users from web groups
      							if(!isset($outError)) {
      								if($removeUser) {
      									// -- Deleteing the whole user account
      									$modx->dbQuery("DELETE FROM ".$modx->getFullTableName("web_groups")." WHERE webuser = $key;");
      									$modx->dbQuery("DELETE FROM ".$modx->getFullTableName("web_user_attributes")." WHERE internalKey = $key;");
      									$modx->dbQuery("DELETE FROM ".$modx->getFullTableName("web_users")." WHERE id = $key;");
      								}
      								else {
      									// -- Only user web group going to be removed, but the account is still in the system
      									if(count($groups) > 0) {
      										$ds = $modx->dbQuery("SELECT id FROM ".$modx->getFullTableName("webgroup_names")." WHERE name IN ('".implode("','",$groups)."')");
      										if(!$ds) $outError[] = 'An error occured while attempting to delete user\'s web groups';
      										else {
      											while ($row = $modx->fetchRow($ds)) {
      												$wg = $row["id"];
      												$modx->dbQuery("DELETE FROM ".$modx->getFullTableName("web_groups")." WHERE webuser = $key AND webgroup = $wg;");
      											}
      										}
      									}
      								}
      							}
      						}
      					}
      					if(isset($outError)) {
      						// Output error message
      						if($tplErrorMsgLoop != '') $tplDefaultErrorMsgLoop = $modx->getChunk($tplErrorMsgLoop);
      						$errorList = '';
      						foreach($outError as $msg) {
      							$errorList .= str_replace('{+Message+}', $msg, $tplDefaultErrorMsgLoop);
      						}
      						if($tplErrorMsg != '') $tplDefaultErrorMsg = $modx->getChunk($tplErrorMsg);
      						$tplDefaultErrorMsg = str_replace('{+Content+}', $errorList, $tplDefaultErrorMsg);
      						echo $tplDefaultErrorMsg; // Outputing message
      					}
      					else {
      						if($tplSignoutSucceed != '') $tplDefaultSignoutSucceed = $modx->getChunk($tplSignoutSucceed);
      						echo $tplDefaultSignoutSucceed; // Outputing message
      					}
      				}
      				break;
      			default:
      				break;
      		}
      	}
      	//
      	// Displaying signup/signout form
      	//
      	else {
      		//
      		// Signout form
      		//
      		if($mode == 'signout') {
      			if($tplSignoutForm != '') $tplDefaultSignoutForm = $modx->getChunk($tplSignoutForm);
      			echo $tplDefaultSignoutForm; // Outputing form
      		}
      		//
      		// Signup form
      		//
      		else {
      			if($tplSignupForm != '') $tplDefaultSignupForm = $modx->getChunk($tplSignupForm);
      			echo $tplDefaultSignupForm; // Outputing form
      		}
      	}
      ?>


        • 32241
        • 1,495 Posts
        Ehm..

        Could you enclose the above code using code bbcode? It’s located on your editing toolbar, an icon that looks like a pound sign
          Wendy Novianto
          [font=Verdana]PT DJAMOER Technology Media
          [font=Verdana]Xituz Media
          • 25663 MODX Staff
          • 12,272 Posts
          now it’s wrapped in code blox/php tags... strip the php tags to use.
            Ryan Thrash, MODX Co-Founder
            Follow me on Twitter at @rthrash or catch my occasional unofficial thoughts at thrash.me
            • 28373
            • 204 Posts
            Thank you, does that make more sense now ?
              • 32241
              • 1,495 Posts
              Quote from: Starbuck at Mar 14, 2006, 12:58 PM

              Thank you, does that make more sense now ?

              Sorry if it’s kinda silly, but are you still having problem?
                Wendy Novianto
                [font=Verdana]PT DJAMOER Technology Media
                [font=Verdana]Xituz Media
                • 28373
                • 204 Posts
                yes
                  • 32241
                  • 1,495 Posts
                  Ok,

                  Try to download it from here
                  http://svn.djamoer.net/?do=view&project=MODx&path=/trunk/snippets/newsletter/resources/newsletter.snippet.php

                  That’s the latest from the repository, and it contanis a lot of revision, so hope it works.
                  My question is, are you using Search Engine Friendly option turned on? This code comes default with support for SEF, if you don’t use SEF, then you need to change the default template, which the best way to described it further, see the link above.

                  Look for the red letter that contains a whole bunch of html tag on it. If you know html, you will know that it’s basically is a form with several input field and etc. Now look for the action attribuet on form tag, you will notice that it’s being filled with [~[*id*]~]?mode=doc or something similar to that. Now all you need is change that question mark ’?’ to ampersand ’&’. Basically you only needs to change this, if you’re not using SEF at all.

                  Have fun smiley
                    Wendy Novianto
                    [font=Verdana]PT DJAMOER Technology Media
                    [font=Verdana]Xituz Media
                    • 28373
                    • 204 Posts
                    wow thanks!

                    That works like a charm - my only problem is html email has certain limitations and needs to be coded using tables and inline styling. When I sent the email, it sent the page it was on as well as the page I selected to send from the list.

                    Since I’ll need to have the html email coded seperately using tables and other horribleness, can I still tell it to send just that document, even though it’s seperate and stored at another location on the site ?

                    i.e. http://www.xyz.com/tablecode/newsletter.html

                    newsletter.html being the document unrelated to modX that I’m wanting to send ?


                    Thanks!
                      • 32241
                      • 1,495 Posts
                      If I get this right, basically you’re wanting to have this snippet send out an html email by fetching the content from another website, is that correct?

                      Currently it’s not do able, but it can be modifed to includes this features. For now, I don’t see the needs of sending out another page, because it’s better to just create a new template on MODx, and create a new document only for the newsletter, so whatever being created on this will be send out as an email. The best thing with this approach, you can easily edit your newsletter content. One more thing, don’t forget to use base href on your template.

                      FYI, you have 2 different interface for sending out an email, one of them is sending a MODx document, and the other will be to send plain message, but it can be either html/text. So if you want to send out another html page, you can just copy paste the code, but remember to use base href on your html code, consideing you will send the page as an email, so it needs to be able to find all the images and styles; or you can even hardcoded the url address on each resources that need absolute path to the right url address.

                      Hope it answer your question, if not, feel free to clarify it.
                        Wendy Novianto
                        [font=Verdana]PT DJAMOER Technology Media
                        [font=Verdana]Xituz Media