Source

lorea_production / elgg / mod / elggman / start.php

Full commit
<?php
error_reporting(E_ALL);

require_once 'post.php';
require_once 'topic.php';
require_once 'mail.php';
//require_once 'lib/Net/POP3.php';

// ListServe settings (not used)
// POP 3 Credentials
define('HOST','mail.artelibredigital.net');
define('LOGIN','info');
define('PASS','No+Info09');


/**
* Cronjob for listserve
*
* Used by CRON to periodically retrieve our discussion posts.
*
* @param unknown_type $hook
* @param unknown_type $entity_type
* @param unknown_type $returnvalue
* @param unknown_type $params
*/
function groupmailshot_cron($hook,$entity_type,$returnvalue, $params) {
	$pop3 = new Net_POP3();

	/*
	 * Connect to localhost on usual port
	 * If not given, defaults are localhost:110
	 */
	$pop3->connect(HOST, 110);

	/*
	 * Login using username/password. APOP will
	 * be tried first if supported, then basic.
	 */
	$pop3->login(LOGIN, PASS);
	if(0 == $pop3->numMsg()) {
		$resulttext = elgg_echo("Unable to get emails");
		return $returnvalue .$resulttext;
	}
	loop_through_emails($pop3);
	$pop3->disconnect();
}

/**
 * Send a notification via email using phpmailer
 *
 * @param ElggEntity $from The from user/site/object
 * @param ElggUser $to To which user?
 * @param string $subject The subject of the message.
 * @param string $message The message body
 * @param array $params Optional parameters (not used)
 * @return bool
 */
function groupmailshot_filtername($name) {
        $group_name = str_replace(' ','-' ,$name);
        $group_name = str_replace(']','' ,$group_name);
        $group_name = str_replace('[','' ,$group_name);
        $group_name = strtolower($group_name);
	return $group_name;
}
function groupmailshot_get_groupmail($group, $mailname, $separator="@") {
	$group_name = groupmailshot_filtername($group->name);
        $group_email = $group_name.$separator.$mailname;
	$parent = get_entity($group->container_guid);
	if ($parent instanceof ElggGroup)
		$group_email = groupmailshot_filtername($parent->name)."+".$group_email;
	return $group_email;
}

