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

3rd party code for phpList

createList function

Postby apreece » 6:53pm, Thu 07 Dec, 2006

Hello!
I've created a CreateList function. hopefully this will help someone out. Included is a diff against the last full text posted of the api. complete with doc addition :)
Code: Select all
--- phplist_api.php     2006-12-07 10:50:00.000000000 -0800
+++ api.php     2006-12-07 10:49:05.000000000 -0800
@@ -1,3 +1,4 @@
 /*

 phplist Class
@@ -78,6 +79,17 @@
   Returns:
     The user ID for the newly created user, or false on failure.

+CreateList(name,description,listorder,owner,rssfeed,active)
+  Parameters:
+    name - The name of the list
+    description - Descr
+    listorder - integer indicating the ordinal of the list
+    owner - name or email address of a valid user.
+    rssfeed - send the string or value NULL to not create an rss feed.
+    active - integer (1 or 0) to indicate if this is an active list.
+  Returns:
+    The list ID for the newly created list, or 0 on failure.
+  NOTE: the prefix attribute is currently unsupported
 subscribe(user,list)
   Parameters:
     user - the phpList user ID or email address of the user you want to modify attributes for
@@ -215,8 +227,30 @@
     return($email);
   }

-
-
+  function CreateList($name,$description,$listorder,$owner,$rssfeed,$active){
+
+    #make sure user is ID format
+    if (is_string($owner)) $owner =
+      $this->email2id($owner);
+
+    #set up rss properly. needs to be null if blank
+    if(empty($rssfeed) || $rssfeed == "NULL")
+      $rssfeed = "NULL";
+    else
+      $rssfeed = "'".addslashes($rssfeed)."'";
+
+    $sql = sprintf('insert into %s (name,description,entered,listorder,owner,prefix,rssfeed,active)values("%s","%s",now(),%d,%d,NULL,%s,%d)',
+      $this->tablePrefix."list",
+      addslashes($name),
+      addslashes($description),
+      $listorder,
+      $owner,
+      $rssfeed,
+      $active);
+    $this->db->query($sql);
+    return($this->db->getOne("select LAST_INSERT_ID()"));
+  }
+
   function createUser($email,$attributes=false) {
     // create a unique id for the user (and make sure it's unique in the database)
     do {
@@ -286,5 +320,5 @@
   }


apreece
phpList newbie
 
Posts: 1
Joined: 6:51pm, Thu 07 Dec, 2006

Postby ClarkKent » 8:43pm, Sun 28 Jan, 2007

I am using Ravis class to add and remove users, adding users works fine but removing them it doesnt seem to remove them, am i doing something wrong? Here is how i am using it

Code: Select all
   $query = "SELECT * from km_users where playername='$ID'";
   $query1 = mysql_query($query) or die("Could not get email");
   $query2 = mysql_fetch_array($query1);
   $email = $query2[email];
   include ($_SERVER['DOCUMENT_ROOT'] . "/includes/mailfunctions.php");
   $list = new phpList("../mail/lists");
   $list->unsubscribe($email);
   unset ($list);
}

It will go through all of this with no apparent errors but it doesn't remove them from the database. Any ideas?
ClarkKent
phpList newbie
 
Posts: 3
Joined: 8:00am, Sat 27 Jan, 2007

Caveat: $userId referenced before defined in CreateUser

Postby peterf » 7:21pm, Sun 04 Feb, 2007

It appears to me that in lines 233... of the Class:
Code: Select all
// 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 = $this->db->query($sql);

// get the new user id
$sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
$userId = $this->db->getOne($sql);


the statements are inverted, so that we're trying to use $userID before it is defined.

After correcting this, the class appears to work perfectly.
Sorry if I didn't notice someone else's corrections already!!

--------

Other observations:

I'm also running into issues setting values for a checkbox which, in the import data is represented as 0 or 1, but in phpList attributes has to be 'off' or 'on'

I do something like this in the import code, before creating the new user:

Code: Select all
$myAttr["I\'m a reader"]=$myData["Areyouareader"]==1?'on':'';

($myData is an array from explode("\t",$theLine))
Note also that to split or explode on a tab double-quotes are required!!!
'\t' would search for a slash and a 't', which of course, is unlikely to be found in your data...

Here's my final import code, specific, of course to my application, but with various useful points.
The names of the lists have been changed to not offend the client!
The import data is a tab-separated list of attributes, with a list of flags (0,1) to denote which lists to subscribe each user, and one for a "are you vegetarian" (a checkbox)

--------
Code: Select all
<?php

//  PSF _ phpListImports by peter fraterdeus (PSF) (fraterdeus c o m)
//  PSF _ 04 Feb 2007 (everybody else in the US is watching the Bears in the StuporBowl)
//  PSF _ takes a tab-separated datafile with a [0,1] flag per mailing list, explodes the values into attributes and lists, adds users and subscribes to their lists.
//        this is specific for moving from a different list management system, and the data came in this fashion YMMV of course.
//
//  PSF _ Expanded from the 'while' loop in "phplistadd"
//        by mouser at donationcoder c o m (donationcoder com), simple front end to
//        phpList class, written by Ravis (ravis o r g)
//        which does main work.

//  PSF _ note also see my changes to phpInterface.php

// mouser _ ...
// this is infinitely faster than built in phplist import.
// NOTE:
// your php may not have the pear db functions installed
// login as root and do: pear lib
// then: pear install db
// if its not installed already
//
// NOTE:
// i strongly recomment you add this after the include of config.php in phpSubscribe.php
// unless you like spending hours screaming because php is silently dying or hanging:
// (it's no good to put it here since it will be clear on include of config.php there.
// $error_level = error_reporting(63);


// filename containing newline separated email addresses with additional attributes and ML flags
$emailfile="./data/Export_2007_02_01_w_Veg_test.txt";

// lists must already exist in phpList. the numeric values in the array are the list IDs in phpList_list
$myLists=array("list1"=>2,
"list2"=>3,
"list3"=>4,
"list4"=>5,
"list5"=>6,
"list6"=>7,
"list7"=>8,
"list8"=>9,);

// your path will vary
$pathToPhpList='{$DOCUMENT_ROOT}/lists/';


// html display
echo '<html><body>';
echo 'phplistImports running <br><br>';
echo "phplistImports data file = $emailfile<br><br>";


// include main func
require($pathToPhpList."phpInterface.php");
echo 'phplistImports after include <br><br>';

//init
$email="";
$attributes=NULL;
$rownum=0;
$error_level = error_reporting(63);
// create new phplist object

$myPhpList=new phpList($pathToPhpList);


// open file and loop, processing each line in turn
if (! $fh = fopen($emailfile, 'r') ) die ("Can't open");
echo "phplistImports after $fh <br><br>";

if ($fh)
    {
    while (!feof($fh))
        {
        ++$rownum;
        $theLine = fgets($fh);
        // PSF_comment out the echos to minimize screen clutter in a long import, but they are useful while debugging...
        echo "<br><br>*******<br>phplistImports $theLine ### $rownum<br><br>\n";
       
       
        /*
        Data import format
        Source   Prefix   First Name   Middle Name   Last Name   Suffix   Password   
        Home Phone   Address Line1   Address Line2   City   State   Zip/Postal Code   
        Email   Email HTML   ML_1   ML_2   ML_3   ML_4   
        ML_5   ML_6   ML_7   ML_8   ML_9   
        ML_10   ML_11   Flag_3_Are you a vegetarian?
       
        */
       
        $myData=Array();
       
        list($myData['Source'],
        $myData['Prefix'],
        $myData['FirstName'],
        $myData['MiddleName'],
        $myData['LastName'],
        $myData['Suffix'],
        $myData['Password'],
       
        $myData['HomePhone'],
        $myData['AddressLine1'],
        $myData['AddressLine2'],
        $myData['City'],
        $myData['State'],
        $myData['ZipPostalCode'],
       
        $myData['Email'],
        $myData['EmailHTML'],
        $myData['ML_1'],
        $myData['ML_2'],
        $myData['ML_3'],
        $myData['ML_4'],
       
        $myData['ML_5'],
        $myData['ML_6'],
        $myData['ML_7'],
        $myData['ML_8'],
        $myData['ML_9'],
       
        $myData['ML_10'],
        $myData['ML_11'],
        $myData['Areyouavegetarian']
        )=explode("\t",$theLine); // get all the pieces NOTE, use "\t" not '\t'!!
       
        // covert imported data from "True/False" to 1 or 0 for htmlemail...
        $myData['EmailHTML'] = $myData['EmailHTML']=='True'?1:0;
       
       
        $myAttr["Address 1"]=$myData["AddressLine1"];
        $myAttr["Address 2"]=$myData["AddressLine2"];
        $myAttr["Child\'s Name"]="";
        $myAttr["City"]=$myData["City"];
        $myAttr["First Name"]=$myData["FirstName"];
        $myAttr["Home Phone"]=$myData["HomePhone"];
        $myAttr["Last Name"]=$myData["LastName"];
        $myAttr["Middle Name"]=$myData["MiddleName"];
        $myAttr["Prefix"]=$myData["Prefix"];
        $myAttr["State"]=$myData["State"];
        $myAttr["Suffix"]=$myData["Suffix"];
        $myAttr["ZipPostal Code"]=$myData["ZipPostalCode"];
        $myAttr["Source"]=$myData["Source"];
       
        // PSF _ phplist checkbox values are 'on' or 'off' - convert imported data from 0 or 1
        $myAttr["I\'m a Vegetarian"]=$myData["Areyouavegetarian"]==1?'on':'';
       
       
        $subbedLists= Array();
       
        //  PSF _ imported data has a flag for each list to be subscribed to
        //  PSF _ for each flag, push the list id onto an array if the flag is '1'
        if ($myData['ML_1'] ==1) array_push($subbedLists,$myLists['list1']);
       
        if ($myData['ML_8'] ==1) array_push($subbedLists,$myLists['list8']);
       
        if ($myData['ML_7'] ==1) array_push($subbedLists,$myLists['list7']);
       
        if ($myData['ML_2'] ==1) array_push($subbedLists,$myLists['list2']);
       
        if ($myData['ML_5'] ==1) array_push($subbedLists,$myLists['list5']);
       
        if ($myData['ML_6'] ==1) array_push($subbedLists,$myLists['list6']);
       
        if ($myData['ML_3'] ==1) array_push($subbedLists,$myLists['list3']);
       
        if ($myData['ML_4'] ==1) array_push($subbedLists,$myLists['list4']);
       
        echo "**** subbedLists ".print_r ($subbedLists). '<br>' . "\n";
       
       
        $userID=$myPhpList->createUser($myData['Email'],$myAttr,$myData['Password'],$myData['EmailHTML']);
        // note, changes to phpInterface->createUser were required to implement... emailhtml is hard coded in Ravis' original.
       
        echo $rownum . ' - ' . $userID . ' - ' . $myData['Email'] . '<br>' . "\n";
       
        foreach ($subbedLists as $theList) {
       
            $myPhpList->subscribe($userID,$theList);
       
            echo $rownum . ' - ' . $userID . ' - ' . $theList . '<br>' . "\n";
       
        }
       
        // display it
        // echo $rownum . ' - ' . $userID . ' - ' . $theList . '<br>' . "\n";
        }
    }
