horst

WireMailSmtp

179 posts in this topic

Wire Mail SMTP

An extension to the new WireMail base class that uses SMTP-transport

This module integrates EmailMessage, SMTP and SASL php-libraries from Manuel Lemos into ProcessWire. I use this continously evolved libraries for about 10 years now and there was never a reason or occasion not to do so. I use it nearly every day in my office for automated composing and sending personalized messages with attachments, requests for Disposition Notifications, etc. Also I have used it for sending personalized Bulkmails many times.

The WireMailSmtp module extends the new email-related WireMail base class introduced in ProcessWire 2.4.1 (while this writing, the dev-branch only).
 
Here are Ryans announcement.



Current Version 0.2.3

Install and Configure

Download the module into your site/modules/ directory and install it.

In the config page you fill in settings for the SMTP server and optionaly the (default) sender, like email address, name and signature.
You can test the smtp settings directly there. If it says "SUCCESS! SMTP settings appear to work correctly." you are ready to start using it in templates, modules or bootstrap scripts.


Usage Examples

The simplest way to use it:

$numSent = wireMail($to, $from, $subject, $textBody);

$numSent = wireMail($to, '', $subject, $textBody); // or with a default sender emailaddress on config page 

This will send a plain text message to each recipient.
 
You may also use the object oriented style:

$mail = wireMail(); // calling an empty wireMail() returns a wireMail object

$mail->to($toEmail, $toName);
$mail->from = $yourEmailaddress; // if you don't have set a default sender in config
                                 // or if you want to override that
$mail->subject($subject);
$mail->body($textBody);

$numSent = $mail->send();

Or chained, like everywhere in ProcessWire:

$mail = wireMail();
$numSent = $mail->to($toEmail)->subject($subject)->body($textBody)->send(); 

Additionaly to the basics there are more options available with WireMailSmtp. The main difference compared to the WireMail BaseClass is the sendSingle option. With it you can set only one To-Recipient but additional CC-Recipients.

$mail = wireMail(); 

$mail->sendSingle(true)->to($toEmail, $toName)->cc(array('person1@example.com', 'person2@example.com', 'person3@example.com')); 

$numSent = $mail->subject($subject)->body($textBody)->send(); 

The same as function call with options array:

$options = array(
    'sendSingle' => true,
    'cc' => array('person1@example.com', 'person2@example.com', 'person3@example.com')
    );

$numSent = wireMail($to, '', $subject, $textBody, $options); 

There are methods to your disposal to check if you have the right WireMail-Class and if the SMTP-settings are working:

$mail = wireMail(); 

if($mail->className != 'WireMailSmtp') {
    // Uups, wrong WireMail-Class: do something to inform the user and quit
    echo "<p>Couldn't get the right WireMail-Module (WireMailSmtp). found: {$mail->className}</p>";
    return;
}

if(!$mail->testConnection()) {
    // Connection not working:
    echo "<p>Couldn't connect to the SMTP server. Please check the {$mail->className} modules config settings!</p>";
    return;
} 

Following are a ...


List of all options and features


testConnection () - returns true on success, false on failures


sendSingle ( true | false ) - default is false

sendBulk ( true | false ) - default is false, Set this to true if you have lots of recipients (50+)


to ($recipients) - one emailaddress or array with multiple emailaddresses

cc ($recipients) - only available with mode sendSingle, one emailaddress or array with multiple emailaddresses

bcc ($recipients) - one emailaddress or array with multiple emailaddresses

 
from = 'person@example.com' - emailaddress, can be set in module config (called Sender Emailaddress) but it can be overwritten here

fromName = 'Name Surname' - optional, can be set in module config (called Sender Name) but it can be overwritten here


priority (3) - 1 = Highest | 2 = High | 3 = Normal | 4 = Low | 5 = Lowest

dispositionNotification () or notification () - request a Disposition Notification


subject ($subject) - subject of the message

body ($textBody) - use this one alone to create and send plainText emailmessages

bodyHTML ($htmlBody) - use this to create a Multipart Alternative Emailmessage (containing a HTML-Part and a Plaintext-Part as fallback)

