We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 4172
    • 5,888 Posts
    Hello,
    I made this snippet for calling eForm with &runSnippet=`eFormEvent` &eformOnBeforeMailSent=`eFormMailer` to send serial-mails with dynamic content and dynamic subject wich replaces the placeholder like [-placeholderfield-].
    It seems to work well.
    But is there a way to get the attachments to send them with the mails?
    Thank you for help

    <?php
    //functions for eForm events
    //eFormEvent
    		/*---------------------------------------------------------------		
    		eFormMailer
    		Version: 0.1 [Alpha 1]
    		Author: Bruno Perner
    		---------------------------------------------------------------
    		Requirements:
    			eForm 1.4+
    		---------------------------------------------------------------
    		Use:
    			- Takes validated eForm data to send serial-mails with dynamic content. 								
    			- Use Placeholders in subject and comments field like [-fieldname-]				  
    		---------------------------------------------------------------*/
    //     The following fields can be used (extra formatting can be required):
    //     id
    //     internalKey
    //     fullname
    //     role
    //     email
    //     phone
    //     mobilephone
    //     blocked
    //     blockeduntil
    //     blockedafter
    //     logincount
    //     lastlogin
    //     thislogin
    //     failedlogincount
    //     dob (this means "date of birth")
    //     gender
    //     country
    //     state
    //     zip
    //     fax
    //     photo
    //     comment    
    //     username
    //     all custom-fields of web_user_attributes_extended 
    //		
    
    #::::::::::::::::::::::::::::::::::::::::
    #  
    #  input fields name="..." in eForm template for saving the Mail as Document:
    #    savemail    - set to 1 to save the mail as Document
    #    folder      - folder id where comments are stored
    #    makefolder  - set to 1 to automatically convert the parent document to a folder. Defaults to 0
    #    template    - name of template to use for news post
    #    hidemenu  - sets the flag to true or false (1|0) as to whether or not it shows in the menu. defaults to false (0)
    #    aliastitle  - set to 1 to use page title as alias suffix. Defaults to 0 - date created.
    #    clearcache  - when set to 1 the system will automatically clear the site cache after publishing an article.
    #  
    #::::::::::::::::::::::::::::::::::::::::		
    		
    function eFormMailer( &$fields ){
    global $modx;
    
    $members=getMembers($fields['group']);
    
    //attr2array('hallo');
    
    foreach ($members as $member){
    $mergedfields=array_merge($fields,$member);	
    
    $fields['comments']=MergePH($fields['comments'], $mergedfields);
    $fields['subject']=MergePH($fields['subject'], $mergedfields);
    $fields['email']=$member['email'];
                   // echo $fields['email'];
                   // echo $fields['group'];
                   // echo $fields['fullname'];
    sendMail($fields);		
    }
    
    //return the last mergedfields for the thankyou-page
    $mergedfields['mgcomments']=$fields['comments'];
    $mergedfields['mgsubject']=$fields['subject'];
    $mergedfields['mgemail']=$fields['email'];
    
    $fields=$mergedfields;
    
    if ($fields['savemail']=='1'){
    	$fields['newdocid']=saveMailToDoc($fields);
    }
    
                   //return succes
    		return true;
    	}	
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    function sendMail($fields){
    
    		global $modx;
    
    		include_once "manager/includes/controls/class.phpmailer.php";
    
    				# send form
    				//defaults to html so only test sendasText
    				//todo
    				$isHtml = ($sendAsText==1 || strstr($sendAsText,'report'))?false:true;
    					
    					//echo $fields['email'];
    					$to = $fields['email'];
    					$mail = new PHPMailer();
    					$mail->IsMail();
    					$mail->CharSet = $modx->config['modx_charset'];
    					$mail->IsHTML($isHtml);
    					$mail->From		= $fields['sender'];
    					$mail->FromName	= $fields['name'];
    					$mail->Subject	= $fields['subject'];
    					$mail->Body		= $fields['comments'];
    					AddAddressToMailer($mail,"replyto",$fields['sender']);
    					AddAddressToMailer($mail,"to",$fields['email']);
    					//AddAddressToMailer($mail,"cc",$cc);
    					//AddAddressToMailer($mail,"bcc",$bcc);
    					AttachFilesToMailer($mail,$attachments);
    					if(!$mail->send()) return 'Main mail: ' . $_lang['ef_mail_error'] . $mail->ErrorInfo;
    	
    
    		return true;
    	}
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function MergePH($docText, $docFields, $vClasses='') {
    	global $formats;
    	$lastitems;
    	if(!$docText) return '';
    
    	preg_match_all('~\[\-(.*?)\-\]~', $docText, $matches);
    	for($i=0;$i<count($matches[1]);$i++) {
    		$name = $matches[1][$i];
    //mod - splitting name:value to get proper docFields key
    		list($listName,$listValue) = explode(":",$name);
    		$value = isset($docFields[$listName])? $docFields[$listName]:"";
    //end mod
    
    		$docText = str_replace("[-$name-]",$value,$docText);
    }
    	return $docText;
    }	
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function getMembers($webGroup){
    
    global $modx;
    
    
    // Language strings
    $sm_lang['no_group'] = "No group was provided.";
    $sm_lang['invalid_group'] = "An invalid webgroup was specified.";
    $sm_lang['no_members_found'] = "No members found.";
    
    // No usersettings below this line
    // -------------------------------
    
    // Get a list of users from the DB. No API call for this :-(
    
    $fields='wu.username, wua . * , wuae . * ';
    $wuae= $modx->getFullTableName('web_user_attributes_extended');
    $wu= $modx->getFullTableName('web_users');
    $wua= $modx->getFullTableName('web_user_attributes');
    $wgn= $modx->getFullTableName('webgroup_names');
    $wg= $modx->getFullTableName('web_groups');
    $sql= "
    SELECT {$fields} FROM {$wua} wua
    JOIN {$wu} wu ON wu.id = wua.internalKey
    JOIN {$wuae} wuae ON wuae.internalKey = wua.internalKey 
    JOIN {$wg} wg ON wg.webuser = wua.internalKey 
    JOIN {$wgn} wgn ON wgn.name = '{$webGroup}' AND wgn.id = wg.webgroup 
    ";
    
    $webusers = $modx->db->query($sql);
    $count = $modx->db->getRecordCount($webusers);
      
      $members=array();
      while ($user = $modx->db->getRow($webusers))
      {
      array_push($members,$user);
      }
    return $members;
    }
    //////////////////////////////////////////////////////////////////////////////////////////
    function saveMailToDoc($fields){
    	global $modx;
    // code from newspublisher	
    
                // get created date
                $createdon = time();
                // set alias name of document used to store articles
                if(!$fields['aliastitle']) $alias = 'article-'.$createdon;
                else {
                    $alias = $modx->stripTags($fields['subject']);
                    $alias = strtolower($alias);
                    $alias = preg_replace('/&.+?;/', '', $alias); // kill entities
                    $alias = preg_replace('/[^\.%a-z0-9 _-]/', '', $alias);
                    $alias = preg_replace('/\s+/', '-', $alias);
                    $alias = preg_replace('|-+|', '-', $alias);
                    $alias = trim($alias, '-');			
                    $alias = 'article-'.$modx->db->escape($alias);
                }
    
                $user = $modx->getLoginUserName();
                $userid = $modx->getLoginUserID();
    
                $title = $fields['subject'];
                $longtitle = $fields['subject'];
                $description = '';
                $introtext = '';
                $pub_date = $fields['pub_date'];
                $unpub_date = $fields['unpub_date'];
                $published = 1;
    
                // check published date
                if($pub_date=="") {
                    $pub_date="0";
                } else {
                    list($d, $m, $Y, $H, $M, $S) = sscanf($pub_date, "%2d-%2d-%4d %2d:%2d:%2d");
                    $pub_date = strtotime("$m/$d/$Y $H:$M:$S");
                    if($pub_date < $createdon) {
                        $published = 1;
                    }    elseif($pub_date > $createdon) {
                        $published = 0;	
                    }
                }
                // check unpublished date
                if($unpub_date=="") {
                    $unpub_date="0";
                } else {
                    list($d, $m, $Y, $H, $M, $S) = sscanf($unpub_date, "%2d-%2d-%4d %2d:%2d:%2d");
                    $unpub_date = strtotime("$m/$d/$Y $H:$M:$S");
                    if($unpub_date < $createdon) {
                        $published = 0;
                    }
                }
    
                // set menu index
                $mnuidx = $modx->db->getValue('SELECT MAX(menuindex)+1 as \'mnuidx\' FROM '.$modx->getFullTableName('site_content').' WHERE parent=\''.$folder.'\'');
                if($mnuidx<1) $mnuidx = 0;
    
                // post news content
                $flds = array(
                    'pagetitle'     => $title,
                    'longtitle'     => $longtitle,
                    'description' => $description,
                    'introtext'     => $introtext,
                    'alias'             => $alias,
                    'parent'            => $fields['folder'], 
                    'createdon'     => $createdon,
                    'createdby'     => ($userid>0 ? $userid * -1:0),
                    'editedon'        => '0',
                    'editedby'        => '0',
                    'published'     => $published,
                    'pub_date'        => $pub_date,
                    'unpub_date'    => $unpub_date,
                    'deleted'         => '0',
                    'hidemenu'        => $fields['hidemenu'],
                    'menuindex'     => $mnuidx,
                    'template'        => $fields['template'],
                    'content'         => $fields['comments']
                );
                $redirectid = $modx->db->insert($flds,$modx->getFullTableName('site_content'));
    
                // Doc group thing
                // look in save_content.processor.php for tips (or below)
                $lastInsertId = $modx->db->getInsertId();
    
                // Get doc groups based on $folder (parent id)
                $parentDocGroupsSql = "SELECT * FROM " . $modx->getFullTableName('document_groups'). " where document=".$fields['folder'];
                $parentDocGroupsRs = $modx->db->query($parentDocGroupsSql);
                $parentDocGroupsLimit = $modx->db->getRecordCount($parentDocGroupsRs);
                for ($pdgi = 0; $pdgi < $parentDocGroupsLimit; $pdgi++) { 
                    $currentDocGroup = $modx->db->getRow($parentDocGroupsRs);
                    $parentDocGroupsArray[$pdgi] = $currentDocGroup['document_group'];
                }
    
                // put the document in the document_groups it should be in
                // check that up_perms are switched on!
                if($modx->config['use_udperms']==1) {
                    if(is_array($parentDocGroupsArray)) {
                        foreach ($parentDocGroupsArray as $dgKey=>$dgValue) {
                            $insertDocSql = "INSERT INTO ".$modx->getFullTableName('document_groups')."(document_group, document) values(".stripslashes($dgValue).", $lastInsertId)";
                            $insertDocRs = $modx->db->query($insertDocSql);
                            if(!$insertDocRs){
                                exit;
                            }
                        } // end foreach
                    } // end if doc group array exists
                } // end if perms are used
    
                // Handle privateweb
                $modx->db->query("UPDATE ".$modx->getFullTableName("site_content")." SET privateweb = 0 WHERE id='$lastInsertId';");
                $privatewebSql =    "
                    SELECT DISTINCT ".$modx->getFullTableName('document_groups').".document_group 
                    FROM ".$modx->getFullTableName('document_groups').", ".$modx->getFullTableName('webgroup_access')." 
                    WHERE 
                    ".$modx->getFullTableName('document_groups').".document_group = ".$modx->getFullTableName('webgroup_access').".documentgroup 
                    AND 
                    ".$modx->getFullTableName('document_groups').".document = $lastInsertId;";
                    $privatewebIds = $modx->db->getColumn("document_group",$privatewebSql);
                    if(count($privatewebIds)>0) {
                        $modx->db->query("UPDATE ".$modx->getFullTableName("site_content")." SET privateweb = 1 WHERE id = $lastInsertId;");	
                    }
    
                    // And privatemgr
                    $modx->db->query("UPDATE ".$modx->getFullTableName("site_content")." SET privatemgr = 0 WHERE id='$lastInsertId';");
                    $privatemgrSql =    "
                        SELECT DISTINCT ".$modx->getFullTableName('document_groups').".document_group 
                        FROM ".$modx->getFullTableName('document_groups').", ".$modx->getFullTableName('membergroup_access')." 
                        WHERE 
                        ".$modx->getFullTableName('document_groups').".document_group = ".$modx->getFullTableName('membergroup_access')." .documentgroup 
                        AND 
                        ".$modx->getFullTableName('document_groups').".document = $lastInsertId;";
                        $privatemgrIds = $modx->db->getColumn("document_group",$privatemgrSql);
                        if(count($privatemgrIds)>0) {
                            $modx->db->query("UPDATE ".$modx->getFullTableName("site_content")." SET privatemgr = 1 WHERE id = $lastInsertId;");	
                        }
                // end of document_groups stuff!
    
                if(!empty($makefolder)) {
                    // convert parent into folder
                    $modx->db->update(array('isfolder'=>'1'),$modx->getFullTableName('site_content'),'id=\''.$folder.'\'');
                }
    
                // empty cache
                if($fields['clearcache']==1){
                    include_once $modx->config['base_path']."manager/processors/cache_sync.class.processor.php";
                    $sync = new synccache();
                    $sync->setCachepath("assets/cache/");
                    $sync->setReport(false);
                    $sync->emptyCache(); // first empty the cache		
                }
    return $lastInsertId; 
    }
    
    
    //////////////////////////////////////////////////////////////////////////////////////////
    //return empty string
    return '';
    ?>
      -------------------------------

      you can buy me a beer, if you like MIGX

      http://webcmsolutions.de/migx.html

      Thanks!
      • 4172
      • 5,888 Posts
      ....and the mail is now saved as document if you select this in the form
        -------------------------------

        you can buy me a beer, if you like MIGX

        http://webcmsolutions.de/migx.html

        Thanks!