[contrib] PHP function to add users / subscribe to lists

3rd party code for phpList

ErrorHandler.php

Postby sbeener » 4:58pm, Fri 17 Aug, 2007

Code: Select all
<?

class ErrorHandler {
   
   private static $errorArray = array();
   private static $warningArray = array();
   
   public static function registerError( $errorTransHandle ) {
      self::$errorArray[] = $errorTransHandle;
   }
   
   public static function clearErrors() {
      self::$errorArray = array();
   }
   
   public static function getErrors() {
      return self::$errorArray;
   }
   
   public static function hasErrors() {
      return count( self::$errorArray ) > 0;
   }
   
   public static function registerWarning( $warn ) {
       self::$warningArray[] = $warn;
   }
   
   public static function clearWarnings() {
       self::$warningArray = array();
   }
   
   public static function getWarnings() {
       return self::$warningArray;
   }
   
   public static function hasWarnings() {
       return count( self::$warningArray ) > 0;
   }
   
   public static function hasMessages() {
       return self::hasWarnings() || self::hasErrors();
   }
   
   public static function getMessages() {
       return array_merge( self::$warningArray, self::$errorArray );
   }
   
}

?>
sbeener
phpLister
 
Posts: 6
Joined: 11:21pm, Thu 16 Aug, 2007
Location: Vancouver, Canada

SimpleEmail.php

Postby sbeener » 5:06pm, Fri 17 Aug, 2007

Code: Select all
<?

class SimpleEmail {
   
    private $recipient;
    private $subject;
    private $message;
    private $headers;
   
    private $error;
   
    public static function isValidEmail( $email ) {
       
       return preg_match('/^[ a-z0-9-_]+(\.[a-z0-9-_]+)*@[a-z0-9-]+(\.[a-z0-9-_]+)*(\.[a-z]{2,4})$/i', $email);
       
    }
   
    function __construct() {
        $this->recipient = '';
        $this->subject = '';
        $this->message = '';
        $this->headers = '';
        $this->error = array();
    }
   
    private function doError( $msg ) {
        $this->error[] = $msg;
    }
   
    public function hasErrors() {
        return count( $this->error );
    }
   
    public function getErrors() {
        return $this->error;
    }
   
    public function addHeader( $header ) {
        $header = trim( trim( $header ), ';' );
        $this->headers .= "$header\r\n";
    }
   
    public function sendMail() {
       
        if( !($this->recipient && $this->subject && $this->message) ) {
            ErrorHandler::registerError( 'Missing fields required to send email' );
        }
       
        if( !ErrorHandler::hasErrors() ) {
            //*DEBUG*/ $success = true; echo "To: $this->recipient\nSubject:$this->subject\n\n$this->message\n";
            $success = mail( $this->recipient, $this->subject, $this->message, $this->headers );
            if( $success ) return true;
            else ErrorHandler::registerError( 'Error sending mail.' );
        }
       
        return false;
       
    }
   
    public function set_recipient( $val ) {
        if( $this->isValidEmail( $val ) ) {
        //if( self::isValidEmail( $val ) ) {
            $this->recipient = $val;
            return true;
        } else {
            ErrorHandler::registerError( 'Invalid email address for recipient' );
            return false;
        }
    }
   
    public function set_subject( $val ) {
        $this->subject = str_replace( array( '"', "\n", "\r" ), array( '\\\"', ''), $val );
    }
   
    public function set_message( $val ) {
        $this->message = str_replace( '"', '\\\"', $val );
    }
   
}

?>
sbeener
phpLister
 
Posts: 6
Joined: 11:21pm, Thu 16 Aug, 2007
Location: Vancouver, Canada

This is a great class

Postby griffonboy » 8:55pm, Sun 02 Sep, 2007

don't get me wrong, but my boss would prefer it if phplist offered an API to do this sort of thing without touching its tables directly. Fooling around with a module's tables introduces coupling and is against our coding practices. I have used this class as a temporary patch and it works fine.
griffonboy
phpLister
 
Posts: 6
Joined: 11:34pm, Wed 19 Apr, 2006
Location: oregon

Postby crazydaddy » 6:17am, Wed 19 Sep, 2007

Excellent post. Code worked fine with PEAR DB but my hosting service only provides MDB2. Fortunately this works with some minor changes to the initialisation. This is include below plus a couple of other functions that I needed to delete a user and to update a user's email address. Just the changed code shown below, rest is as per original.