else
{
    echo 'Failed to open file "' . $emailfile . '".<br>';
}


// done
echo 'Processed Lines: ' . $rownum . '<br>';
echo '</body></html>';
?>


finally, the revised createUser code from phpImplements.php (Ravis' phpList Class), with password, and htmlemail included...
Code: Select all
function createUser($email,$attributes=false,$password,$htmlemail) {
// 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)."'";
$exists = $this->db->getOne($sql);
} while ($exists);

// insert the user
$sql = "INSERT INTO ".$this->userTablePrefix."user (email,password,entered,confirmed,uniqid,htmlemail) values ('".addslashes($email)."','".addslashes($password)."',now(),1,'".addslashes($uniqueId)."','".addslashes($htmlemail)."')";
$result = $this->db->query($sql);

// get the new user id
$sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
$userId = $this->db->getOne($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 = $this->db->query($sql);

// get the new user id
$sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
$userId = $this->db->getOne($sql);

// set attributes if any
if ($attributes) $this->setAttributes($userId,$attributes);

return($userId);
}


Hope this will be helpful for someone else!
Cheers
Peter
peterf
phpLister
 
Posts: 10
Joined: 6:45pm, Mon 22 Jan, 2007

Postby deke » 1:18pm, Tue 20 Mar, 2007

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:

Code: Select all
function createUser($email,$attributes=false, $htmlemail) {
      // 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)."'";
         $exists = $this->db->getOne($sql);
      } while ($exists);
      
      // insert the user  - EDIT:  Changed 1 to 0 for confirm.
      $sql = "INSERT INTO ".$this->userTablePrefix."user (email,entered,confirmed,uniqid,htmlemail) values ('".addslashes($email)."',now(),0,'".addslashes($uniqueId)."','".addslashes($htmlemail)."')";
      $result = $this->db->query($sql);
      
      // get the new user id
      $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
      $userId = $this->db->getOne($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 = $this->db->query($sql);
      
      // get the new user id
      $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
      $userId = $this->db->getOne($sql);
      
      // set attributes if any
      if ($attributes) $this->setAttributes($userId,$attributes);
      
      # EDIT: (send confirmation email - Flex99's code)
      $spage = '1';
      $subscribemessage = ereg_replace('\[LISTS\]', 'Your Lists Name', getUserConfig("subscribemessage:$id",$userId));
      sendMail($email, getConfig("subscribesubject:$spage"), $subscribemessage,system_messageheaders(),$envelope);
      
      return($userId);
   }


When I run this function... the page just turns blank... the user is added, but no confirmation is sent. Any idea how I can get it working? Thanks.
deke
phpList newbie
 
Posts: 3
Joined: 6:43pm, Mon 19 Mar, 2007

Just Tables & Fields please

Postby serenity » 11:28am, Sun 13 May, 2007

Hi Everyone,

I must say that this thread is truley infomative. One question; I will be using a programing language called 4D to query and manupulate PHP TAbles. Can any one in detail give me the exact Tables/Fields(Columns) that PHP uses to store data such as email, name, last name etc. And in what order please.

I know that the ListID also comes into play. Why isn't there just one table that stores all user info.

I noticed the for example in the table phplist_user_user there is many unused fields, why is this?

Can some one tell me preferably in 123. What fields to populate and what table/field to query if I want to import all user data into my own database. Also there is the question; When I add attributes such as gender or country I don't see that added to any of the tables and phplist_user_user in particular, which I think hold many of the user info, Right.
serenity
phpLister
 
Posts: 5
Joined: 11:02pm, Sat 12 May, 2007

Postby 9inetoe » 12:49am, Sat 19 May, 2007

Serenity,

I'm new to phplist myself this week, so I cannot give you the kind of detailed info you are looking for, but I can help you with some of your generalized questions:

I know that the ListID also comes into play. Why isn't there just one table that stores all user info.


This has to do with database 'normalization.' If all your information is stored in one table, it can lead to a system that is inefficient and inflexible.

If you google "normalize database" you will find a ton of helpful examples which will explain a lot of why phplist is setup the way it is.


What fields to populate and what table/field to query if I want to import all user data into my own database. Also there is the question;


This question is pretty open-ended - it depends on how much detail you want in your records. However, in general, to import the user's data, you would need to include serveral tables. At a minimum, I think you would be looking at something like:

- phplist_user_user (user's basic data, like email address, etc.)

- phplist_listuser (which list[s] the user belongs to)

- phplist_list (in case you want to display the actual name of the list[s] the user belongs to, or find out how many lists you have)

phplist_user_attribute (holds info about any attributes that have been added)

phplist_user_user_attribute (the actual values for any of your possible attributes)

phplist_listattr_memberlist (defines certain types of attributes, such as checkboxgroup - there may be other tables that store info about other subtypes of attributes that I am unaware of, but I know about this one for sure)

...etc., etc.

I could go on. You can see this gets pretty complex.



When I add attributes such as gender or country I don't see that added to any of the tables and phplist_user_user in particular, which I think hold many of the user info, Right.


Actually, no. Actual values for the attributes are in (help out here if I am off base anybody):

phplist_user_user_attribute - this table holds the id of the attribute, the user id, and the values for the attributes you have assigned.

Again, all of these structures are in accordance with normalization for Relational Databases. Phplist is not built like a spreadsheet, where everything is on one table...that's the 'relational' part of "Relational Database" -- different parts of the system are captured in their own tables and 'related' to each other through various foreign keys and such.

Hope this helps a little - I realize it may not be exactly what you were expecting. :wink:
9inetoe
phpList newbie
 
Posts: 2
Joined: 12:15am, Sat 19 May, 2007

Postby serenity » 9:35pm, Sun 20 May, 2007

Thanks for the reply. I think I need to no exactly if I can store user info like name, country, gender along with the email address. It seems that only email addresses can be stored.
serenity
phpLister
 
Posts: 5
Joined: 11:02pm, Sat 12 May, 2007

Other user info

Postby 9inetoe » 6:03pm, Mon 21 May, 2007

Yes, you can do this...I allude to this in my previous post.

...Actual values for the attributes are in (help out here if I am off base anybody):

phplist_user_user_attribute - this table holds the id of the attribute, the user id, and the values for the attributes you have assigned.


PhpList calls these 'extra' items that you are describing "attributes," and you have to add them to your installed phplist application in the admin area.

Attributes can be things like, first name, last name, country, etc.

Once you add some attributes they will be stored in this table. However, bear in mind that some of the values stored here may look a little funny, because they are dependent on the way you set this up in the admin. For example, checkbox groups are just comma separated lists of id numbers in the 'value' field of the attributes, and those id numbers correspond to the key for each of your checkboxes held in yet another table.

In other words, yes, phplist can do, what you are asking -- but the place to look for the stored information may not be as staightforward as you are hoping for.

Check out the documentation and I'm sure you can find information on attributes.
9inetoe
phpList newbie
 
Posts: 2
Joined: 12:15am, Sat 19 May, 2007

Postby sunhaq » 11:10pm, Fri 25 May, 2007

I just tried out the class and found something that looks like a small error to me. The following function uses $userId which is not defined.

Code: Select all
    // 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 = $this->db->query($sql);


Afaik PEAR DB got no insertid function so i just putted

Code: Select all
$userId = $this->email2id($email);


right in front of it.

This is not needed in the original version, just in the revised version from the "12:53pm, Sat 15 Apr, 2006" posting by Ravis.
sunhaq
phpList newbie
 
Posts: 2
Joined: 11:52am, Wed 21 Feb, 2007

First version rewritten for mysql

Postby josh_H » 3:20pm, Thu 09 Aug, 2007

Hi all. Just posting a quick modification of the first iteration of Ravin's code. No promises on anything, it simply replaces the PEAR DB code for the php mysql database access code. Should save someone a few minutes.

Code: Select all
<?


/*

phplistSubscribe

Written by Ravis (http://www.ravis.org/)
March 29th, 2006

Modified by Josh Harle (http://www.neonascent.net) to replace PEAR DB with mysql database access
10th August, 2007

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";

?>

TODO:
Turn this function into a PHP class for interacting with phpList programmatically (for someone not me) ;-)

*/


// Include your phpList config.php file here
require("config/config.php");




// Setup and connect to the database (this only needs to be done once per session
// You don't need to change anything here.

//$db = DB::connect("mysql://$database_user:$database_password@$database_host/$database_name");
//if (DB::isError($db)) die($db->getMessage());
//$db->setFetchMode(DB_FETCHMODE_ASSOC);
$link = mysql_connect($database_host, $database_user, $database_password)
    or die('Could not connect: ' . mysql_error());
mysql_select_db($database_name) or die('Could not select database');


// the actual function
function phplistSubscribe($listId,$email,$attributes=NULL) {
  global $db,$table_prefix,$usertable_prefix;
  // 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 ".$usertable_prefix."attribute WHERE name='".addslashes($name)."'";
      //$id = $db->getOne($sql);
      //if ($id) $attributeIds[$name] = $id;
      $result = mysql_query($sql);
     if ($result) {
            $attributeIds[$name] = mysql_result($result, 0);
     } 
     
    }
  }
 
  // is there already a user in the system using this email addy?
  $sql = "SELECT id FROM ".$usertable_prefix."user WHERE email='".addslashes($email)."'";
  //$userId = $db->getOne($sql);
  $result = mysql_query($sql);
  if ($result) {
      $userId = mysql_result($result, 0);
  } 
 
  // if the user doesn't exist, create them
  if (empty($userId)) {
    echo "attempting to create new user";
    // 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 ".$usertable_prefix."user WHERE uniqid='".addslashes($uniqueId)."'";
      //$exists = $db->getOne($sql);
      $result = mysql_query($sql);
     if ($result) {
            $exists = mysql_result($result, 0);
     }
    } while ($exists);
    // insert the user
    $sql = "INSERT INTO ".$usertable_prefix."user (email,entered,confirmed,uniqid) values ('".addslashes($email)."',now(),1,'".addslashes($uniqueId)."')";
    //$result = $db->query($sql);
    $result = mysql_query($sql);
    // get the new user id
    $sql = "SELECT id FROM ".$usertable_prefix."user WHERE uniqid='".addslashes($uniqueId)."'";
    //$userId = $db->getOne($sql);
   $result = mysql_query($sql);
     if ($result) {
            $userId = mysql_result($result, 0);
     }
  }
 
  // insert attributes (if any) for the user
  foreach ($attributeIds as $name=>$id) {
    $value = $attributes[$name];
    // special case for countries - get the country id instead of using the name
    if (strtolower($name)=="country") {
      $sql = "SELECT id FROM ".$table_prefix."listattr_countries WHERE name='".addslashes($value)."'";
      //$value = $db->getOne($sql);
      $result = mysql_query($sql);
     if ($result) {
            $value = mysql_result($result, 0);
     }
      // if the country name wasn't found, skip
      if (empty($value)) continue;
    }
    $sql = "REPLACE INTO ".$usertable_prefix."user_attribute (attributeid,userid,value) values ('".addslashes($id)."','".addslashes($userId)."','".addslashes($value)."')";
    //$result = $db->query($sql);
    $result = mysql_query($sql);
  }
 
  // add a note saying we imported them manually
  $sql = "INSERT INTO ".$usertable_prefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Import via phplistSubscribe()')";
  //$result = $db->query($sql);
  $result = mysql_query($sql);
 
  // 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);
  $result = mysql_query($sql);
   
  // return the user id
  return($userId);
}