addSignature ( true | false ) - the default-behave is selectable in config screen, this can be overridden here
(only available if a signature is defined in the config screen)

attachment ($filename, $alternativeBasename = "") - add attachment file, optionally alternative basename


send () - send the message(s) and return number of successful sent messages


getResult () - returns a dump (array) with all recipients (to, cc, bcc) and settings you have selected with the message, the message subject and body, and lists of successfull addresses and failed addresses,


logActivity ($logmessage) - you may log success if you want

logError ($logmessage) - you may log warnings, too. - Errors are logged automaticaly
 
 
useSentLog (true | false) - intended for usage with e.g. third party newsletter modules - tells the send() method to make usage of the sentLog-methods - the following three sentLog methods are hookable, e.g. if you don't want log into files you may provide your own storage, or add additional functionality here

sentLogReset ()  - starts a new LogSession - Best usage would be interactively once when setting up a new Newsletter

sentLogGet ()  - is called automaticly within the send() method - returns an array containing all previously used emailaddresses

sentLogAdd ($emailaddress)  - is called automaticly within the send() method
 

Changelog: https://github.com/horst-n/WireMailSmtp/blob/master/CHANGELOG.md

 

Edited by horst
bumped to version 0.2.3
28 people like this

Share this post


Link to post
Share on other sites

Thanks for making this Horst! Tested here and got it working. I did have to modify your to() function (my fault, since I changed the WireMail interface for that function in the last update), but that was easy, and everything else worked (testing it with Gmail). I particularly liked being able to test the settings from the module screen.

Your getModuleInfo() returns singular=true.  The intention with WireMail is that it would be singular=false, so that you'd start with a new/fresh instance every time you get it from wireMail() or $modules->get('WireMailSmtp'). Otherwise, it might already have the to/from/subject/body settings from the last use still in there. 

Why necessary to specify the sender email address in the module settings? Will this prevent someone from being able to change the $mail->from(); address from the API side? Also was wondering why it's necessary to specify the hostname in the module settings? Does it go into an envelope from header or something? 

1 person likes this

Share this post


Link to post
Share on other sites

Thanks for making this Horst! Tested here and got it working. I did have to modify your to() function (my fault, since I changed the WireMail interface for that function in the last update), but that was easy, and everything else worked (testing it with Gmail). I particularly liked being able to test the settings from the module screen.

Your getModuleInfo() returns singular=true. The intention with WireMail is that it would be singular=false, so that you'd start with a new/fresh instance every time you get it from wireMail() or $modules->get('WireMailSmtp'). Otherwise, it might already have the to/from/subject/body settings from the last use still in there.

Yes have read it in SwiftMailer-Thread before. I will update the module after posting this.  :)

Also have allready downloaded a fresh wire folder from Github.

Why necessary to specify the sender email address in the module settings? Will this prevent someone from being able to change the $mail->from(); address from the API side?

Lazyness! If using the object->style (not the procedural function call), there is no need to specify it when a default sender is set in config settings. But it could be overwritten by the $mail->from. Maybe I should make it an optional setting, not a required one.

I have thought of a setting that prevents overwriting settings from the config screen. Default Sender is the only one valid. Recipients could be a whitelist (currently a textarea under tab advanced) and a checkbox to include emailaddresses from PW users or not. If a security restriction like this is implemented and checked, mails only get send to recipients from the valid_recipients list.

Is this a useful feature?

Also was wondering why it's necessary to specify the hostname in the module settings? Does it go into an envelope from header or something?

This is used when connecting to the SMTP-Server. You find it as the first entry in the Received header of every received mail. For example my local test account is called pw4.kawobi.local, this is what the headers look:

Return-Path: <xxxx@xxxxxxx.xx>
X-Original-To: xxxx@xxxxxxx.xx
Received: from pw4.kawobi.local (dslb-084-099-066-105.t-online [84.99.66.105])
	by xyz1234.smtpserver.com (Postfix) with ESMTPSA id 5EDBC2C004E6
	for <xxxx@xxxxxxx.xx>; Mon,  3 Mar 2014 19:00:10 +0100 (CET)