// Include your phpList config.php file here

require("config/config.php");
class phpList {

var $db;
var $tablePrefix;
var $userTablePrefix;

function phpList($pathToPhpList=NULL) {
// if no path specified, assume this file is in thephplist dir
if (empty($pathToPhpList)) $pathToPhpList = dirname(__FILE__);

// Include your phpList config.php file here
require("$pathToPhpList/config/config.php");
$this->tablePrefix = $table_prefix;
$this->userTablePrefix = $usertable_prefix;
// Setup and connect to the database (this only needs to be done once per session
// Full path to php
$path = "/path to php/php/";
require_once($path."MDB2.php");
$this->db = MDB2::connect("mysql://$database_user:$database_password@$database_host/$database_name");
echo "connected to database" . '<li>';
if (MDB2::isError($this->db)) die($this->db->getMessage());
$this->db->setFetchMode(MDB2_FETCHMODE_ASSOC);
}


function deleteUser($userId)
// Deletes a user
{
$sql = "DELETE FROM ".$this->tablePrefix."listuser WHERE userid='".addslashes($userId)."'";
$this->db->query($sql);
$sql = "DELETE FROM ".$this->tablePrefix."user_attribute WHERE userid='".addslashes($userId)."'";
$this->db->query($sql);
$sql = "DELETE FROM ".$this->tablePrefix."usermessage WHERE userid='".addslashes($userId)."'";
$this->db->query($sql);
$sql = "DELETE FROM ".$this->tablePrefix."user_message_bounce WHERE user='".addslashes($userId)."'";
$this->db->query($sql);
$sql = "DELETE FROM ".$this->tablePrefix."user_user WHERE id='".addslashes($userId)."'";
$this->db->query($sql);
$sql = "DELETE FROM ".$this->tablePrefix."user_user_history WHERE userid='".addslashes($userId)."'";
$this->db->query($sql);
$sql = "DELETE FROM ".$this->tablePrefix."user_rss WHERE userid='".addslashes($userId)."'";
$this->db->query($sql);
}

function upemail($userId, $email)
// updates a users email address
{
$sql = "UPDATE ".$this->userTablePrefix."user SET email='".addslashes($email)."' WHERE id='".addslashes($userId)."'";
$this->db->query($sql);
}
crazydaddy
phpList newbie
 
Posts: 4
Joined: 12:28am, Tue 11 Sep, 2007

Postby santos.john » 5:12pm, Mon 24 Dec, 2007

Colinh wrote:Hi
Please ignore my last question, I realised after looking closer that I had misunderstood how it was working, it should work fine, at the moment the REPLACE INTO is not working for me but that is my problem.

Colin


The same question from me. It should work, but why it always doesn't work? Thx
santos.john
phpList newbie
 
Posts: 3
Joined: 5:09pm, Mon 24 Dec, 2007

Postby gorkau » 10:20am, Fri 25 Jan, 2008

I've found a little bug in saveLists function. It works ok when the user is subscribed to just one list, but there are problems if he is subscribed to more than one. It now looks like this:

Code: Select all
        $q = 'REPLACE INTO ' . self::$table_prefix . 'listuser ( userid, listid, entered ) VALUES';
        foreach( $this->lists as $id => $listInfo ) {
            $entered = $listInfo['entered'] ? "'{$listInfo['entered']}'" : 'NOW()';
            $q_array .= " ( $this->userId , $id, $entered )";
        }
        if( Query::executeQuery( $q ) ) {
            return true;
        }


But it should be like this:


Code: Select all
        foreach( $this->lists as $id => $listInfo ) {
            $entered = $listInfo['entered'] ? "'{$listInfo['entered']}'" : 'NOW()';
            $q_array[] = " ( $this->userId , $id, $entered )";
        }
        $q .= implode(", ", $q_array);
        if( Query::executeQuery( $q ) ) {
            return true;
        }


That solved the problem for me.
gorkau
phpList newbie
 
Posts: 1
Joined: 10:13am, Fri 25 Jan, 2008

front end for this

Postby ah » 12:14pm, Tue 05 Feb, 2008

hi, has anyone implemented a front end with a form for this, i have been trying to get it to work without any luck. anyone got any examples. also do all the classes need to be in seperate files or can they be in one include? will it work on php four?
ah
phpList newbie
 
Posts: 3
Joined: 11:47am, Tue 29 Jan, 2008

Postby sayad » 8:06pm, Wed 20 Feb, 2008

santos.john wrote:
Colinh wrote:Hi
Please ignore my last question, I realised after looking closer that I had misunderstood how it was working, it should work fine, at the moment the REPLACE INTO is not working for me but that is my problem.

Colin


The same question from me. It should work, but why it always doesn't work? Thx



and i have the same question...
sayad
phpList newbie
 
Posts: 2
Joined: 7:55pm, Wed 20 Feb, 2008

Postby bzcoder » 6:22pm, Wed 14 May, 2008

sayad wrote:and i have the same question...


Make sure the table listuser has a unique index on the fields userid and listid(combined, not individually).

Hmmm. listusers has 4 fields, not 3 as is listed above. Just by the seat of my pants, I would suggest

Code: Select all
  // subscribe them to the specified list
  $sql = "REPLACE INTO ".$table_prefix."listuser (userid,listid,entered) VALUES ('".addslashes($userId)."','".addslashes($listId)."',now())";
  $result = $db->query($sql);


Should actually be:
Code: Select all
  // subscribe them to the specified list
  $sql = "REPLACE INTO ".$table_prefix."listuser (userid,listid,entered,modified) VALUES ('".addslashes($userId)."','".addslashes($listId)."',now(),now())";
  $result = $db->query($sql);


This is just for the listuser table, let me know if your having problems with other tables.
[/code]
bzcoder
PL Geek
 
Posts: 53
Joined: 8:15pm, Mon 14 Apr, 2008

Postby raphaelb » 2:54pm, Wed 21 May, 2008

Code: Select all
    private function attributeValue( &$attr ) {
        if( $attr['name'] == 'country' ) {
            $return[ $attr['name'] ] = $attr['countryName'];
        }
        else {
            $return[ $attr['name'] ] = $attr['value'];
        }
    }


should be:

Code: Select all
    private function attributeValue( &$attr ) {
        if( $attr['name'] == 'country' ) {
          return $attr['countryName'];
        }
        else {
         return $attr['value'];
        }
    }
raphaelb
phpLister
 
Posts: 9
Joined: 9:43am, Tue 13 May, 2008

Postby raphaelb » 3:33pm, Wed 21 May, 2008

there is a new function:

Code: Select all
   public function isRegistedEmail( $val= 0 ) {
        if($val==0)
         $val=$this->email;
        if( SimpleEmail::isValidEmail( $val ) ) {
              $q = 'SELECT id FROM ' . self::$usertable_prefix . "user WHERE email='$val'";
            $result = Query::queryToArray( $q );
            return count( $result );
        }
        else {
            ErrorHandler::registerError( 'Invalid Email supplied to PhpListUser' );
         return -1;
        }
       
    }
raphaelb
phpLister
 
Posts: 9
Joined: 9:43am, Tue 13 May, 2008

Postby Guest » 6:08pm, Tue 26 Aug, 2008

deke wrote:Has anyone been able to implement Ravis' class so that it can send out a confirmation email as well? I am using the code example provided by flex99 but can't seem to get it working:


I am also still looking for a way to send the confirmation email. Where are the functions getUserConfig() and getConfig() defined?

Thankyou.
Guest
 

trying to email confirmation link

Postby Guest » 9:07pm, Tue 26 Aug, 2008

I tracked down getUserConfig() and decided to try:

Code: Select all
require($pathToPhpList . "/admin/defaultconfig.inc");


When I call getUserConfig(), some kind of error is thrown and I get a blank response, even with php.ini error reporting On and E_ALL.<br>

The log mentions "File does not exist: /var/www/html/admin/admin"
Guest
 

phpList uid encoding for confirm link

Postby Guest » 12:27am, Wed 27 Aug, 2008

I have resorted to sending my own confirmation email and I wonder what is the format of the confirmation link? I tried to md5() the userId but that doesn't work...

Thanks!
Guest
 

figured out custom confirm email

Postby Guest » 5:40pm, Wed 27 Aug, 2008

Some more digging revealed that it's the user's uniqueId. All is working now.
Guest
 

PreviousNext

Return to Contributions: Plug-ins, Add-ons, Mods

Who is online

Users browsing this forum: No registered users and 5 guests