?>
josh_H
phpList newbie
 
Posts: 1
Joined: 3:15pm, Thu 09 Aug, 2007

Postby sbeener » 11:36pm, Thu 16 Aug, 2007

This code was very useful for me while trying to integrate PHPList with a project of mine so I thought I'd post the adjustments I made.

The project is PHP5 so I put the functionality into a class. Because it's part of a larger framework it uses a few other classes which I've included in the archive.

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

the attachment

Postby sbeener » 11:37pm, Thu 16 Aug, 2007

Didn't appear to attach...
sbeener
phpLister
 
Posts: 6
Joined: 11:21pm, Thu 16 Aug, 2007
Location: Vancouver, Canada

Postby H2B2 » 2:55am, Fri 17 Aug, 2007

Yes, unfortunately file attachments do no seem to work on this forum.

I guess the only alternative is to post your code here. Just to avoid any problems with html
code being cut off, make sure you click on "Disable HTML in this post" on the left of your
editing window.

I think this would certainly be a very useful contribution to this thread.
Thanks!
H2B2
Moderator
 
Posts: 7188
Joined: 1:51am, Wed 15 Mar, 2006

PhpListUser.php

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

edited to correct many many grievous errors
Code: Select all
<?


/*

PhpListUser (derived from phplistSubscribe function)

Written by Ravis (http://www.ravis.org/)
March 29th, 2006

Modified by Josh Harle (http://www.neonascent.net) to replace PEAR DB with mysql database access
10th August, 2007

Modified by Rob Linton (http://www.yarwoodinteractive.com)
15th August, 2007
Refactored as a PHP5 class that uses my SimpleEmail, Query and ErrorHandler classes.
Much of the summary still applies although now you can add and remove lists - but not attributes, I
don't need if for this project so it's a to do item if needed down the road.  Attribute may only be
added and edited.  You no longer need PEAR DB but you'll need the class files I referenced above:
  require_once( 'SimpleEmail.php' );
  require_once( 'Query.php' );
  require_once( 'ErrorHandler.php' );

Enjoy.
 

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.

rl - The PEAR DB abstraction layer has been replaced with my Query class.

USAGE:

    PhpListUser::$PHPListPath = 'mypathto/phplist';
   
    $user = new PhpListUser( 'email@address.com' );
   
    $user->addListId( 2 );  // this won't add them until you save
    $user->save();          // now they're added
   
    $warns = ErrorHandler::getWarnings();
    $errs = ErrorHandler::getErrors();

Happy coding!

//-----------------------------------------------------------------------*/