To: Peter Mueller <xxxx@xxxxxxx.xx>
Subject: WireMailSmtp Test MultipartAlternative

As far as I know, this is common usage, but with most clients you cannot influence the chosen name.

EDIT: Module is updated to v0.0.4, look into the first post please. :)

2 people like this

Share this post


Link to post
Share on other sites

I have updated the class to version 0.0.5 and also have edited the first post of this thread (added some short examples and a list of available options/methods).

Now per default the module sends multiple messages in a loop, (one for each TO-recipient) like the base class do.

Additionaly you can call sendBulk to send larger amount of messages at once in an optimized manner, - or you can call sendSingle to set the module to allow only one TO-recipient but additionally CC-recipients. More information are now in the first post here.

6 people like this

Share this post


Link to post
Share on other sites

Hhm, sorry! With the 0.0.5 I have added a configuration option that lets you choose when an optional MailSignature should be send, but have left a boolean true somewhere in the code that overrides always these setting. :-[

Have corrected this now and committed the v 0.0.6 to GitHub. (ZIP)

2 people like this

Share this post


Link to post
Share on other sites

Hey Horst,

do you think this class is usable for a newsletter? (Remembering our little talk about it :) )

/ Nico

Share this post


Link to post
Share on other sites

Yes it is. I think with Ryan's changes given to all email-related stuff it is much easier as of it was as we have talked about it.

If I remember right, you call only at one point in your code php's mail function. This part maybe get reorganized depending of if it is called a single time (then it is just fine to pass all recipients into wireMail at this point) or if it is within a loop (called multiple times), than you have to change this.

You have to pass $options array('sendBulk'=>true) with the wireMail($to, $from, $subject, $textBody, $options);

You need to update the wire folder to 2.4.1 (the current dev branch)!

EDIT:

There is only rare support built in for bulk mail sending, at least when focusing on robustness and comfortable handling of large amounts.

Actually there is only a check in it that skips duplicate emailaddress entries. Actually it is needed that the script runs within one request from start to end. If it gets interrupted somehow you end up in a mess. I think it is fine to use it with small amounts of recipients actually (0-200).

Oh, - while writing here I got an idea how to implement a simple hookable feedback for that. I will try this and add it to the module if it comes out functional.

EDIT2: added! see next post :)

Share this post


Link to post
Share on other sites

updated to version 0.0.7

Added a new flag that tells the send() method to make usage of the new logging methods for handling large amounts of recipients by using permanent storage across multiple script calls:

  • useSentLog( true | false )
    Tells the send()-method to make usage of the SentLog-methods! 
     
  • sentLogReset()
    It starts a new LogSession - Best usage would be interactively once when setting up a new Newsletter.
     
  • sentLogGet()
    is called automaticly by the send() method - returns an array containing all previously used emailaddresses
     
  • sentLogAdd($emailaddress)
    is called automaticly by the send() method - stores each successfully sent emailaddress into the provided log

This is intended to use within third party modules for newsletter systems. All three sentLog methods are made hookable, so, e.g. if you don't want log into files you may provide your own storage, or add additional functionality here.

The usage is really simple, I think. When starting a new Newsletter Session, you once have to call wireMail()->sentLogReset() to clear any previously stored content in the log. This best should be done manually / interactively I think.

After that you only have to set the useSentLog flag to true, e.g by passing an options array into the procedural function call

$options = array(
    'sendBulk' => true,
    'useSentLog' => true
    );

$numSent = wireMail($to, $from, $textBody, $options);

or in object-oriented style like this

$numSent = wireMail()->sendBulk(true)->useSentLog(true)->to($to)->from($from)->body($textBody)->send();

That's all. Now you can call your newsletter sending script multiple times (for example bind to lazy cron) and no recipient get lost nor will receive multiple messages.

No more worries about script timeouts or other interruptions, just call your script in regular intervals, but ensure that only one instance is running at the time and not multiple in parallel. It would not mess up the logfile because it uses filelocking, but you may get trouble with your SMTP provider if you stress the server. :lol:

PS: @Nico: want to test it in the near future?

6 people like this

Share this post


Link to post
Share on other sites

