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

3rd party code for phpList

Postby chrishanvey » 5:39am, Fri 24 Oct, 2008

Are these classes anywhere to download, or do they only exist in these posts?

Just wondering if i can download an updated version or i have to scrape them off and apply updates by reading through all the posts.

Anybody know?

thanks
chrishanvey
PL Nut
 
Posts: 17
Joined: 2:25am, Thu 01 Dec, 2005

Correction to 'remove list' functionality

Postby chrishanvey » 11:58am, Fri 07 Nov, 2008

I found an error that was preventing the lists from being removed properly. The error is in the last line of code i have posted, but i have included the first few lines of the enclosing method to make it easier to locate:
Code: Select all
    private function saveLists() {
       
        $removeIds = array_unique( $this->removeLists );
        foreach( $removeIds as $removeId ) {
            $q = 'DELETE FROM ' . self::$table_prefix . "listuser WHERE userid=$this->userId AND listid=" . Query::makeDBIntegerSafe( $removeId );

            if( Query::executeQuery( $q ) ) {
                if( isset( $this->attributes[$removeId] ) ) unset( $this->attributes[$removeId] );


Should be:
Code: Select all
    private function saveLists() {
       
        $removeIds = array_unique( $this->removeLists );
        foreach( $removeIds as $removeId ) {
            $q = 'DELETE FROM ' . self::$table_prefix . "listuser WHERE userid=$this->userId AND listid=" . Query::makeDBIntegerSafe( $removeId );

            if( Query::executeQuery( $q ) ) {
               if( isset( $this->lists[$removeId] ) ) unset( $this->lists[$removeId] );
[/code]
chrishanvey
PL Nut
 
Posts: 17
Joined: 2:25am, Thu 01 Dec, 2005

Postby Guest » 5:37pm, Tue 23 Dec, 2008

After fiddling around I have made a few amendments so thought I would post what Ive done. Hopefully someone will find it useful:

Code: Select all
class phpList {

   var $db;
   var $tablePrefix;
   var $userTablePrefix;
   
   
   function phpList() {
      require("listconfig.php");
      $this->tablePrefix = $table_prefix;
      $this->userTablePrefix = $usertable_prefix;
      mysql_select_db($database_name) or die('Could not select database');
   }
   
   
   function setAttributes($userIdOrEmail,$attributes,$overwrite=false) {
      if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
      else $userId = $this->email2id($userIdOrEmail);
      if (empty($userId)) return(false);
            
      // if attributes were specified, try and map them to attribute ids in the db
      $attributeIds = array();
      if (is_array($attributes)) {
         foreach ($attributes as $name=>$value) {
            $sql = "SELECT id FROM ".$this->userTablePrefix."attribute WHERE name='".addslashes($name)."'";
            $result = mysql_query($sql);
            if ($result) {
               $attributeIds[$name] = mysql_result($result, 0);
            }
         }
      }
      // insert attributes (if any) for the user
      foreach ($attributeIds as $name=>$id) {
         $value = $attributes[$name];
         if ($overwrite) $sql = "REPLACE INTO ";
         else $sql = "INSERT IGNORE INTO ";
         $sql .= $this->userTablePrefix."user_attribute (attributeid,userid,value) values ('".addslashes($id)."','".addslashes($userId)."','".addslashes($value)."')";
         $result = mysql_query($sql);
      }
      return(true);
   }
   
   
   function email2id($email) {
      $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE email='".addslashes($email)."'";
      $result = mysql_query($sql);
      $userId = mysql_result($result, 0);
      if (empty($userId)) return(false);
      return($userId);
   }
   
   
   function id2email($userId) {
      $sql = "SELECT email FROM ".$this->userTablePrefix."user WHERE id='".addslashes($userId)."'";
      $result = mysql_query($sql);
      $email = mysql_result($result, 0);
      if (empty($email)) return(false);
      return($email);
   }
   
   
   function createUser($email,$password,$attributes=false) {
      // is there already a user in the system using this email addy?
        $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE email='".addslashes($email)."'";
      $result = mysql_query($sql);
        if ($result) {
         $userId = mysql_result($result, 0);
      }
        
      // if the user doesn't exist, create them
        if (empty($userId)) {
         // create a unique id for the user (and make sure it's unique in the database)
         do {
            $uniqueId = md5(uniqid(mt_rand(0,1000).$email));
            $sql = "SELECT COUNT(*) FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
            $result = mysql_query($sql);
            if ($result) {
               $exists = mysql_result($result, 0);
            }
         } while ($exists);
         
         // insert the user
         $sql = "INSERT INTO ".$this->userTablePrefix."user (email,entered,confirmed,uniqid,htmlemail,password) values ('".addslashes($email)."',now(),1,'".addslashes($uniqueId)."',1,'".addslashes($password)."')";
         $result = mysql_query($sql);
         
         // add a note saying we imported them manually
         $sql = "INSERT INTO ".$this->userTablePrefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Import via phpList Class')";
         $result = mysql_query($sql);
         
         // get the new user id
         $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
         $result = mysql_query($sql);
         if ($result) {
            $userId = mysql_result($result, 0);
         }
         
         // set attributes if any
         if ($attributes) $this->setAttributes($userId,$attributes);
         
         return($userId);
      }
   }
   
   
   // subscribe a user to a list - accepts either a user id or an email addy
   // user must exist
   function subscribe($userIdOrEmail,$listId) {
      if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
      else $userId = $this->email2id($userIdOrEmail);
      if (empty($userId)) return(false);
      
      // subscribe them to the specified list
      $sql = "INSERT IGNORE INTO ".$this->tablePrefix."listuser (userid,listid,entered) VALUES ('".addslashes($userId)."','".addslashes($listId)."',now())";
      $result = mysql_query($sql);
      
      // add a note saying we subscribed them manually
      $sql = "INSERT INTO ".$this->userTablePrefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Subscribed to list ".addslashes($listId)." via phpList Class')";
      $result = mysql_query($sql);
      
      return(true);
   }
   
   
   // unsubscribe an email addy from the list
   // if no list id provided, unsubscribe the user from all lists
   function unsubscribe($userIdOrEmail,$listId=NULL) {
      if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
      else $userId = $this->email2id($userIdOrEmail);
      if (empty($userId)) return(false);
      
      // unsubscribe them   
      $sql = "DELETE FROM ".$this->tablePrefix."listuser WHERE userid='".addslashes($userId)."'";
      if ($listId) $sql .= " AND listid='".addslashes($listId)."'";
      $result = mysql_query($sql);
      
      // add a note saying we unsubscribed them manually
      $sql = "INSERT INTO ".$this->userTablePrefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Unsubscribed from list ".addslashes($listId)." via phpList Class')";
      $result = mysql_query($sql);
      
      return(true);
   }
   
   
   // takes an e-mail address to determine if currently subscribed to any other lists, other than this one...
   // returns true if subscribed to more than one list and false if not
   function getSubscriberStatus($userIdOrEmail, $listId) {
      if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
      else $userId = $this->email2id($userIdOrEmail);
      if (empty($userId)) return(false);
      
      $sql = "SELECT userid FROM ".$this->tablePrefix."listuser WHERE listid != '".addslashes($listId)."' AND userid = '".addslashes($userId)."'";   
      $result = mysql_query($sql);
      $num_rows = mysql_num_rows($result);
      
      if ($num_rows>0) return(true);
      else return(false);
   }
 
   
   // Deletes a user if they are only subscribed to one list, else simply unsubscribes them from this list...
   function deleteUser($userIdOrEmail, $listId) {
      if($otherListCheck = $this->getSubscriberStatus($userIdOrEmail, $listId)) {
         //unsubscribe
         $this->unsubscribe($userIdOrEmail,$listId);
      } else {
         if(is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
         else $userId = $this->email2id($userIdOrEmail);
         if (empty($userId)) return(false);
         
         $sql = "DELETE FROM ".$this->tablePrefix."listuser WHERE userid='".addslashes($userId)."'";
         $result = mysql_query($sql);
         $sql = "DELETE FROM ".$this->tablePrefix."user_attribute WHERE userid='".addslashes($userId)."'";
         $result = mysql_query($sql);
         $sql = "DELETE FROM ".$this->tablePrefix."usermessage WHERE userid='".addslashes($userId)."'";
         $result = mysql_query($sql);
         $sql = "DELETE FROM ".$this->tablePrefix."user_message_bounce WHERE user='".addslashes($userId)."'";
         $result = mysql_query($sql);
         $sql = "DELETE FROM ".$this->tablePrefix."user_user WHERE id='".addslashes($userId)."'";
         $result = mysql_query($sql);
         $sql = "DELETE FROM ".$this->tablePrefix."user_user_history WHERE userid='".addslashes($userId)."'";
         $result = mysql_query($sql);
         $sql = "DELETE FROM ".$this->tablePrefix."user_rss WHERE userid='".addslashes($userId)."'";
         $result = mysql_query($sql);
      }
   }
   
   
   // updates a users email address
   function upemail($newEmail, $oldEmail, $listId, $userStatus) {
      //check if new email exists already
      $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE email='".addslashes($newEmail)."'";
      $result = mysql_query($sql);
        if ($result) {
         $userId = mysql_result($result, 0);
      }
        
      // if the email doesn't exist then go ahead and update old email to new email...it wont conflict with anyone else...
        if (empty($userId)) {
         $userId = $this->email2id($oldEmail);
         if (empty($userId)) return(false);
         $sql = "UPDATE ".$this->userTablePrefix."user SET email='".addslashes($newEmail)."' WHERE id='".addslashes($userId)."'";
         $result = mysql_query($sql);
         if($result) {
            return(true);
         } else {
            return(false);
         }
      } else { // if there is another user with the new email addy, then merge as it is more than likely the same person from another site...
         //unsubscribe from this list user old email address...
         $this->unsubscribe($oldEmail,$listId);
         $this->setAttributes($oldEmail, array($listId . 'Status'=>'0'), true);
         // todo - if user not subscripbed to any other list then maybe delete them completely???
         //now re-subscribe back to same list using new email...This will update an existing account as we have already acertained that the new email exists above...
         $this->subscribe($newEmail,$listId);
         $this->setAttributes($newEmail, array($listId . 'Status'=>$userStatus), true);
         return(true);
      }
   }
   
   
   
   // updates a users password ... md5 password sent through func...
   function uppass($newPass, $email) {
      $userId = $this->email2id($email);
      $sql = "UPDATE ".$this->userTablePrefix."user SET password='".addslashes($newPass)."' WHERE id='".addslashes($userId)."'";
      $result = mysql_query($sql);
   }
}
Guest
 

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

Postby dzyubam » 5:00pm, Wed 10 Jun, 2009

Hi all,

I'm new to PHPlist and am not really a programmer. Is there a fairly easy way to customize the code posted in this thread? I have a phpbb3 forum and would like to add a user to a single list in PHPlist automatically upon registering with phpbb3. Even though it seems easy enough, I don't know where to start. Any help will be greatly appreciated. :)

Thanks,
Max
dzyubam
phpList newbie
 
Posts: 1
Joined: 4:51pm, Wed 10 Jun, 2009

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

Postby GeeketteGurl » 10:00pm, Wed 10 Jun, 2009

Not to sound too dumb...

I have created the files from sbeener's rendition of this that doesn't use Pear.

I have created PhpListUser, ErrorHandler, SimpleEmail and Query and uploaded them to my admin folder in phplist (hope that's the right place for these and that I did them correctly). Now, my question is - how do I access PhpListUser? When I just go to http://www.mydomain/lists/admin/PhpListUser.php - I get a 403 forbidden message
When I go to http://www.mydomain/lists/admin/?page=PhpListUser - I just get a blank page with the PHPList header. What am I doing incorrectly?
GeeketteGurl
PL Nut
 
Posts: 39
Joined: 5:41pm, Wed 20 May, 2009

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

Postby kwcjr » 5:17pm, Sun 05 Jul, 2009

Here is another minor (but important) change like the one above to make deleting from lists work. This one makes adding to lists work (for me anyway). Code by sbeener » 4:44pm, Fri 17 Aug, 2007 was generating MySQL errors.

If you only have one list then this error would not have appeared. I have several lists that are being managed through this code so the error became apparent as multiple records (e.g., multiple sets of values) for a REPLACE INTO require comma separation between the value sets.

Code as it was:
Code: Select all
    private function saveLists() {
       
        $removeIds = array_unique( $this->removeLists );
        foreach( $removeIds as $removeId ) {
            $q = 'DELETE FROM ' . self::$table_prefix . "listuser WHERE userid=$this->userId AND listid=" . Query::makeDBIntegerSafe( $removeId );
            if( Query::executeQuery( $q ) ) {
                if( isset( $this->attributes[$removeId] ) ) unset( $this->attributes[$removeId] );
            }
            else {
                // just a warning.
                ErrorHandler::registerWarning( "Failed to remove user from list id: $removeId" );
            }
        }
       
        // these are all either verified (by set_lists) or from the db
        $q = 'REPLACE INTO ' . self::$table_prefix . 'listuser ( userid, listid, entered ) VALUES';
        foreach( $this->lists as $id => $listInfo ) {
            $entered = $listInfo['entered'] ? "'{$listInfo['entered']}'" : 'NOW()';
            $q .= " ( $this->userId , $id, $entered )";
        }
        if( Query::executeQuery( $q ) ) {
            return true;
        }
       
        ErrorHandler::registerError( 'Error saving lists.' );
        return false;
       
    }



Code as I changed it to eliminate MySql errors (this also includes the change from the attributes table to the list table documented earlier):
Code: Select all
    private function saveLists() {
       
        $removeIds = array_unique( $this->removeLists );
        foreach( $removeIds as $removeId ) {
            $q = 'DELETE FROM ' . self::$table_prefix . "listuser WHERE userid=$this->userId AND listid=" . Query::makeDBIntegerSafe( $removeId );
            if( Query::executeQuery( $q ) ) {
                if( isset( $this->lists[$removeId] ) ) unset( $this->lists[$removeId] );
            }
            else {
                // just a warning.
                ErrorHandler::registerWarning( "Failed to remove user from list id: $removeId" );
            }
        }
       
        // these are all either verified (by set_lists) or from the db
        $q = 'REPLACE INTO ' . self::$table_prefix . 'listuser ( userid, listid, entered ) VALUES';
        foreach( $this->lists as $id => $listInfo ) {
            $entered = $listInfo['entered'] ? "'{$listInfo['entered']}'" : 'NOW()';
            $q .= " ( $this->userId , $id, $entered ), ";
        }
        $q = substr($q,0,strlen($q)-2);
        if( Query::executeQuery( $q ) ) {
            return true;
        }
       
        ErrorHandler::registerError( 'Error saving lists.' );
        return false;
       
    }
kwcjr
phpLister
 
Posts: 7
Joined: 7:31pm, Thu 14 May, 2009

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

Postby kwcjr » 7:45pm, Sun 05 Jul, 2009

Fix to the function get_attribute( $name ). For me, it was always returning an empty string. Here is the working version:

Code: Select all
    public function get_attribute( $name ) {
        foreach( $this->attributes as $attr ) {
            if( $attr['name'] == $name ) {
   return $attr['value'];
   }
        }
       
        ErrorHandler::registerWarning( "Unable to retrieve attribute '$name' from class attributes" );
        return false;
       
    }
kwcjr
phpLister
 
Posts: 7
Joined: 7:31pm, Thu 14 May, 2009

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

Postby kwcjr » 3:20am, Mon 06 Jul, 2009

Fix for createUniqueId(). When inserting new subscribers, this routine just plain aborted php on my server. Took a while, but finally noticed that
Code: Select all
 $hash = md5( uniqid( mt_rand( 0, 1000 ) ) . $email );

should be
Code: Select all
 $hash = md5( uniqid( mt_rand( 0, 1000 ) ) . $this->email );


Here is the udpated routine:
Code: Select all
    private function createUniqueId() {
        // create a unique id for the user (and make sure it's unique in the database)
        $safe = 0;
        do {
            $hash = md5( uniqid( mt_rand( 0, 1000 ) ) . $this->email );
            $sql = 'SELECT id FROM ' . self::$usertable_prefix . "user WHERE uniqid='$hash'";
            $result = Query::queryToArray( $sql );
            if( $safe++ > 10 ) {
               ErrorHandler::registerError( "Couldn't get unique id in $safe tries, aborting." );
               return false;
            }
        }
        while( count( $result ) > 0 );
       
        $this->uniqid = $hash;
        return true;
       
    }
kwcjr
phpLister
 
Posts: 7
Joined: 7:31pm, Thu 14 May, 2009

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

Postby kwcjr » 3:26am, Mon 06 Jul, 2009

Correction for adding a new subscriber but not adding them to any lists:
Code: Select all
    private function saveLists() {
       
        $removeIds = array_unique( $this->removeLists );
        foreach( $removeIds as $removeId ) {
            $q = 'DELETE FROM ' . self::$table_prefix . "listuser WHERE userid=$this->userId AND listid=" . Query::makeDBIntegerSafe( $removeId );
            if( Query::executeQuery( $q ) ) {
                if( isset( $this->lists[$removeId] ) ) unset( $this->lists[$removeId] );
            }
            else {
                // just a warning.
                ErrorHandler::registerWarning( "Failed to remove user from list id: $removeId" );
            }
        }
       
        // these are all either verified (by set_lists) or from the db
        $q = 'REPLACE INTO ' . self::$table_prefix . 'listuser ( userid, listid, entered ) VALUES';
      $i =0;
        foreach( $this->lists as $id => $listInfo ) {
            $entered = $listInfo['entered'] ? "'{$listInfo['entered']}'" : 'NOW()';
            $q .= " ( $this->userId , $id, $entered ), ";
         $i++;
        }
      if ($i > 0) {
         $q = substr($q,0,strlen($q)-2);
           if( Query::executeQuery( $q ) ) {
               return true;
           }
          
           ErrorHandler::registerError( 'Error saving lists.' );
           return false;
       }
      return true;
    }
kwcjr
phpLister
 
Posts: 7
Joined: 7:31pm, Thu 14 May, 2009

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

Postby placebo » 1:53pm, Wed 22 Jul, 2009

to remove from a list [updated, quoted codedidnt work]

Code: Select all
<?php

//make your connections to the db where php list is stored***************


function phplistUnsubscribe($listId,$email) {


  // first of all, i must search for the user:
  $sql = "SELECT id FROM phplist_user_user WHERE email='".addslashes($email)."'";

      $result = mysql_query($sql);
      $userId = mysql_result($result, 0);

 


  // then i'll unsuscribe her from the list:
  $sql = "DELETE FROM phplist_listuser WHERE listid = ".$listId." AND userid = ".$userId;
 $result = mysql_query($sql);

//printing to see if it works
 echo $userId."<br>";
echo $listId;


  // add a note saying we unsuscribed them manually
  $sql = "INSERT INTO ".$usertable_prefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Unsuscribed via phplistUnubscribe()')";
 $result = mysql_query($sql);

  // return the query's result
  return($result);
 
   
}   



phplistUnsubscribe(4,'EMAIL@EMAIL.COM');


?>
placebo
phpLister
 
Posts: 14
Joined: 3:41pm, Wed 02 Jul, 2008

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

Postby jmar » 11:41pm, Thu 15 Apr, 2010

First of all, Thank you Ravis, this saved a project today.
I had to rewrite the script so it could work with Zend Framework, so I thought I'd share the script.

I turned it into a model which you call as any other model
Code: Select all
<?php
/*

    phplistSubscribe

   Based on original script by:
    Written by Ravis (http://www.ravis.org/)
    March 29th, 2006
   
   Re-written by:
   Javier Martinez (http://www.famunion.com)
   April 15,2010
   
    SUMMARY:
    This function provides a simple way to interact with phpList in your own programs (eg: adding a user
    who just purchased something from your website to a mailing list).

    Takes a list id, an email address, and optionally some attributes and subscribes the user to that list.
    If the user already exists, the existing account will be subscribed. If it's a new user they'll be added
    first. Users added in this way are pre-confirmed (they will not be sent a confirmation email).

    DISCLAIMER:
    All the standard rules apply. No responsibility for loss of data, corruption of data, alien abductions,
    watching bad movies, unruly children, etc etc. Note that I'm pretty busy and I really don't have time
    to support this code, so please don't contact me asking for help implementing it. I release it simply
    because I thought it might be useful. I know absolutely nothing about phpList, really, I just installed
    it today. The queries here are mostly ripped from the phpList import debug info, the rest of the code is
    mine (although I wouldn't be surprised if it matches closely the phpList import code).

    REQUIREMENTS:
    This function makes use of the PEAR DB abstraction layer, which makes dealing with databases a lot
    nicer. If you like there's nothing to stop you from modifying the $db-> commands to standard PHP
    mysql functions, but since I use the PEAR DB layer for pretty much everything, I used it here too.
    In fact, you could even use the DB layer included with phpList, I didn't because I wanted to keep
    the code as independent as possible.

    USAGE:
    $userId = phplistSubscribe(list,email[,attributes]);

    PARAMETERS:
    list       - The ID of the list you want to subscribe the user to. No verification is done on this
                 field, it's up to you to make sure you pass it a valid ID.
    email      - The email address of the user you want to subscribe. This is also how the function tells
                 if a user exists or not. If the email doesn't exist in the system it'll be added as a new
                 user.
    attributes - Optional. An array of NAME=>VALUE pairs. NAME should be a pre-defined attribute in
                 phpList. If it doesn't exist, the attribute will be skipped (this function will NOT create
                 attributes for you). VALUE is a text field with the value of the attribute. There's a
                 special case built in for when NAME==country, the function will do a lookup to determine
                 the country ID so that country fields will be normalized. If you specify a country that
                 doesn't already exist in phpList, the attribute will be skipped (this function will NOT
                 create countries for you). NOTE THAT IF YOU ARE WORKING WITH AN EXISTING USER (a matching
                 email address) THEN ANY CONFLICTING ATTRIBUTES WILL BE OVERWRITTEN WITH WHAT YOU SPECIFY
                 IN THIS ARRAY!!

    RETURN VALUE:
    The resulting user id. This will either be the previously existing user matched using the email address
    or the new user created with that email address. You can use this value for further processing if you
    wish.

    EXAMPLE:
    <listId>"Test Account","country"=>"Canada");
    $userId = phplistSubscribe($listId,$email,$attributes);
    print "Added user $userId\n";

    ?>   

    */
   
class Phplist extends Zend_Db_Table_Abstract{
   
   protected $_db ;
   protected $_table_prefix = "phplist_";
   protected $_usertable_prefix = "phplist_user_";
   
   public function Phplist(){
      $this->_db = Zend_Db::factory(Zend_Registry::get('configPhplist')->db);
   }
   
   
   public function phplistSubscribe($listId,$email,$attributes=NULL){
       // if attributes were specified, try and map them to attribute ids in the db
       $attributeIds = array();
       $attributeIds = $this->mapAttributes($attributes);
       $userId = $this->createUser($email);
      
       $this->insertAttributes($attributeIds, $attributes, $userId);
       $this->addNote($attributeIds, $attributes, $userId);
       $this->subscribeToList($userId, $listId);
      
   }#END function
   
   public function mapAttributes($attributes){
      // if attributes were specified, try and map them to attribute ids in the db
      $attributeIds = array();
      if (is_array($attributes)) {
         foreach ($attributes as $name=>$value) {
            $sql = "SELECT id FROM ".$this->_usertable_prefix."attribute WHERE name='".addslashes($name)."'";
            
            $rs = $this->_db->fetchAll($sql);      
            $id =$rs[0]["id"];                        
            
            if ($id) $attributeIds[$name] = $id;
         }
         //print_r($attributeIds);exit;
         return $attributeIds;
      }   
   }#END function
   
   public function doesUserExist($email){
      // is there already a user in the system using this email addy?
      $sql = "SELECT id FROM ".$this->_usertable_prefix."user WHERE email='".addslashes($email)."'";
      $rs = $this->_db->fetchAll($sql);   
      return ($rs[0]["id"] > 0)?$rs[0]["id"]:false;
   }#END function
   
   public function createUser($email){
      // is there already a user in the system using this email addy?
      $userId = $this->doesUserExist($email);
      //echo $userId;exit;
      if($userId != false){
         //user exists
         return $userId;
      }else{               
         // if the user doesn't exist, create them      
         // create a unique id for the user (and make sure it's unique in the database)
         $exists = true;
         do {
            $uniqueId = md5(uniqid(mt_rand(0,1000).$email));
            $sql = "SELECT COUNT(*) as returnCount FROM ".$this->_usertable_prefix."user WHERE uniqid='".addslashes($uniqueId)."'";
            $rs = $this->_db->fetchAll($sql);            
            $exists = ($rs[0]["returnCount"]==0)?false:true;
         } while ($exists == true);
                  
         $data = array(
                    "email"      =>   addslashes($email),
                    "entered"      =>   'now()',
                    "confirmed"   =>   1,
                    "uniqid"      =>   addslashes($uniqueId)
                    );
         $this->_db->insert($this->_usertable_prefix.'user', $data);   
         $userId = $this->_db->lastInsertId();
         return $userId;   
      }
   }#END function
   
   public function insertAttributes($attributeIds, $attributes, $userId){
       // insert attributes (if any) for the user
      foreach ($attributeIds as $name=>$id) {
         $value = $attributes[$name];
         //Delete current attribute for the user
         $this->_db->delete($this->_usertable_prefix.'user_attribute', 'attributeid = '.addslashes($id)." AND userid = " . addslashes($userId));
         
         //Add new attribute record for the user
         $data = array(
                    "attributeid"      =>   addslashes($id),
                    "userid"         =>   addslashes($userId),
                    "value"         =>   addslashes($value)
                    );
         $this->_db->insert($this->_usertable_prefix.'user_attribute', $data);                  
      }
   }#END function
   
   public function addNote($userId){
      // add a note saying we imported them manually
      $data = array(
                 "userid"      =>   addslashes($userId),
                 "date"      =>   'now()',
                 "summary"      =>   'Entered from jarrowprobiotics.com probiotics profile'
                 );
      $this->_db->insert($this->_usertable_prefix.'user_history', $data);            
   }#END function
   
   public function subscribeToList($userId, $listId){
      //Delete current attribute for the user
      $this->_db->delete($this->_table_prefix.'listuser', 'userid = '.addslashes($userId)." AND listid = " . addslashes($listId));
      
      //Add new attribute record for the user
      $data = array(
                 "userid"      =>   addslashes($userId),
                 "listid"      =>   addslashes($listId),
                 "entered"      =>   'now()'
                 );
      $this->_db->insert($this->_table_prefix.'listuser', $data);            
   }#END function
   
}
?>
jmar
phpList newbie
 
Posts: 1
Joined: 11:37pm, Thu 15 Apr, 2010

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

Postby Treytor » 9:25am, Tue 04 May, 2010

Sorry I'm a PHP newbie, but is there any way I can execute this script from a different domain on another server?

I've gotten it successfully working as "add.php" in my lists directory on my server, but I'd like to be able to add e-mails to my mailing list when people register on my forum, which is hosted on another server.

I've got the code in the right place, and I tried doing a "require_once" in PHP to include the add.php file and execute the function, but I'm realizing this won't work.

Any ideas?

Thanks in advance!
Treytor
phpList newbie
 
Posts: 1
Joined: 9:23am, Tue 04 May, 2010

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

Postby tari » 1:15pm, Wed 29 Dec, 2010

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?
astigmatismкосоглазие
Radeon 6990
Last edited by tari on 2:06pm, Mon 17 Oct, 2011, edited 1 time in total.
tari
phpList newbie
 
Posts: 1
Joined: 1:14pm, Wed 29 Dec, 2010

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

Postby timcinel » 12:26am, Wed 05 Jan, 2011

Just wanted to say thanks - it still seems to work with the latest version!
timcinel
phpList newbie
 
Posts: 1
Joined: 12:22am, Wed 05 Jan, 2011

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

Postby amed » 1:38pm, Mon 31 Jan, 2011

Thanks ravis for the excellent script. For those trying to get it to work with PEAR - DB but are having problem. try the following link

http://pear.php.net/manual/en/installation.checking.php


Furthermore for those using plesk. You will also need to modify the virtual host directory to add the PEAR path. For more info on this , use the following link

http://kb.parallels.com/en/432

cheers
amed
phpList newbie
 
Posts: 3
Joined: 1:31pm, Mon 31 Jan, 2011

PreviousNext

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

Who is online

Users browsing this forum: No registered users and 2 guests

cron