class PhpListUser {
   
    // static
    public static $PHPListPath = '';
   
    private static $table_prefix = '';
    private static $usertable_prefix = '';
    private static $config_loaded = false;
   
    // instance
    private $userId;
    private $email;
    private $uniqid;
    private $attributes;    // user attributes.  array( id => array( name, value ), ... )
    private $lists;         // currently subscribed lists.  array( id=>array( list_name, entered date ), ... )
   
    private $removeLists;   // array of list ids to remove user from on a save
   
    private static function loadConfig() {
       
        require( self::$PHPListPath. '/config/config.php' );
       
        // We need $table_prefix and $usertable_prefix
        self::$table_prefix = $table_prefix;
        self::$usertable_prefix = $usertable_prefix;
       
        // If db constants are not defined, get them from the config for the Query class.
        if( !defined( 'DB_HOST' ) ) define( 'DB_HOST', $database_host );
        if( !defined( 'DB_USER' ) ) define ( 'DB_USER', $database_user );
        if( !defined( 'DB_PASS' ) ) define ( 'DB_PASS', $database_password );
        if( !defined( 'DB_NAME' ) ) define ( 'DB_NAME', $database_name );
       
        self::$config_loaded = true;
       
    }
   
    public function __construct( $email=null ) {
       
        if( !self::$config_loaded ) self::loadConfig();
       
        $this->userId = 0;
        $this->email = '';
        $this->uniqid = '';
        $this->attributes = array();
        $this->lists = array();
       
        $this->removeLists = array();
       
        if( $email ) {
            $this->set_email( $email );
            $this->load();
        }
       
    }
   