Hello horst, i have installed and tried WireMailSmtp too and installing and sending mail works fine.

But i also noted that sending a form with more then 1 file field will send only a link to the first attachment. The second attachment is always 0b (in the email body). While in the FormBuilder Entries both files are uploaded correctly.

Seems like a little bug in the WireMail class processing the second file field incorrectly.

Share this post


Link to post
Share on other sites

I don't know FormBuilder.

wireMail()->attachment() needs an absolute path for every (disk) file it should attach to a message. You can pass it as array or have to call it multiple times. Here are all is working as expected.

Maybe you can debug what is passed to the attachment function when running with FormBuilder?

You can call a log here

wire('log')->save( "debug_attachments", strtolower(__FUNCTION__).' :: '.serialize($filenames));   // ATTENTION this is $filename(s) ending with s

and here

wire('log')->save( "debug_attachments", strtolower(__FUNCTION__).' :: '.serialize($filename));   // ATTENTION this is $filename, without s

Trying this with passing an array logs something like:

2014-03-11 14:04:36	guest	http://pw4.kawobi.local/mailtest/	attachments :: a:2:{i:0;s:75:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/hyatt2.0x100.jpg";i:1;s:79:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/westin_interior1.jpg";}
2014-03-11 14:04:36	guest	http://pw4.kawobi.local/mailtest/	attachfile :: s:75:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/hyatt2.0x100.jpg";
2014-03-11 14:04:36	guest	http://pw4.kawobi.local/mailtest/	attachfile :: s:79:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/westin_interior1.jpg";

Calling it multiple times (2) with string filenames:

2014-03-11 14:10:10	guest	http://pw4.kawobi.local/mailtest/	attachments :: s:75:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/hyatt2.0x100.jpg";
2014-03-11 14:10:10	guest	http://pw4.kawobi.local/mailtest/	attachments :: s:79:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/westin_interior1.jpg";
2014-03-11 14:10:10	guest	http://pw4.kawobi.local/mailtest/	attachfile :: s:75:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/hyatt2.0x100.jpg";
2014-03-11 14:10:10	guest	http://pw4.kawobi.local/mailtest/	attachfile :: s:79:"W:/WEB_MIRRORS/_ProcessWire/pw4/htdocs/site/assets/files/1/westin_interior1.jpg";
3 people like this

Share this post


Link to post
Share on other sites

@horst thank you for helping and pointing out a way to log the file names to see what is going on.

I have placed both lines inside the WireMailSmtp.module and posted the form a few times to find out that nothing is logged. The code is right because putting the following line in the __construct() created the expected log file correctly.

wire('log')->save( "debug_attachments", "tralalala");
I came to the conclusion that form builder is not realy sending the files as attachments. All it does is save the attachments to /assets/cache/form-builder/form-x/entry-x/ and rendering a 'special' link to those files. So now i'm sure the bug is form-builder related and not in your WireMailSmtp and/or WireMailSwiftMailer module.

I will report it in the form-builder forum and see if i can find out something more to backup the bug report with.

Update: Haha Ryan is always 3 steps ahead :) I found this line in InputfieldFormBuilderFile.module

// @todo this is producing invalid file links when more than one file on the page

Edited by Raymond Geerts
3 people like this

Share this post


Link to post
Share on other sites

@Raymond: I don't know how FormBuilder works, where and how you can connect the uploaded files to the WireMail classes. If you find a solution it would be kind if you can post it here.

Share this post


Link to post
Share on other sites

hi horst, thank you for this module, works great.

i'm interested in the "You can hook into it if you want use alternative stores for it" thing from a template to get a sentlog for each page, can you give me a tip how to achieve this?

Share this post


Link to post
Share on other sites

ah ok, works this way.

wire()->addHook("wireMail::sentLogReset", function(HookEvent $event) {	
		$filename = wire('config')->paths->logs . 'wiremailsmtp_sentlog_' .wire('page')->name. '.txt';
		@touch($filename);
		$res = file_put_contents($filename, '', LOCK_EX );
		if(false===$res || 0!==$res || !file_exists($filename) || !is_readable($filename) || !is_writeable($filename)) {
			$this->logError('Cannot reset Content of the SentLog: ' . $filename);
			throw new WireException('You want to make usage of the SentLog-feature, but cannot reset Content of the SentLog: ' . basename($filename));
		}
		$event->replace = true;
		$event->return = 0===$res ? true : false;	
	
});
1 person likes this