function groupmailshot_notify_handler(ElggUser $from, ElggUser $to, $topic, $comment, $new_post = NULL, $prev = NULL, array $params = NULL)
{
  $mailname = get_plugin_setting("mailname", "elggman");
  if (!$mailname) {
    return;
  }
  global $CONFIG,$SUBJECT_TITLE;
  // $message = html_entity_decode($comment->value, ENT_COMPAT,'UTF-8');
 $message = $comment->value;
  if (!$from)
    throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'desde'));

  if (!$to)
    throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'a'));

  if ($to->email=="")
    throw new NotificationException(sprintf(elgg_echo('NotificationException:NoEmailAddress'), $to->guid));
  
  $topic_guid = $topic->getGUID();
  $group = get_entity($topic->container_guid);
  $subject = "[".$group->name."] ".$topic->title;

  $site = get_entity($CONFIG->site_guid);

  $from_name = $from->name;

  $from_email = $from->email;
  $group_email = groupmailshot_get_groupmail($group, $mailname);
  $group_listid = groupmailshot_get_groupmail($group, $mailname, ".");

  if (check_entity_relationship($from->getGUID(), 'obfuscated_groupmailshot', $group->getGUID()) || !$from_email) {
    $from_email = $from->username . '@n-1.cc';
  }
  if (check_entity_relationship($to->getGUID(), 'starred_groupmailshot', $group->getGUID())) {
    if (!check_entity_relationship($to->getGUID(), 'flags_content', $group->getGUID()))
      return;
  }
  $footer = "\n_______________________________________________\n";
  $footer .= $group->name." mailing list\n";
  $footer .= $group_email . "\n";
 // $footer .= $CONFIG->wwwroot . 'mod/threaded_forums/topicposts.php?topic='.$topic_guid.'&group_guid='.$group->getGUID();
  $footer .= $CONFIG->wwwroot . 'pg/elggman/'.$group->getGUID().'/'.$topic_guid.'/'.$new_post->getGUID();


	$header_eol = "\r\n";
	if (
		(isset($CONFIG->broken_mta)) &&
		($CONFIG->broken_mta)
	)
		$header_eol = "\n"; // Allow non-RFC 2822 mail headers to support some broken MTAs
        $nposts = count_annotations($topic_guid, "", "", 'group_topic_post');
	if ($new_post)
        	$post_id = $new_post->getGUID();
	else
        	$post_id = $comment->id;
        $msg_id = "{$post_id}.{$topic_guid}@".$mailname;
        if (!empty($prev) || $nposts > 1) {
	    $subject = 'Re: '.$subject;
	}
	$from_line = $from_email;
	if ($from->name)
		$from_line = "{$from->name} <{$from_email}>";
        //echo($nposts.$msg_id);
	$headers = "From: {$from_line}{$header_eol}"
		. "Sender: {$group_email}{$header_eol}"
		. "Content-Type: text/plain; charset=UTF-8; format=flowed{$header_eol}"
  		. "MIME-Version: 1.0{$header_eol}"
  		. "Reply-To: <{$group_email}>{$header_eol}"
  		. "List-Id: <{$group_listid}>{$header_eol}"
  		. "List-Post: <mailto:{$group_email}>{$header_eol}"
                . "Precedence: list{$header_eol}"
                . "Message-Id: <{$msg_id}>{$header_eol}"
  		. "Content-Transfer-Encoding: 8bit{$header_eol}";
        if ($prev) {
		// threaded forums
                $first_post_id = $prev->getGUID();
                $resp_id = "{$first_post_id}.{$topic_guid}@".$mailname;
                $headers .= "In-Reply-To: <{$resp_id}>{$header_eol}";
	}
        elseif ($nposts > 1) {
		// normal forums
                $first_post = get_annotations($topic_guid, "", "", "", "", $nposts-2, 1);
                $first_post_id = $first_post[0]->id;
                $resp_id = "{$first_post_id}.{$topic_guid}@".$mailname;
                $headers .= "In-Reply-To: <{$resp_id}>{$header_eol}";
        }

	$subject = htmlspecialchars_decode($subject);
	$message = utf8_encode(html_entity_decode($message));
  	if (is_callable('mb_encode_mimeheader')) {
		$subject = mb_encode_mimeheader($subject,"UTF-8", "B");
  	}
  
	// Format message
	$message = preg_replace("/(<\/p.*>)/", "</p>\n", $message); // Add an xtra line after a paragraph tag
	$message = preg_replace("/(<br>)/", "<br>\n", $message); // Add an xtra line after a br
	$message = preg_replace("/(<br\/>)/", "<br/>\n", $message); // Add an xtra line after a br
	$message = preg_replace("/(<li>)/", "<li> * ", $message); // Add formatting to li tags
	$message = strip_tags($message);
	//  	$message = strip_tags($message, '<p>'); // Strip tags from message
	//	$message = preg_replace("/<p.*>(.+)<\/p.*>/", "$1\n", $message); // Replace <p> tags with empty lines
  	$message = preg_replace("/(\r\n|\r)/", "\n", $message); // Convert to unix line endings in body
  	//$message = preg_replace("/^From/", ">From", $message); // Change lines starting with From to >From
	
	$message = wordwrap($message.$footer);
	if (is_plugin_enabled('elggpg')) {
		try {
			putenv("GNUPGHOME=".elggpg_get_gpg_home());
	                $gpg = new gnupg();
			$gpg->addencryptkey($to->email);
			$encmessage = $gpg->encrypt($message);
			if ($encmessage)
				$message = $encmessage;
		}
		catch(Exception $e) {
		}
	}
	return mail($to->email, $subject, $message, $headers);
}