    public function clear() {
       
        $this->__construct();
       
    }
   
    public function load() {
       
        if( !$this->email ) {
            ErrorHandler::registerError( "Can't load PhpListUser without email address" );
            return false;
        }
       
        // else...
        // TO DO - actually load...
       
        $q = 'SELECT id,uniqid FROM ' . self::$usertable_prefix . "user WHERE email='$this->email'";
        $record = Query::queryToRecord( $q );
       
        if( $record ) {
           
            $this->userId = $record['id'];
            $this->uniqid = $record['uniqid'];
           
            $success = $this->loadAttributes() && $this->loadLists();
            return $success;
           
        }
       
        ErrorHandler::registerError( "Error loading user with email: $this->email" );
        return false;
       
    }
   
    public function save() {
       
        // Must be error free
        if( ErrorHandler::hasErrors() ) return false;
       
        // If there's no user id we assume it's an insert
        if( !$this->userId ) {
           
            // Make sure email is unique
            if( $this->emailIsUnique() ) {
                return $this->insertNewUser();
            }
            // If not unique... we load the user and update below
            else {
                if( !$this->load() ) {
                    return false;
                }
            }
        }
       
        // Here we've either returned already or have a user loaded up ready to be updated
        if( $this->updateUser() ) {
           
            // if success reload the attributes
            $email = $this->email;
            $this->clear();
            $this->email = $email;
            $this->load();
           
        }
       
    }
   