Share this post


Link to post
Share on other sites

@Horst,

great module, many thanks for your work on this! Got attachments sending and works perfectly....

Got a couple of questions; first thing is that my email client is showing the wrong time sent on the emails, specifically Outlook for Mac; webmail, apple mail and android mail are all showing the correct sent time; just wondering why Outlook is showing the sent time as 4 hours before the actual time sent - could it be interpreting the headers differently? Other than these messages sent by WiremailSMTP, outlook shows the correct time sent...

** Update - i'm now using mandrill for the smtp and this has fixed the time being wrong on Outlook; not sure if it is the server, or if Mandrill is cleaning up/altering some part of the email code itself;

2nd question is how might i use logActivity ($logmessage) to save that activity into a textarea field on my processwire page that the email is generating from?; would be cool to show a field with the send log right on that page;

another question which isn't really directly related to the module, is how one might use images within the RTE and be able to have the email display the images; it would require replacing the relative image paths in TinyMCE with the absolute paths, but i'm not sure how to get started on that...[for now i have a hanna code that inserts the site's base path; kills the image in the editor, but it shows in the email...

Share this post


Link to post
Share on other sites

I finally got around to installing and configuring this module today.  Thank you for making this available as a ProcessWire module.  Everything worked fine and you should be commended for a quality piece of work.

1 person likes this

Share this post


Link to post
Share on other sites

Got a couple of questions; first thing is that my email client is showing the wrong time sent on the emails, specifically Outlook for Mac; webmail, apple mail and android mail are all showing the correct sent time; just wondering why Outlook is showing the sent time as 4 hours before the actual time sent - could it be interpreting the headers differently? Other than these messages sent by WiremailSMTP, outlook shows the correct time sent...

The Date header what is sent together with the emails is configured this way:

date("D, j M Y H:i:s \G\M\T P")

It results in the current GMT and the local difference in P.

AFAIK that's the common way according to the RFCs.

2nd question is how might i use logActivity ($logmessage) to save that activity into a textarea field on my processwire page that the email is generating from?; would be cool to show a field with the send log right on that page;

logActivity isn't meant to hook into. But you can get data from the logfile with tail() or something.

The logfile is under $config->paths->logs . WireMailSmtp::LOG_FILENAME_ACTIVITY . '.txt'

Edited by horst
4 people like this

Share this post


Link to post
Share on other sites

@horst - thanks, this time difference thing is probably related to the actual server location vs the config->timezone ? does your module use the config->timezone setting to set that?

regarding the whole logging thing, i feel stupid, i'm pretty much lost even after reading this thread 5 times... no idea how to simply log the success of a mail being sent, either to a log file, or to a field on my page... for now i do this which is ok for the moment:

                        // Send
                        $sendLog = 'Number Sent: ';
                        $sendLog .=    $mail->send();
                        
                        // Logging
                        $email_log = $message->email_log;
                        $email_log .= "\n". $sendLog;
                        $message->email_log = $email_log;
                        $message->of(false);
                        $message->save();

Share this post


Link to post
Share on other sites

@Macrura: regarding the logging, there are already functions that do the logging into files if you enable it like explained here.

If you don't want use the default logging files, you need to hook into the logging functions by e.g. creating a module with your logging functions or by defining the hooks on a template like MartinD described here.

But can you explain a bit more how you setup your mail recipients? How many recipients do you use (bulk or single)?

If you use bulk sending, do you have an admin page where you initialize the mail sending? (add / select recipients to / from a collection?)

Or do you prefer to do this ((partially) hardcoded?) in a template file only?

I can write some lines of example code if I know a bit more of your setup. :)

EDIT:

regarding the Date Header: https://github.com/horst-n/WireMailSmtp/blob/master/WireMailSmtpAdaptor.php#L351

