Difference between revisions of "Extension:EmailPage"

From Organic Design wiki
(add heading)
(list recipients)
Line 38: Line 38:
  
 
var $recipients = array();
 
var $recipients = array();
 +
var $title;
 +
var $subject;
 +
var $header;
 +
var $cat;
 +
var $group;
 +
var $list;
 +
var $textonly;
  
 
# Constructor
 
# Constructor
Line 48: Line 55:
 
function execute($param) {
 
function execute($param) {
 
global $wgOut,$wgUser,$wgEmailArticleContactsCat,$wgGroupPermissions,$wgSitename;
 
global $wgOut,$wgUser,$wgEmailArticleContactsCat,$wgGroupPermissions,$wgSitename;
$title = Title::makeTitle(NS_SPECIAL,'EmailArticle');
 
  
# If the form has been posted, attempt to send the message
+
# Bail if no article title to send has been specified
if (isset($_REQUEST['sf_cat'])) $this->send($param);
+
if ($param == '') return $wgOut->addWikiText(wfMsg('ea_noarticle'));
elseif ($param == '') return $wgOut->addWikiText(wfMsg('ea_noarticle'));
 
  
 +
$this->title    = $param;
 +
$this->subject  = isset($_REQUEST['sf_subject'])  ? $_REQUEST['sf_subject']  : "\"$param\" article sent from $wgSitename";
 +
$this->header  = isset($_REQUEST['sf_header'])  ? $_REQUEST['sf_header']  : '';
 +
$this->cat      = isset($_REQUEST['sf_cat'])      ? $_REQUEST['sf_cat']      : '';
 +
$this->group    = isset($_REQUEST['sf_group'])    ? $_REQUEST['sf_group']    : '';
 +
$this->list    = isset($_REQUEST['sf_list'])    ? $_REQUEST['sf_list']    : '';
 +
$this->textonly = isset($_REQUEST['sf_textonly']) ? $_REQUEST['sf_textonly'] : false;
 +
 +
# If the send button was clicked, attempt to send and exit
 +
if (isset($_REQUEST['ea_send'])) return $this->send();
 +
 +
$special = Title::makeTitle(NS_SPECIAL,'EmailArticle');
 
$wgOut->addWikiText(wfMsg('ea_heading',$param));
 
$wgOut->addWikiText(wfMsg('ea_heading',$param));
 
$wgOut->addHTML(wfElement('form',array(
 
$wgOut->addHTML(wfElement('form',array(
 
'class'  => 'EmailArticle',
 
'class'  => 'EmailArticle',
'action' => $title->getLocalURL('action=submit'),
+
'action' => $special->getLocalURL('action=submit'),
 
'method' => 'POST'
 
'method' => 'POST'
 
),null));
 
),null));
Line 91: Line 108:
 
# Subject
 
# Subject
 
$wgOut->addWikiText(wfMsg('ea_subject'));
 
$wgOut->addWikiText(wfMsg('ea_subject'));
$subject = "\"$param\" article sent from $wgSitename";
+
$wgOut->addHTML(wfElement('input',array('type' => 'text', 'name' => 'sf_subject', 'value' => $this->subject, 'style' => "width:100%")));
$wgOut->addHTML(wfElement('input',array('type' => 'text', 'name' => 'sf_subject', 'value' => $subject, 'style' => "width:100%")));
 
  
 
# Header
 
# Header
 
$wgOut->addWikiText(wfMsg('ea_header'));
 
$wgOut->addWikiText(wfMsg('ea_header'));
$wgOut->addHTML("<textarea name=\"sf_header\"></textarea><br />\n");
+
$wgOut->addHTML("<textarea name=\"sf_header\">$header</textarea><br />\n");
 
$wgOut->addHTML("</fieldset>");
 
$wgOut->addHTML("</fieldset>");
  
 
# Submit buttons
 
# Submit buttons
$wgOut->addHTML(wfElement('input',array('type' => 'submit','name' => 'show','value' => wfMsg('ea_show'))));
+
$wgOut->addHTML(wfElement('input',array('type' => 'submit','name' => 'ea_send','value' => wfMsg('ea_send'))));
$wgOut->addHTML(wfElement('input',array('type' => 'submit','name' => 'send','value' => wfMsg('ea_send'))));
+
$wgOut->addHTML(wfElement('input',array('type' => 'submit','name' => 'ea_show','value' => wfMsg('ea_show'))));
  
 
$wgOut->addHTML('</form>');
 
$wgOut->addHTML('</form>');
 +
 +
# If the show button was clicked, render the list
 +
if (isset($_REQUEST['ea_send'])) return $this->send(false);
 
}
 
}
  
 
# Send the message to the recipients
 