    // pass this any number of list ids
    public function addListId() {
       
        $ids = func_get_args();
        foreach( $ids as $id ) {
            $safeId = Query::makeDBIntegerSafe( $id );
            if( $safeId && $safeId != 'NULL' ) {
                $q = 'SELECT name,entered FROM ' . self::$table_prefix . "list WHERE id=$safeId";
                if( $record = Query::queryToRecord( $q ) ) {
                    $this->lists[$safeId] = $record;
                    return true;
                }
                else {
                    ErrorHandler::registerError( "Unable to find list with id: $id" );
                }
            }
           
            ErrorHandler::registerError( "Missing or invalid list id specified: $id" );
            return false;
           
        }
       
    }
   
   
    public function removeListId( $id ) {
        $this->removeLists[] = $id;
    }
   
    public function clearRemoveList() {
        $this->removeLists = array();
    }
   
    private function loadAttributes() {
       
        // 'id' is the attribute id
        $q = 'SELECT id,name,value FROM ' . self::$usertable_prefix . 'user_attribute AS ua' .
                ' JOIN ' . self::$usertable_prefix . 'attribute AS a ON( ua.attributeid = a.id )' .
                " WHERE ua.userid=$this->userId";
       
        $result = Query::queryToArray( $q );
        if( $result !== false ) {
            foreach( $result as $row ) {
                $this->attributes[ $row['id'] ] = array( 'name' => $row['name'], 'value' => $row['value'] );
            }
            return true;
        }
       
        ErrorHandler::registerError( 'Error retrieving attributes from database.' );
        return false;
       
    }
   
    private function loadLists() {
       
        $q = 'SELECT listid,name,lu.entered FROM ' . self::$table_prefix . 'listuser AS lu' .
                ' JOIN ' . self::$table_prefix . 'list AS l ON( lu.listid = l.id )' .
                " WHERE lu.userid=$this->userId";
       
        $result = Query::queryToArray( $q );
        if( $result !== false ) {
            foreach( $result as $row ) {
                $this->lists[ $row['listid'] ] = array( 'name' => $row['name'], 'entered' => $row['entered'] );
            }
            return true;
        }
       
        ErrorHandler::registerError( 'Error retrieving lists from database.' );
        return false;
       
    }
   
    private function insertNewUser() {
       
        if( !$this->createUniqueId() ) {
            return false;
        }
       
        $q = 'INSERT INTO ' . self::$usertable_prefix . 'user ( email, entered, confirmed, uniqid )' .
                ' VALUES ( ' .
                    "'$this->email', " .   // $this->email is verified in the setter
                    'NOW(), ' .
                    '1, ' .
                    "'$this->uniqid'" .     // $this->uniqid is generated internally by this class or retrieved from the db
                ' )';
       
        if( Query::executeQuery( $q ) ) {
            $this->userId = Query::getLastInsertId();
           
            // add a note saying we imported them manually
            $q = 'INSERT INTO ' . self::$usertable_prefix . 'user_history ( userid, ip, date, summary )' .
                    ' VALUES( ' .
                        $this->userId . ', ' .
                        "'{$_SERVER['REMOTE_ADDR']}', "
                        'NOW(), ' .
                        "'Added via PhpListUser()'" .
                    ' )';
           
            // this warning won't stop anything from happening
            if( !Query::executeQuery( $q ) ) ErrorHandler::registerWarning( 'Failed to save user add note.' );
           
        }
        else {
            ErrorHandler::registerError( 'Unable to insert new user' );
            return false;
        }
       
        return $this->saveAttributes() && $this->saveLists();
       
    }
   
    private function updateUser() {
       
        // all we update is the email
        $q = 'UPDATE ' . self::$usertable_prefix . 'user' .
                " SET email='$this->email'" .   // $this->email is verified in the setter
                " WHERE id=$this->userId";
       
        if( Query::executeQuery( $q ) ) {
            return $this->saveAttributes() && $this->saveLists();
        }
       
        ErrorHandler::registerError( 'Error updating user.' );
        return false;
       
    }
   