It simply uses the PHP date function to output the current date-time. But you may try using the php gmdate function instead and look if it solves the issue.

You simply need to change date to gmdate in line 351 of WireMailSmtpAdaptor.php.

Edited by horst
forgot to answer to the date thing
1 person likes this

Share this post


Link to post
Share on other sites

Hi Horst -

thanks ! i'm using PW pages for the email and i have contacts stored in pages and then i can use asmselect for choosing who to send to, 1 or more...

so for multiple i use the recipients array

// Recipients
if($message->recipients->count()) {
	$recipients = array();
	foreach($message->recipients as $recipient) {
		$recipients[] = $recipient->title . ' <' . $recipient->email . '>';
		}
	$mail->to($recipients); 
} 

but i was thinking that I want to personalize the emails, so i would need to refactor the code to start a loop with the recipients and then run a string replace on the {{name}} placeholder in the email...

how does this relate to the bulk option?

thanks also about the gmdate  - will look at that tonight..

cheers!

Share this post


Link to post
Share on other sites

i think what was happening then with the date/time is that it is getting server time, as opposed to processwire time..

$this->emailMessage->SetHeader("Date", date("D, j M Y H:i:s \G\M\T P"));

so the problem could be for someone who is using a server in a different timezone

could we override this at the template/api level?
 

Also  - to elaborate more on this use case: last year i found it necessary to setup future sending emails to some clients (hosting invoices, payment plans etc..) and the only solution i could come up with was a service called LetterMeLater; but i thought while using it, that it would not be so hard to build this in processwire... so after about 2 hrs of setup i was able to replicate that and it works well, better than the original service i was using;

