-# Abort if called from a web server
-if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
- print "This script must be run from the command line\n";
- exit();
-}
-
-define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
-define('LACONICA', true);
-
-require_once(INSTALLDIR . '/lib/common.php');
-require_once(INSTALLDIR . '/lib/mail.php');
-require_once('Mail/mimeDecode.php');
-
-# FIXME: we use both Mail_mimeDecode and mailparse
-# Need to move everything to mailparse
-
-class MailerDaemon {
-
- function __construct() {
- }
-
- function handle_message($fname='php://stdin') {
- list($from, $to, $msg) = $this->parse_message($fname);
- if (!$from || !$to || !$msg) {
- $this->error(NULL, _t('Could not parse message.'));
- }
- common_log(LOG_INFO, "Mail from $from to $to: " .substr($msg, 0, 20));
- $user = $this->user_from($from);
- if (!$user) {
- $this->error($from, _('Not a registered user.'));
- return false;
- }
- if (!$this->user_match_to($user, $to)) {
- $this->error($from, _('Sorry, that is not your incoming email address.'));
- return false;
- }
- if (!$user->emailpost) {
- $this->error($from, _('Sorry, no incoming email allowed.'));
- return false;
- }
- $response = $this->handle_command($user, $msg);
- if ($response) {
- $this->respond($from, $to, $response);
- return true;
- }
- $msg = $this->cleanup_msg($msg);
- $this->add_notice($user, $msg);
- }
-
- function error($from, $msg) {
- file_put_contents("php://stderr", $msg . "\n");
- exit(1);
- }
-
- function user_from($from_hdr) {
- $froms = mailparse_rfc822_parse_addresses($from_hdr);
- if (!$froms) {
- return NULL;
- }
- $from = $froms[0];
- $addr = common_canonical_email($from['address']);
- $user = User::staticGet('email', $addr);
- if (!$user) {
- $user = User::staticGet('smsemail', $addr);
- }
- return $user;
- }
-
- function user_match_to($user, $to_hdr) {
- $incoming = $user->incomingemail;
- $tos = mailparse_rfc822_parse_addresses($to_hdr);
- foreach ($tos as $to) {
- if (strcasecmp($incoming, $to['address']) == 0) {
- return true;
- }
- }
- return false;
- }
-
- function handle_command($user, $msg) {
- $cmd = trim(strtolower($msg));
- switch ($cmd) {
- case 'off':
- $this->set_notify($user, false);
- return true;
- case 'on':
- $this->set_notify($user, true);
- return true;
- default:
- return false;
- }
- }
-
- function set_notify($user, $value) {
- $orig = clone($user);
- $user->smsnotify = $value;
- $result = $user->update($orig);
- if (!$result) {
- common_log_db_error($user, 'UPDATE', __FILE__);
- return false;
- }
- return true;
- }
-
- function respond($from, $to, $response) {
-
- $headers['From'] = $to;
- $headers['To'] = $from;
- $headers['Subject'] = "Command complete";