    private function saveAttributes() {
       
        foreach( $this->attributes as $id => $attr ) {
            // REPLACE INTO is like INSERT but it will UPDATE if the primary key(s) already exist.  MySQL specific extension, kinda cool.
            // We can trust all of these values except $attr['value']
            $q = 'REPLACE INTO ' . self::$usertable_prefix . 'user_attribute (attributeid,userid,value)' .
                    ' VALUES ( ' .
                        $id . ', ' .
                        $this->userId . ', ' .
                        Query::makeDBStringSafe( $attr['value'] ) .
                    ' )';
           
            if( !Query::executeQuery( $q ) ) {
                // just a warning
                ErrorHandler::registerWarning( "Failed to save attribute {$attr['name']} = {$attr['value']}." );
            }
           
        }
       
        return true;
       
    }
   
    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;
       
    }
           
           
    private function emailIsUnique() {
       
        // We can trust $this->email because it's verified in the setter
        $q = 'SELECT id FROM ' . self::$usertable_prefix . "user WHERE email='$this->email'";
        $result = Query::queryToArray( $q );
        $isUnique = count( $result ) == 0;
       
        return $isUnique;
       
    }
   
    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 ) ) . $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;
       
    }
   
    private function getAttributeIdFromName( $name ) {
       
        $sql = 'SELECT id FROM ' . self::$usertable_prefix . 'attribute WHERE name=' . Query::makeDBStringSafe($name);
       
        if( $result = Query::queryToArray( $sql ) ) {
           
            // I don't know about PHPList's database design, it might be possible to specify attributes with the same name
            // in which case we should be referencing attributes by their ids not their names.  I inherited this method...
            if( count( $result ) > 1 ) {
                ErrorHandler::registerError( "Ambiguous reference to attribute '$name'.  Multiple entries found in attribute table." );
                return false;
            }
            else {
                return $result[0]['id'];
            }
           
        }
       
        ErrorHandler::registerError( "Unable to find id for attribute '$name'." );
        return false;
       
    }
   
    /* Currently not using this... leaving it just in case.
    private function verifyLists() {
       
        // If any list names are missing, retrieve them from the db.  If the name is present then
        // it's already verified (it came from the db).
        foreach( $this->lists as $id => $listname ) {
            if( !$listname ) {
                $q = 'SELECT name FROM ' . self::$table_prefix . 'list WHERE id=' . Query::makeDBIntegerSafe( $id );
                if( $record = Query::queryToRecord( $q ) ) {
                    $this->lists[$id] = $record['name'];
                }
                else {
                    ErrorHandler::registerError( "Invalid list id specified: $id" );
                }
            }
        }
       
    }
    //*/
   
    private function addAttribute( $name, $value ) {
       
        if( $id = $this->getAttributeIdFromName( $name ) ) {
           
            // Special case for countries - get the country id instead of using the name.  This is from
            // the original code and I'm not sure what the implications are.  It populates the value
            // with the country id instead of the string value.  It might be specific to a particular
            // set up or it might be how PHPList works.  Keep an eye on this if things go wonky.
            if( strtolower( $name ) == 'country' ) {
                $countryName = $value;
                $q = 'SELECT id FROM ' . self::$table_prefix . 'listattr_countries WHERE name=' . Query::makeDBStringSafe( $countryName );
                if( $record = Query::queryToRecord( $q ) ) {
                    $value = $record['id'];
                }
                else {
                    ErrorHandler::registerError( "Failed to find match for special case country attribute: $countryName." );
                    return false;
                }
            }
            // end country exception
           
            $attrArray = array(
                            'name'  => $name,
                            'value' => $value
                         );
           
            // store the countryName for the get handler
            if( isset( $countryName ) ) $attrArray['countryName'] = $countryName;
           
            $this->attributes[$id] = $attrArray;
            return true;
           
        }
       
        ErrorHandler::registerError( 'Unable to find attribute by name: $name.' );
        return false;
       
    }
   
    private function attributeValue( &$attr ) {
        if( $attr['name'] == 'country' ) {
            $return[ $attr['name'] ] = $attr['countryName'];
        }
        else {
            $return[ $attr['name'] ] = $attr['value'];
        }
    }
   
    //
    // getter/setters
    //
   
    public function set_attribute( $name, $value ) {
       
        $this->addAttribute( $name, $value );
       
    }
   
    public function get_attribute( $name ) {
       
        foreach( $this->attributes as $attr ) {
            if( $attr['name'] == $name ) return $this->attributeValue( $attr );
        }
       
        ErrorHandler::registerWarning( "Unable to retrieve attribute '$name' from class attributes" );
        return false;
       
    }
   
    // Pass this an assoc array( $attr_name => $attr_value, ... )
    public function set_attributes( $val ) {
       
        foreach( $val as $n => $v ) {
            $this->addAttribute( $n, $v );
        }
       
    }
   
    public function get_attributes() {
       
        $return = array();
        foreach( $this->attributes as $attr ) {
            $return[ $attr['name'] ] = $this->attributeValue( $attr );
        }
        return $return;
       
    }
   
    public function get_lists() {
       
        return $this->lists;
       
    }
   
    public function set_email( $val ) {
       
        if( SimpleEmail::isValidEmail( $val ) ) {
            $this->email = $val;
        }
        else {
            ErrorHandler::registerError( 'Invalid Email supplied to PhpListUser' );
        }
       
    }
   
    public function get_email() {
        return $this->email;
    }
   
}


?>
Last edited by sbeener on 1:18am, Thu 23 Aug, 2007, edited 2 times in total.
sbeener
phpLister
 
Posts: 6
Joined: 11:21pm, Thu 16 Aug, 2007
Location: Vancouver, Canada

Query.php

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

Code: Select all
<?