some features I've been able to accomplish over the last few days of creating this:

  • Select Identity to send from (and then uses that identity's signature)
  • Select multiple recipients
  • using a profields table, setup a schedule of sending, along with placeholder texts for each sending instance
  • Attachments to the message (page)
  • Attachments from a central repository of attachments
  • Links to documents/media
  • Render inline images in body and signatures (using string replacements for the image urls - prepending the site URL), also floating images are working
  • List of attached documents
  • Send offset (so you can select a due date and then offset to send the message X days early; this way you can set the dates in the table to the due dates and avoid date confusion)
  • Boilerplate insertion (select from an array of generic pre-written 'boilerplate' texts and insert them..)

this is going to really save a lot of time for me! I'm also using Mandrill to send these, so i can check to make sure they were sent, and also i can see if the recipient opened the message..

3 people like this

Share this post


Link to post
Share on other sites

i'm using PW pages for the email and i have contacts stored in pages and then i can use asmselect for choosing who to send to, 1 or more...

so for multiple i use the recipients array

Ok, if I got it right, you create a new page for a new message (regardless of single or bulk)

you select recipients via asm

create text, attach files, etc.

then at some point you need to save the page.

And now, - how do you execute the send? (scheduled or not)

Share this post


Link to post
Share on other sites

Right - and i have a cron job which runs every 5 min a 'mail_cron' template;

the template runs through some $pages->find and gets the messages to be sent;

I only use it to schedule emails (though if i needed to send it right away, i would set the send time for 5 min from now..)

this is the simple sending code:

https://gist.github.com/outflux3/797a18f5d2eaf0a87efb

but i'm working on changing over to this:

https://gist.github.com/outflux3/530b8adb1a6b7019d262

the only difference i added the table for sending multiple future-scheduled emails with the text placeholders;

so you could use the custom text placeholder to have an amount due and then in the message say "Amount Due by {{duedate}}: {{custom}}"

or you can just use the custom field to send slightly different messages for each instance..

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      First a note about my other modules...
      I have three existing modules that are similar in that they allow restrictions to be placed on repeating inputfields: Limit Repeater, Limit PageTable, Limit Table
      Restrict Repeater Matrix takes a different approach to the module configuration from those other modules. The module settings for Restrict Repeater Matrix are applied in the field settings rather in a module config screen. I think this new approach is better, but it means that it isn't practical to create different settings for different roles via the admin interface. Instead the module has a hookable method, allowing roles to be targeted and other advanced usages to be achieved via a hook. The result is that the module is more flexible.
      I intend to transition my other modules to the same approach over the coming weeks, but because this will result in breaking changes I will be releasing the updated modules under new names ("Restrict Repeater", etc) to avoid users upgrading via the Upgrades module without full awareness of the changes. The old modules will be marked as deprecated.
       
      Restrict Repeater Matrix
      A module for ProcessWire CMS/CMF. Allows restrictions and limits to be placed on Repeater Matrix fields.
      For any matrix type in a Repeater Matrix field you have the option to:
      Prevent drag-sorting of items Prevent cloning of items Prevent toggling of the published state of items Prevent trashing of items Limit the number of items that may be added to the inputfield Please note that restrictions and limits are applied with CSS/JS so should not be considered tamper-proof.
      Usage
      Install the Restrict Repeater Matrix module.
      For each matrix type created in the Repeater Matrix field settings, a "Restrictions" fieldset is added at the bottom of the matrix type settings:

      For newly added matrix types, the settings must be saved first in order for the Restrictions fieldset to appear. Set restrictions for each matrix type as needed. A limit of zero means that no items of that matrix type may be added to the inputfield.
      Setting restrictions via a hook
      Besides setting restrictions in the field settings, you can also apply or modify restrictions by hooking RestrictRepeaterMatrix::checkRestrictions. This allows for more focused restrictions, for example, applying restrictions depending on the template of the page being edited or depending on the role of the user.
      The checkRestrictions() method receives the following arguments:
      $field This Repeater Matrix field $inputfield This Repeater Matrix inputfield $matrix_types An array of matrix types for this field. Each key is the matrix type name and the value is the matrix type integer. $page The page that is open in ProcessPageEdit The method returns a multi-dimensional array of matrix types and restrictions for each of those types. An example of a returned array:

      Example hooks
      Prevent the matrix type "images_block" from being added to "my_matrix_field" in a page with the "basic-page" template:
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $page = $event->arguments('page'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && $page->template->name === 'basic-page') { $type_restrictions['images_block']['limit'] = 0; } $event->return = $type_restrictions; });  
      Prevent non-superusers from trashing any Repeater Matrix items in "my_matrix_field":
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && !$this->user->isSuperuser()) { foreach($type_restrictions as $key => $value) { $type_restrictions[$key]['notrash'] = true; } } $event->return = $type_restrictions; });  
      https://github.com/Toutouwai/RestrictRepeaterMatrix
    • By bernhard
      Hi,
      just stumbled over a little module that i built for my last project. it helped me to test performance of my rockdatatables module to generate 3000 random json datasets and i want to share it with you. maybe it saves some time for someone.
      https://gitlab.com/baumrock/RockDummyData/
      easy example:
      $rdd = $modules->get('RockDummyData'); for($i=0; $i<15; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); echo date("d.m.Y H:i:s", $dummy->timestamp) . "<br>"; } more advanced:
      $json = new stdClass(); $json->data = array(); $rdd = $modules->get('RockDummyData'); for($i=0; $i<3000; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); $obj = new stdClass(); $obj->name = $dummy->forename . ' ' . $dummy->surname; $obj->position = $dummy->job; $obj->office = $dummy->city; $obj->color = $dummy->color; $obj->start_date = new stdClass(); $obj->start_date->display = date('d.m.Y',$dummy->timestamp); $obj->start_date->sort = $dummy->timestamp; $obj->salary = rand(0,10000); $json->data[] = $obj; } echo json_encode($json); you have to store your random datasets on your own into the /data folder. there are several services for creating all kinds of random data on the web - if you know one service that allows sharing those datasets let me know and i can include common needed data into the module
    • By AndySh
      Hello!
      I need your assistance please. I purchased the module FormBuilder. Unfortunately, the module discontinued delivering customer submissions to e-mail box specified in the module settings. Direct mailing to the e-mail box works OK. The module settings stays the same and are correct, like "Send e-mail to administrator(s) is checked. The last version of FormBuilder 3.0 has been installed. Please advise how to resolve the issue becase I cannot get orders from customers anymore (((
    • By kixe
      As described in this post (https://processwire.com/talk/topic/8551-custom-urls-for-pages/?p=82742) the option 'Name Format Children' under the tab 'Family' in template settings doesn't work properly and also not as expected. I had a look inside the code and made some changes which are working properly, which offers much more options, more consistency and less code too.

      The result is the following. You have 3 Options for generating name and title, which could be combined in endless variations.
      Name is always derived from title, same like creating pages manually.
      type date: if function detects # character anywhere in the string, conversion will be: deletion of # and string will be used as format parameter for PHP date() function type field: if string is a fieldname of the parent page the value of this field will be used type string: if string doesn't fit to the 2 preceeding it will be taken as it is All parts (separated by comma) will be composed in the order of setting. You can use unlimited numbers of parts

      I made a pull request on github: https://github.com/ryancramerdesign/ProcessWire/pull/831

      Example screenshots

      Setting ...


      will result in


       
    • By kongondo
      FieldtypeRuntimeMarkup and InputfieldRuntimeMarkup
       
      Modules Directory: http://modules.processwire.com/modules/fieldtype-runtime-markup/
      GitHub: https://github.com/kongondo/FieldtypeRuntimeMarkup
       
      This module allows for custom markup to be dynamically (PHP) generated and output within a page's edit screen (in Admin).
       
      The value for the fieldtype is generated at runtime. No data is saved in the database. The accompanying InputfieldRuntimeMarkup is only used to render/display the markup in the page edit screen.
       
      The field's value is accessible from the ProcessWire API in the frontend like any other field, i.e. it has access to $page and $pages.
       
      The module was commissioned/sponsored by @Valan. Although there's certainly other ways to achieve what this module does, it offers a dynamic and flexible alternative to generating your own markup in a page's edit screen whilst also allowing access to that markup in the frontend. Thanks Valan!
       
      Warning/Consideration
      Although access to ProcessWire's Fields' admin pages is only available to Superusers, this Fieldtype will evaluate and run the custom PHP Code entered and saved in the field's settings (Details tab). Utmost care should therefore be taken in making sure your code does not perform any CRUD operations!! (unless of course that's intentional) The value for this fieldtype is generated at runtime and thus no data is stored in the database. This means that you cannot directly query a RuntimeMarkup field from $pages->find(). Usage and API
       
      Backend
      Enter your custom PHP snippet in the Details tab of your field (it is RECOMMENDED though that you use wireRenderFile() instead. See example below). Your code can be as simple or as complicated as you want as long as in the end you return a value that is not an array or an object or anything other than a string/integer.
       
      FieldtypeRuntimeMarkup has access to $page (the current page being edited/viewed) and $pages. 
       
      A very simple example.
      return 'Hello'; Simple example.
      return $page->title; Simple example with markup.
      return '<h2>' . $page->title . '</h2>'; Another simple example with markup.
      $out = '<h1>hello '; $out .= $page->title; $out .= '</h1>'; return $out; A more advanced example.
      $p = $pages->get('/about-us/')->child('sort=random'); return '<p>' . $p->title . '</p>'; An even more complex example.
      $str =''; if($page->name == 'about-us') { $p = $page->children->last(); $str = "<h2><a href='{$p->url}'>{$p->title}</a></h2>"; } else { $str = "<h2><a href='{$page->url}'>{$page->title}</a></h2>"; } return $str; Rather than type your code directly in the Details tab of the field, it is highly recommended that you placed all your code in an external file and call that file using the core wireRenderFile() method. Taking this approach means you will be able to edit your code in your favourite text editor. It also means you will be able to type more text without having to scroll. Editing the file is also easier than editing the field. To use this approach, simply do:
      return wireRenderFile('name-of-file');// file will be in /site/templates/ If using ProcessWire 3.x, you will need to use namespace as follows:
      return ProcessWire\wireRenderFile('name-of-file'); How to access the value of RuntimeMarkup in the frontend (our field is called 'runtime_markup')
       
      Access the field on the current page (just like any other field)
      echo $page->runtime_markup; Access the field on another page
      echo $pages->get('/about-us/')->runtime_markup; Screenshots
       
      Backend
       

       

       
      Frontend