/**
 * Returns a more meaningful message
 *
 * @param unknown_type $hook
 * @param unknown_type $entity_type
 * @param unknown_type $returnvalue
 * @param unknown_type $params
 */
function groupmailshot_notify_message($hook, $entity_type, $returnvalue, $params)
{
	global $SUBJECT_TOPIC, $TOPIC_MSG,$CONFIG;

	$entity = $params['entity'];
	$to_entity = $params['to_entity'];
	$method = $params['method'];
	$msg = '';
	if (($entity instanceof ElggEntity) && ($to_entity->guid != $entity->owner_guid) && ($entity->getSubtype() == 'groupforumtopic'))
	{
		$title = $entity->title;
		if(get_input('topic_post')) {
			$msg = get_input('topic_post');
		} else {
			// I hates globals but seems like the quickest way to store our topics latest message.
			$msg = $TOPIC_MSG;
		}
		$SUBJECT_TOPIC = "Re: [{$title}]";
		$name = get_user($entity->owner_guid)->get('username');
		$date = date('d-m-Y');
		$msg_body = "Topic:<b>$title</b>\n\nEl siguiente comentario ha sido creado por $name el $date\n\n$msg\n\n" . $entity->getURL();
		return $msg_body;
	}
	return null;
}

function groupmailshot_toplevel_mailbridge($event, $object_type, $rel) {
    $topic_guid = $rel->guid_one;
    $topic = get_entity($topic_guid);
    $new_post = get_entity($rel->guid_two);
    $group = get_entity($new_post->container_guid);
    $owner = $new_post->getOwnerEntity();
    $posts = elgg_get_entities_from_relationship(array('relationship'=>'group_discussion_top_level_post', 'relationship_guid'=>$topic_guid));
    $prev_post = NULL;
    if ($posts && count($posts) > 1)
        $prev_post = $posts[count($posts)-1];
    $comments = get_annotations($new_post->getGUID(), "", "", "", "", 0, 1);
    $comment = $comments[0];
    mailto_group($owner, $group, $topic, $comment, $new_post, $prev_post);
}

function groupmailshot_reply_mailbridge($event, $object_type, $rel) {
    $prev_post = get_entity($rel->guid_one);
    $new_post = get_entity($rel->guid_two);
    $group = get_entity($new_post->container_guid);
    $owner = $new_post->getOwnerEntity();
    $comments = get_annotations($new_post->getGUID(), "", "", "", "", 0, 1);
    $comment = $comments[0];
    $topics = elgg_get_entities_from_relationship(array('relationship'=>'group_discussion_topic_link', 'relationship_guid'=>$new_post->getGUID(), 'inverse_relationship'=>TRUE));
    $topic = $topics[0];
    mailto_group($owner, $group, $topic, $comment, $new_post, $prev_post);
}

function groupmailshot_forum_mailbridge($event, $object_type, $comment) {
	$object = $comment->getEntity();
	if ($object->getSubtype() === 'groupforumtopic') {
		$group = get_entity($object->container_guid);
		$owner = $comment->getOwnerEntity();
		mailto_group($owner, $group, $object, $comment);
	}
	return true;
}

function mailto_group($owner, $group, $object, $comment, $new_post=NULL, $prev=NULL) {
	$users = elgg_get_entities_from_relationship(array('relationship' => 'notifymailshot',
							    'relationship_guid' => $group->getGUID(),
							    'inverse_relationship' => true,
							    'types' => 'user',
							    'limit' => 9999));
	$members = $group->getMembers(0);
	foreach ($users as $user) {
            // check the user is actually a member of the group.
            if (in_array($user, $members))
		    groupmailshot_notify_handler($owner, $user, $object, $comment, $new_post, $prev);
	    else
		    remove_entity_relationship($user->guid, 'notifymailshot', $group->getGUID());
        }
}


function groupmailshot_dummy($from, $to, $subject, $topic, $params = array()) {
}