class Query {
     
    private $mString;
    private $mResult;
   
    private static $dbconn;  // holds the db connection
    private static $lastResult;
    private static $lastErrorCode;
    private static $lastErrorMsg;
   
    public static $echoQuery = false; // boolean for whether to echo or not
   
   private static $mOpenForBusiness;

   static public function isOpenForBusiness()
   {
      return self::$mOpenForBusiness;
   }

    static public function openDatabase()
    {
       
        // if already connected..
       if( self::IsOpenForBusiness() ) {
          return;
       }
      
       self::$dbconn = mysql_connect( DB_HOST, DB_USER, DB_PASS );
      
       if( self::$dbconn ) {
          
           if( mysql_select_db( DB_NAME ) ) {
              self::$mOpenForBusiness = true;
           }
           else {
               ErrorHandler::registerError( 'Unable to select db.' );
           }
          
       }
       else {
          self::$mOpenForBusiness = false;
       }
      
       return self::$mOpenForBusiness;
      
    }
   
    public function __construct( $query = "" )
    {
        $this->setString( $query );
    }
   
    public static function executeQuery( $queryStr ) {
       if( !self::$mOpenForBusiness && !self::OpenDatabase() ) {
           ErrorHandler::registerError( "Couldn't open database." );
           die( implode( "<br />\n", ErrorHandler::getErrors() ) . "<br />\n" );
       }
       
       if( self::$echoQuery ) echo "$queryStr<br />\n";
       
       self::$lastResult = @mysql_query( $queryStr );
       
       if( !self::$lastResult ) {
          self::$lastErrorMsg = mysql_error();
          self::$lastErrorCode = mysql_errno();
          ErrorHandler::registerError( self::$lastErrorCode . ': ' . self::$lastErrorMsg . " <br />Query: $queryStr" );
       }
       
       return self::$lastResult;
       
    }
   
    public static function freeResult() {
       
        mysql_free_result( self::$lastResult );
       
    }
   
    public static function queryToArray( $queryStr ) {
       if( self::executeQuery( $queryStr ) ) {
          $arr = array();
          while( $row = mysql_fetch_assoc( self::$lastResult ) ) $arr[] = $row;
          self::freeResult();
          return $arr;
       }
       return false;
    }
   
    // for queries where you are only concerned about the first record returned
    public static function queryToRecord( $queryStr ) {
       if( self::executeQuery( $queryStr ) ) {
          $record = mysql_fetch_assoc( self::$lastResult );
          self::freeResult();
          return $record;
       }
       return false;
    }
   
    public static function getLastInsertId() {
      if( $id = mysql_insert_id() ) {
         return $id;
      }
       // else...
      return false;
   }
   //*/
   
   /* pgsql
   public static function GetNextSequenceVal( $seqName ) {
      
      $sql = "SELECT nextval(" . self::makeDBStringSafe( $seqName ) . ") as key";
      if( $result = self::queryToRecord( $sql ) ) {
         return $result['key'];
      }
      return false;
   }
   //*/
      
   public static function totalRows() {
      return mysql_num_rows( self::$lastResult );
   }
   
   public static function getLastErrorCode() {
      return self::$lastErrorCode;
   }
   
   public static function getLastErrorMsg() {
      return self::$lastErrorMsg;
   }
   
    public static function makeDBStringSafe( $str, $omitQuotes=false ) {
       
       $str = mysql_real_escape_string( $str );
       //$str = str_replace( array('\\',"'"), array('\\\\',"\\'"), $str );
       
       if( $str == '' ) return 'NULL';
       if( $omitQuotes ) return $str;
        return "'$str'";
       
    }
   
    // this isn't really complete, be careful.
    public static function makeDBBinarySafe( $str ) {
       
        return mysql_real_escape_string( $str );
       
    }
   
    // Poorly named function.  Left in for compatibility's sake
    public static function makeDBNumberSafe( $str ) {
       
        return self::makeDBIntegerSafe( $str );
       
    }
   
    public static function makeDBIntegerSafe( $str ) {
       
       if( !preg_match( "/^\-?\d+$/", $str ) ) return 'NULL';
       else return $str;
       
    }
   
    // everything is true except (case-insensitive) 'false', 'f', 'no', 'n' or a value that evaluates to false.
    // '0' (String 0) is false.
    public static function makeDBBooleanSafe( $val ) {
       
      $val = strtolower( $val );
      $val = "'" . ( !$val || $val=='false' || $val=='f' || $val=='no' || $val=='n' ? 'FALSE' : 'TRUE' ) . "'";
      return $val;
      
    }
   
    public static function makeDBCurrencySafe( $str ) {
       
        return self::makeDBFloatSafe( $str );
       
    }
   
    public static function makeDBFloatSafe( $str ) {
       
       $num = preg_replace( "/[^\d\.]/", '', $str );
       if( $num == '' ) return 'NULL';
       else return $num;
       
    }
   
    public static function makeDBTimeStampSafe( $str ) {
       
        // eg. 2007-06-19 14:15:44
        if( preg_match( '/^\d{4}\-\d\d\-\d\d \d\d?:\d\d:\d\d$/', $str ) ) {
        //if( preg_match( '/^\d{4}\-?\d\d\-?\d\d$/', $str ) ) {
            return "'$str'";
        }
        // else
        ErrorHandler::registerError( "Invalid Timestamp encountered: $str" );
        return '';
       
    }
   
}

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

PreviousNext

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

Who is online

Users browsing this forum: No registered users and 1 guest

cron