# Send the message to the recipients
function send($title) {
+
function send($send = true) {
 
global $wgOut,$wgUser,$wgParser,$wgServer,$wgScript,$wgEmailArticleCss,$wgEmailArticleGroup,$wgEmailArticleAllowRemoteAddr;
 
global $wgOut,$wgUser,$wgParser,$wgServer,$wgScript,$wgEmailArticleCss,$wgEmailArticleGroup,$wgEmailArticleAllowRemoteAddr;
  
Line 117: Line 136:
  
 
$db      = &wfGetDB(DB_SLAVE);
 
$db      = &wfGetDB(DB_SLAVE);
$title    = Title::newFromText($title);
+
$title    = Title::newFromText($this->title);
 
$parser  = new Parser;
 
$parser  = new Parser;
 
$opt      = new ParserOptions;
 
$opt      = new ParserOptions;
$subject  = $_REQUEST['sf_subject'];
 
$header  = $_REQUEST['sf_header'];
 
$cat      = $_REQUEST['sf_cat'];
 
$group    = $_REQUEST['sf_group'];
 
$list    = $_REQUEST['sf_list'];
 
$textonly = $_REQUEST['sf_textonly'];
 
  
 
# Get contact article titles from selected cat
 
# Get contact article titles from selected cat
if ($cat) {
+
if ($this->cat) {
 
$cl    = $db->tableName('categorylinks');
 
$cl    = $db->tableName('categorylinks');
$result = $db->query("SELECT cl_from FROM $cl WHERE cl_to = '$cat' ORDER BY cl_sortkey");
+
$result = $db->query("SELECT cl_from FROM $cl WHERE cl_to = '{$this->cat}' ORDER BY cl_sortkey");
 
while ($row = mysql_fetch_row($result)) $this->addRecipient(Title::newFromID($row[0]));
 
while ($row = mysql_fetch_row($result)) $this->addRecipient(Title::newFromID($row[0]));
 
}
 
}
  
 
# Get email addresses from users in selected group
 
# Get email addresses from users in selected group
if ($group) {
+
if ($this->group) {
 
$u      = $db->tableName('user');
 
$u      = $db->tableName('user');
 
$ug    = $db->tableName('user_groups');
 
$ug    = $db->tableName('user_groups');
$result = $db->query("SELECT $u.user_email FROM $u,$ug WHERE $ug.ug_user = $user.user_id AND $ug.ug_group = '$group'");
+
$result = $db->query("SELECT $u.user_email FROM $u,$ug WHERE $ug.ug_user = $user.user_id AND $ug.ug_group = '{$this->group}'");
 
while ($row = mysql_fetch_row($result)) $this->addRecipient($row[0]);
 
while ($row = mysql_fetch_row($result)) $this->addRecipient($row[0]);
 
}
 
}
Line 149: Line 162:
 
$article = new Article($title);
 
$article = new Article($title);
 
$message = $article->getContent();
 
$message = $article->getContent();
if ($header) $message = "$header\n\n$message";
+
if ($this->header) $message = "{$this->header}\n\n$message";
  
 
# Convert the message text to html unless textonly
 
# Convert the message text to html unless textonly
if ($textonly == '') {
+
if ($this->textonly == '') {
  
 
# Parse the wikitext
 
# Parse the wikitext
Line 168: Line 181:
 
}
 
}
 
   
 
   
# Set up new mailer instance
+
# Send message or list recipients
$mail          = new PHPMailer();
+
$count = count($this->recipients);
$mail->From    = $wgUser->isValidEmailAddr() ? $wgUser->getEmail() : "wiki@$wgServer";
+
if ($count > 0) {
$mail->FromName = $wgUser->getName();
+
 
$mail->Subject  = $subject;
+
# Set up new mailer instance if sending
$mail->Body    = $message;
+
if ($send) {
$mail->IsHTML(!$textonly);
+
$mail          = new PHPMailer();
foreach ($this->recipients as $recipient) $mail->AddAddress($recipient);
+
$mail->From    = $wgUser->isValidEmailAddr() ? $wgUser->getEmail() : "wiki@$wgServer";
 +
$mail->FromName = $wgUser->getName();
 +
$mail->Subject  = $this->subject;
 +
$mail->Body    = $message;
 +
$mail->IsHTML(!$this->textonly);
 +
}
 +
else $msg = wfMsg('ea_listrecipients');
 +
 +
# Loop through recipients sending or adding to list
 +
foreach ($this->recipients as $recipient) $send ? $mail->AddAddress($recipient) : $msg .= "\n*$recipient";
 
   
 
   
# Send message and redirect client back to article or raise error
+
if ($send) {
if ($state = $mail->Send()) $msg = wfMsg('ea_sent',$title,count($this->recipients),$mail->FromName);
+
if ($state = $mail->Send()) $msg = wfMsg('ea_sent',$title,$count,$mail->FromName);
else $msg = wfMsg('ea_error',$title,$mail->ErrorInfo);
+
else $msg = wfMsg('ea_error',$title,$mail->ErrorInfo);
 +
}
 +
else $state = $count;
 +
}
 +
else $msg = wfMsg('ea_error',wfMsg('ea_norecipients'));
 +
 
 
$wgOut->addWikiText($msg);
 
$wgOut->addWikiText($msg);
 
return $state;
 
return $state;
Line 208: Line 235:
 
'ea_heading'          => "== Emailing [[$1]] article ==",
 
'ea_heading'          => "== Emailing [[$1]] article ==",
 
'ea_noarticle'        => "Please specify an article to send, for example [[Special:EmailArticle/Main Page]].",
 
'ea_noarticle'        => "Please specify an article to send, for example [[Special:EmailArticle/Main Page]].",
 +
'ea_norecipients'    => "No valid email addresses found!",
 +
'ea_listrecipients'  => "List of recipients:",
 
'ea_error'            => "'''Error sending [[$1]]:''' ''$1''",
 
'ea_error'            => "'''Error sending [[$1]]:''' ''$1''",
 
'ea_sent'            => "Article [[$1]] sent successfully to '''$2''' {{PLURAL:recipient|recipients}} by [[User:$3|$3]].",
 
'ea_sent'            => "Article [[$1]] sent successfully to '''$2''' {{PLURAL:recipient|recipients}} by [[User:$3|$3]].",
Line 215: Line 244:
 
                      . "*''separate items with , ; * \\n\n"
 
                      . "*''separate items with , ; * \\n\n"
 
                      . "*''list can contain templates and parser-functions''",
 
                      . "*''list can contain templates and parser-functions''",
'ea_show'            => "Show list",
+
'ea_show'            => "Resolve addresses",
 
'ea_send'            => "Send!",
 
'ea_send'            => "Send!",
 
'ea_subject'          => "Enter a subject line for the email",
 
'ea_subject'          => "Enter a subject line for the email",

Revision as of 02:51, 7 June 2007

<?php

  1. Extension:EmailArticle
Info.svg These are the MediaWiki extensions we're using and/or developing. Please refer to the information on the mediawiki.org wiki for installation and usage details. Extensions here which have no corresponding mediawiki article are either not ready for use or have been superseded. You can also browse our extension code in our local Subversion repository or our GitHub mirror.

Template:Php

  1. - Licenced under LGPL (http://www.gnu.org/copyleft/lesser.html)
  2. - Author: User:NadCategory:Extensions created with Template:SpecialPage
  3. - See http://www.mediawiki.org/wiki/Extension:EmailArticle for installation and usage details
  4. - Started: 2007-05-25 (based on http://www.organicdesign.co.nz/email-article.php from XmlWiki)

$wgShowExceptionDetails = true;

if (!defined('MEDIAWIKI')) die('Not an entry point.');

define('EMAILARTICLE_VERSION','0.0.1, 2007-06-05');

$wgEmailArticleGroup = 'postmaster'; # Users must belong to this group to send emails (empty string means anyone can send) $wgEmailArticleContactsCat = 'Contacts'; # This specifies the name of a category containing categories of contact articles $wgEmailArticleCss = 'EmailArticle.css'; # A minimal CSS article to embed in the email (eg. monobook/main.css without portlets, actions etc) $wgEmailArticleAllowRemoteAddr = array($_SERVER['SERVER_ADDR'],'127.0.0.1'); # Allow anonymous sending from these addresses $wgPhpMailerClass = dirname(__FILE__).'/phpmailer/class.phpmailer.php'; # From http://phpmailer.sourceforge.net/

if ($wgEmailArticleGroup) $wgGroupPermissions['sysop'][$wgEmailArticleGroup] = true;

$wgExtensionFunctions[] = 'wfSetupEmailArticle';

$wgExtensionCredits['specialpage'][] = array( 'name' => 'Special:EmailArticle', 'author' => 'User:Nad', 'description' => 'Send rendered article to an email address or list of addresses', 'url' => 'http://www.mediawiki.org/wiki/Extension:EmailArticle', 'version' => EMAILARTICLE_VERSION );

  1. If form has been posted, include the phpmailer class

if (isset($_REQUEST['sf_cat'])) require_once($wgPhpMailerClass);

  1. Define a new class based on the SpecialPage class

require_once("$IP/includes/SpecialPage.php"); class SpecialEmailArticle extends SpecialPage {

var $recipients = array(); var $title; var $subject; var $header; var $cat; var $group; var $list; var $textonly;

# Constructor function SpecialEmailArticle() { global $wgEmailArticleGroup; SpecialPage::SpecialPage('EmailArticle',$wgEmailArticleGroup); }

# Override SpecialPage::execute($param = ) function execute($param) { global $wgOut,$wgUser,$wgEmailArticleContactsCat,$wgGroupPermissions,$wgSitename;

# Bail if no article title to send has been specified if ($param == ) return $wgOut->addWikiText(wfMsg('ea_noarticle'));

$this->title = $param; $this->subject = isset($_REQUEST['sf_subject'])  ? $_REQUEST['sf_subject']  : "\"$param\" article sent from $wgSitename"; $this->header = isset($_REQUEST['sf_header'])  ? $_REQUEST['sf_header']  : ; $this->cat = isset($_REQUEST['sf_cat'])  ? $_REQUEST['sf_cat']  : ; $this->group = isset($_REQUEST['sf_group'])  ? $_REQUEST['sf_group']  : ; $this->list = isset($_REQUEST['sf_list'])  ? $_REQUEST['sf_list']  : ; $this->textonly = isset($_REQUEST['sf_textonly']) ? $_REQUEST['sf_textonly'] : false;

# If the send button was clicked, attempt to send and exit if (isset($_REQUEST['ea_send'])) return $this->send();

$special = Title::makeTitle(NS_SPECIAL,'EmailArticle'); $wgOut->addWikiText(wfMsg('ea_heading',$param)); $wgOut->addHTML(wfElement('form',array( 'class' => 'EmailArticle', 'action' => $special->getLocalURL('action=submit'), 'method' => 'POST' ),null)); $wgOut->addHTML('<fieldset><legend>'.wfMsg('ea_selectrecipients').'</legend>');

$wgOut->addHTML('

'); # If $wgEmailArticleContactsCat is set, create a select list of all categories if ($wgEmailArticleContactsCat) { $db =& wfGetDB(DB_SLAVE); $cl = $db->tableName('categorylinks'); $cats = '<option/>'; $result = $db->query("SELECT cl_from FROM $cl WHERE cl_to = '$wgEmailArticleContactsCat' ORDER BY cl_sortkey"); while ($row = mysql_fetch_row($result)) { $t = Title::newFromID($row[0]); if ($t->getNamespace() == NS_CATEGORY) $cats .= "<option>{$t->getText()}</option>"; } if ($cats) $wgOut->addHTML("\n");

}

# Allow selection of a group $groups = '<option/>'; foreach (array_keys($wgGroupPermissions) as $group) if ($group != '*') $groups .= "<option>$group</option>";

$wgOut->addHTML("\n"); $wgOut->addHTML('
From category:<select name=\"sf_cat\">$cats</select>
From group:<select name=\"sf_group\">$groups</select>

');

# Addition of named list $wgOut->addWikiText(wfMsg('ea_selectlist')); $wgOut->addHTML("<textarea name=\"sf_list\" rows=\"5\"></textarea>
\n"); $wgOut->addHTML('</fieldset>');

$wgOut->addHTML('<fieldset><legend>'.wfMsg('ea_compose').'</legend>');

# Subject $wgOut->addWikiText(wfMsg('ea_subject')); $wgOut->addHTML(wfElement('input',array('type' => 'text', 'name' => 'sf_subject', 'value' => $this->subject, 'style' => "width:100%")));

# Header $wgOut->addWikiText(wfMsg('ea_header')); $wgOut->addHTML("<textarea name=\"sf_header\">$header</textarea>
\n"); $wgOut->addHTML("</fieldset>");

# Submit buttons $wgOut->addHTML(wfElement('input',array('type' => 'submit','name' => 'ea_send','value' => wfMsg('ea_send')))); $wgOut->addHTML(wfElement('input',array('type' => 'submit','name' => 'ea_show','value' => wfMsg('ea_show'))));

$wgOut->addHTML('</form>');

# If the show button was clicked, render the list if (isset($_REQUEST['ea_send'])) return $this->send(false); }

# Send the message to the recipients function send($send = true) { global $wgOut,$wgUser,$wgParser,$wgServer,$wgScript,$wgEmailArticleCss,$wgEmailArticleGroup,$wgEmailArticleAllowRemoteAddr;

# Set error and bail if user not in postmaster group, and request not from trusted address if (!in_array($wgEmailArticleGroup,$wgUser->getGroups()) && !in_array($_SERVER['REMOTE_ADDR'],$wgEmailArticleAllowRemoteAddr)) { $wgOut->addWikiText(wfMsg('ea_autherror')); return false; }

$db = &wfGetDB(DB_SLAVE); $title = Title::newFromText($this->title); $parser = new Parser; $opt = new ParserOptions;

# Get contact article titles from selected cat if ($this->cat) { $cl = $db->tableName('categorylinks'); $result = $db->query("SELECT cl_from FROM $cl WHERE cl_to = '{$this->cat}' ORDER BY cl_sortkey"); while ($row = mysql_fetch_row($result)) $this->addRecipient(Title::newFromID($row[0])); }

# Get email addresses from users in selected group if ($this->group) { $u = $db->tableName('user'); $ug = $db->tableName('user_groups'); $result = $db->query("SELECT $u.user_email FROM $u,$ug WHERE $ug.ug_user = $user.user_id AND $ug.ug_group = '{$this->group}'"); while ($row = mysql_fetch_row($result)) $this->addRecipient($row[0]); }

# Recipients from list (expand templates in wikitext) $list = $parser->preprocess($list,$title,$opt); foreach (preg_split("/[\\x00-\\x1f,;*]+/",$list) as $item) $this->addRecipient($item);

# Compose the wikitext content of the article to send $article = new Article($title); $message = $article->getContent(); if ($this->header) $message = "{$this->header}\n\n$message";

# Convert the message text to html unless textonly if ($this->textonly == ) {

# Parse the wikitext $message = $parser->parse($message,$title,$opt,true,true)->getText();

# Convert any relative URL's to absolute $message = preg_replace("|\\W$wgScript|i",$wgServer.$wgScript,$message);

# Create a simple html wrapper with embedded CSS for the message content $article = new Article(Title::newFromText($wgEmailArticleCss)); $css = $article->getContent(); $head = "<head><style type=\"text/css\">$css</style></head>"; $message = "$head

$message

";

}

# Send message or list recipients $count = count($this->recipients); if ($count > 0) {

# Set up new mailer instance if sending if ($send) { $mail = new PHPMailer(); $mail->From = $wgUser->isValidEmailAddr() ? $wgUser->getEmail() : "wiki@$wgServer"; $mail->FromName = $wgUser->getName(); $mail->Subject = $this->subject; $mail->Body = $message; $mail->IsHTML(!$this->textonly); } else $msg = wfMsg('ea_listrecipients');

# Loop through recipients sending or adding to list foreach ($this->recipients as $recipient) $send ? $mail->AddAddress($recipient) : $msg .= "\n*$recipient";

if ($send) { if ($state = $mail->Send()) $msg = wfMsg('ea_sent',$title,$count,$mail->FromName); else $msg = wfMsg('ea_error',$title,$mail->ErrorInfo); } else $state = $count; } else $msg = wfMsg('ea_error',wfMsg('ea_norecipients'));

$wgOut->addWikiText($msg); return $state; }

# Add a recipient the list # - accepts title objects for article containing email address, or string of actual address function addRecipient($recipient) { if (is_object($recipient) && $recipient->exists()) { $article = new Article($recipient); if (preg_match('/[a-z0-9_.-]+@[a-z0-9_.-]+/i',$article->getContent(),$emails)) $recipient = $emails[0]; else $recipient = ; } if ($valid = User::isValidEmailAddr($recipient)) $this->recipients[] = $recipient; return $valid; }

}

  1. Called from $wgExtensionFunctions array when initialising extensions

function wfSetupEmailArticle() { global $wgLanguageCode,$wgMessageCache;

# Add the messages used by the specialpage if ($wgLanguageCode == 'en') { $wgMessageCache->addMessages(array( 'emailarticle' => "EmailArticle", 'ea_heading' => "== Emailing $1 article ==", 'ea_noarticle' => "Please specify an article to send, for example Special:EmailArticle/Main Page.", 'ea_norecipients' => "No valid email addresses found!", 'ea_listrecipients' => "List of recipients:", 'ea_error' => "Error sending $1: $1", 'ea_sent' => "Article $1 sent successfully to $2 recipients by $3.", 'ea_selectrecipients' => "Select recipients", 'ea_compose' => "Compose content", 'ea_selectlist' => "Additional recipients as article titles or email addresses\n" . "*separate items with , ; * \\n\n" . "*list can contain templates and parser-functions", 'ea_show' => "Resolve addresses", 'ea_send' => "Send!", 'ea_subject' => "Enter a subject line for the email", 'ea_header' => "Optionally you can add an introductory wikitext message to your email" )); }

# Add the specialpage to the environment SpecialPage::addPage(new SpecialEmailArticle()); } ?>