/**
* Sets our permissions so that users can post messages via email
*
* @param unknown_type $hook
* @param unknown_type $entity_type
* @param unknown_type $returnvalue
* @param unknown_type $params
*/
function groupmailshot_permissions_check($hook_name,$entity_type,$return_value,$params) {
	if('cron' == get_context()) {
		return true;
	}
	return null;
}

function groupmailshot_page_handler($page) {
	global $CONFIG;
	switch($page[0]) {
		case 'subscription':
			set_page_owner($page[1]);
			include($CONFIG->pluginspath . "elggman/subscription.php");
			return;
		case 'admin':
			set_page_owner($page[1]);
			include($CONFIG->pluginspath . "elggman/admin.php");
			return;
		default:
			if (count($page) == 3) {
				set_page_owner($page[0]);
        	                set_input('group_guid', $page[0]);
                	        set_input('topic', $page[1]);
                        	set_input('post_id', $page[2]);
				include($CONFIG->pluginspath . "threaded_forums/topicposts.php");
				return;
			}
			break;
	}
	forward();
}

function elggman_member_add($event, $object_type, $object) {
	$user_guid = $object->guid_one;
	$group_guid = $object->guid_two;
	$group = get_entity($group_guid);
	
	if ($group->elggman_autosubscribe) {
		if (!check_entity_relationship($user_guid, 'notifymailshot', $group_guid)) {
			add_entity_relationship($user_guid, 'notifymailshot', $group_guid);
			// XXX should send email to explain we're subscribed
		}
	}
}

function elggman_submenus() {
	global $CONFIG;
	if (get_context() == 'threaded_forums') {
		$group = page_owner_entity();
		if ($group) {
			if (check_entity_relationship(get_loggedin_userid(), 'notifymailshot', page_owner()))
				add_submenu_item(elgg_echo('elggman:configure'), $CONFIG->wwwroot . "pg/elggman/subscription/" . $group->getGUID(), 'groupsactions');
			if ($group->canEdit())
				add_submenu_item(elgg_echo('elggman:admin'), $CONFIG->wwwroot . "pg/elggman/admin/" . $group->getGUID(), 'groupsactions');
		}
	}
}

/**
* Sets up our plugin
*/
function groupmailshot_init() {
	global $CONFIG;
	register_plugin_hook('permissions_check','all','groupmailshot_permissions_check');
	register_plugin_hook('notify:entity:message', 'object', 'groupmailshot_notify_message');
	//register_plugin_hook('cron','minute','groupmailshot_cron');
	//register_elgg_event_handler('create','annotation','groupmailshot_forum_mailbridge');
	register_elgg_event_handler('create','group_discussion_top_level_post','groupmailshot_toplevel_mailbridge');
	register_elgg_event_handler('create','group_discussion_reply_post','groupmailshot_reply_mailbridge');
	register_page_handler('elggman','groupmailshot_page_handler');
	extend_view('forum/topics','listserv/forumtopics',0);

	register_elgg_event_handler('create', 'member', 'elggman_member_add');

	// Register actions (suscribe-forum)
	register_action("listserv/suscribe-forum",false,$CONFIG->pluginspath . "elggman/actions/subscribe-forum.php");
	register_action("elggman/subscribe",false,$CONFIG->pluginspath . "elggman/actions/subscribe-forum.php");
	register_action("elggman/changesubscription",false,$CONFIG->pluginspath . "elggman/actions/changesubscription.php");
	register_action("elggman/unsubscribe",false,$CONFIG->pluginspath . "elggman/actions/unsubscribe-forum.php");
	register_action("elggman/admin",false,$CONFIG->pluginspath . "elggman/actions/admin.php");
	register_notification_handler('mailshot', 'groupmailshot_dummy');

	register_elgg_event_handler('pagesetup','system','elggman_submenus');
}
// Initialise our plugin
register_elgg_event_handler('init','system','groupmailshot_init');
// Notification hooks