7
\$\begingroup\$

I created this class that connects to Gmail contacts, and enables you to add/edit/delete the contact.

I'm curious to see what others think of my code. If you see any areas for improvement, that would be awesome!

  1. The contact[] is purely for testing.
  2. I also realize that it could be more robust, but for my needs, this is all that I need.

<?php

class gmail {

    private $email;
    private $password;

    private $gdata;
    private $client;

    public $protocolVersion = 3;


    //    Load Gmail Libraries
    function __construct()
    {
        require_once 'Zend/Loader.php';
        Zend_Loader::loadClass('Zend_Gdata');
        Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
        Zend_Loader::loadClass('Zend_Http_Client');
        Zend_Loader::loadClass('Zend_Gdata_Query');
        Zend_Loader::loadClass('Zend_Gdata_Feed');

    }


    //    SET CLASS VARIABLES
    public function setOption($option, $value)
    {
        $this->$option = $value;
    }


    //    LOGIN TO GMAIL
    public function login()
    {
        if(!isset($this->email)) {
            die("Email is not set");
        }
        if(!isset($this->password)) {
            die("Password is not set");
        }

        $this->client = Zend_Gdata_ClientLogin::getHttpClient($this->email, $this->password, 'cp');
        $this->client->setHeaders('If-Match: *');

        $this->gdata  = new Zend_Gdata($this->client);
        $this->gdata->setMajorProtocolVersion($this->protocolVersion);
    }


    //    Get contacts feed
    public function getContacts($maxResults = 10)
    {
        try {

            $query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full');
            $query->maxResults = $maxResults;
            $query->setParam('orderby', 'lastmodified');
            $query->setParam('sortorder', 'descending');

            $feed = $this->gdata->getFeed($query);

            return $feed;

        } catch (Exception $e) {
            die('ERROR:' . $e->getMessage());
        }
    }


    //    Determine the schema type from Google
    //    Remove everything but the actual Schema
    public function determineSchemaType($value, $format = 'remove')
    {
        if(!isset($value)) {
            die("Schema is not set.");
        }

        $standard = "http://schemas.google.com/g/2005#";

        if($format == 'remove') {
            $schema = str_replace($standard, '', $value);

        } else if ($format == 'add') {
            $schema = $standard . $value;
        }

        return $schema;
    }


    //    Parse Contacts Feed into simpler objects
    public function parseContactsFeed($feed)
    {
        if(empty($feed)) {
            die("Feed is not set");
        }

        try {

            $results = array();
            foreach($feed as $entry){

                $xml = simplexml_load_string($entry->getXML());
                $obj = new stdClass;

                //    EDIT LINK
                $obj->editLink  = $entry->getEditLink()->href;

                //    FIRST Name
                $obj->firstName  = (string) $xml->name->givenName;
                //    LAST Name
                $obj->familyName = (string) $xml->name->familyName;
                //    MIDDLE Name
                $obj->middleName = (string) $xml->name->additionalName;

                //    Organization
                $obj->orgName     = (string) $xml->organization->orgName;
                $obj->orgNameRel  = (string) $this->determineSchemaType($xml->organization['rel']);
                //    Organization Title
                $obj->orgTitle = (string) $xml->organization->orgTitle;

                //    Get All Email Addresses
                foreach ($xml->email as $e) {
                    $obj->emailAddress[] = (string) $e['address'];
                    $obj->emailType[]    = (string) $this->determineSchemaType($e['rel']);
                }

                //    Get ALL Phone Numbers
                foreach ($xml->phoneNumber as $p) {
                    $obj->phoneNumber[] = (string) $p;
                }

                //    Get ALL Web Addresses
                foreach ($xml->website as $w) {
                    $obj->website[] = (string) $w['href'];
                    $obj->websiteType[] = (string) $w['rel'];
                }

                foreach($xml->structuredPostalAddress as $address) {
                    $obj->addressType[]       = (string) $this->determineSchemaType($address['rel']);
                    $obj->addressStreet[]     = (string) $address->street;
                    $obj->addressPOBox[]      = (string) $address->pobox;
                    $obj->addressPostalCode[] = (string) $address->postcode;
                    $obj->addressCity[]       = (string) $address->city;
                    $obj->addressRegion[]     = (string) $address->region;
                    $obj->addressCountry[]    = (string) $address->country;
                }

                $results[] = $obj;
            }


            return $results;

        } catch (Exception $e) {
            die('ERROR:' . $e->getMessage());
        }
    }


    //    CREATE Contact Object
    public function contact($contact, $action = 'add') 
    {
        if(!isset($contact)) {
            die("Contact is not set");
        }

        try {
            $contact = array();

            $contact['gmailEditLink'] = "http://www.google.com/m8/feeds/contacts/account@gmail.com/base/534653f6089a7ba9";

            $contact['name']         = "John Doe";
            $contact['firstName']    = "John 2";
            $contact['middleName']   = 'Middle';
            $contact['lastName']     = 'Doe 2';

            $contact['emailWork']     = 'john2@johndoe.com';
            $contact['emailPersonal'] = 'john2@gmail.com';

            $contact['company']      = "John Deere";
            $contact['title']        = "Owner";

            $contact['homePhone']    = "250-869-5952";
            $contact['mobilePhone']  = "250-869-5952";
            $contact['workPhone']    = "250-869-5952";
            $contact['workPhone2']   = "250-869-5952";
            $contact['fax']          = "250-869-5952";

            $contact['workCity']     = "Ktown";
            $contact['workAddress']  = "111 Venus Rd";
            $contact['workAddress2'] = "Unit 111";
            $contact['workProvince'] = "BC";
            $contact['workZipCode']  = "v1p 1b1";
            $contact['workCountry']  = "Canada";

            $contact['homeCity']     = "Ktown";
            $contact['homeAddress']  = "222 Venus Rd";
            $contact['homeAddress2'] = "Unit 111";
            $contact['homeProvince'] = "BC";
            $contact['homeZipCode']  = "v1p 1b1";
            $contact['homeCountry']  = "Canada";



            $doc  = new DOMDocument();
            $doc->formatOutput = true;

            $entry = $doc->createElement('atom:entry');
            $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:atom', 'http://www.w3.org/2005/Atom');
            $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd',   'http://schemas.google.com/g/2005');
            $doc->appendChild($entry);


            //    NAME
            $name = $doc->createElement('gd:name');
            $entry->appendChild($name);
                $firstName = $doc->createElement('gd:givenName', $contact['firstName']);
                $name->appendChild($firstName);

                $middleName = $doc->createElement('gd:additionalName', $contact['middleName']);
                $name->appendChild($middleName);

                $lastName = $doc->createElement('gd:familyName', $contact['lastName']);
                $name->appendChild($lastName);


            //    EMAILS
            $email = $doc->createElement('gd:email');
                     $email->setAttribute('address', $contact['emailWork']);
                     $email->setAttribute('displayName', $contact['firstName'] ." ". $contact['lastName']);
                     $email->setAttribute('rel' ,'http://schemas.google.com/g/2005#work');
                     $entry->appendChild($email);

            $email = $doc->createElement('gd:email');
                     $email->setAttribute('address', $contact['emailPersonal']);
                     $email->setAttribute('displayName', $contact['firstName'] ." ". $contact['lastName']);
                     $email->setAttribute('rel' ,'http://schemas.google.com/g/2005#home');
                     $entry->appendChild($email);

            //    PHONE NUMBERS
            $phone = $doc->createElement('gd:phoneNumber', $contact['homePhone']);
                     $phone->setAttribute('rel', 'http://schemas.google.com/g/2005#home');
                     $entry->appendChild($phone);

            $phone = $doc->createElement('gd:phoneNumber', $contact['mobilePhone']);
                     $phone->setAttribute('rel', 'http://schemas.google.com/g/2005#mobile');
                     $entry->appendChild($phone);

            $phone = $doc->createElement('gd:phoneNumber', $contact['workPhone']);
                     $phone->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
                     $entry->appendChild($phone);

            $phone = $doc->createElement('gd:phoneNumber', $contact['workPhone2']);
                     $phone->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
                     $entry->appendChild($phone);

            $phone = $doc->createElement('gd:phoneNumber', $contact['fax']);
                     $phone->setAttribute('rel', 'http://schemas.google.com/g/2005#fax');
                     $entry->appendChild($phone);


            //    ORGANIZATION
            $org = $doc->createElement('gd:organization');
                    $org->setAttribute('rel' ,'http://schemas.google.com/g/2005#work');
                    $entry->appendChild($org);

            $orgName = $doc->createElement('gd:orgName', $contact['company']);
            $org->appendChild($orgName);

            $orgName = $doc->createElement('gd:orgTitle', $contact['title']);
            $org->appendChild($orgName);


            //    WORK ADDRESS
            $workAddress = $doc->createElement('gd:structuredPostalAddress');
                           $workAddress->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
                           $entry->appendChild($workAddress);

                           $workCity = $doc->createElement('gd:city', $contact['workCity']);
                           $workAddress->appendChild($workCity);

                           $workStreet = $doc->createElement('gd:street', $contact['workAddress'] ." :: ". $contact['workAddress2']);
                           $workAddress->appendChild($workStreet);

                           $workProvince = $doc->createElement('gd:region', $contact['workProvince']);
                           $workAddress->appendChild($workProvince);

                           $workZipCode = $doc->createElement('gd:postcode', $contact['workZipCode']);
                           $workAddress->appendChild($workZipCode);

                           $workCountry = $doc->createElement('gd:country', $contact['workCountry']);
                           $workAddress->appendChild($workCountry);

            //    WORK ADDRESS
            $homeAddress = $doc->createElement('gd:structuredPostalAddress');
                           $homeAddress->setAttribute('rel', 'http://schemas.google.com/g/2005#home');
                           $entry->appendChild($homeAddress);

                           $homeCity = $doc->createElement('gd:city', $contact['homeCity']);
                           $homeAddress->appendChild($homeCity);

                           $homeStreet = $doc->createElement('gd:street', $contact['homeAddress'] ." :: ". $contact['homeAddress2']);
                           $homeAddress->appendChild($homeStreet);

                           $homeProvince = $doc->createElement('gd:region', $contact['homeProvince']);
                           $homeAddress->appendChild($homeProvince);

                           $homeZipCode = $doc->createElement('gd:postcode', $contact['homeZipCode']);
                           $homeAddress->appendChild($homeZipCode);

                           $homeCountry = $doc->createElement('gd:country', $contact['homeCountry']);
                           $homeAddress->appendChild($homeCountry);


            //    SAVE CONTACT
            if($action == 'add') {
                $this->addContact($doc->saveXML());
            }

            //    UPDATE CONTACT
            if($action == 'update') {
                $this->updateContact($doc->saveXML(), $contact['gmailEditLink']);
            }

            //    SHOW CONTACT
            if($action == 'show') {
                echo "<pre>";
                print_r($doc->saveXML());
                echo "</pre>";
            }


        } catch (Exception $e) {
            die('ERROR:' . $e->getMessage());
        }
    }


    //    SAVE Contact
    public function addContact($xml)
    {
        if(!isset($xml)) {
            die("XML is not set");
        }

        $results = $this->gdata->insertEntry($xml, 'http://www.google.com/m8/feeds/contacts/default/full');
        echo $results->id;
    }


    //    UPDATE Contact
    public function updateContact($xml, $editLink)
    {
        if(!isset($xml)) {
            die("XML is not set");
        }

        try {

            $extra_header = array();
            $extra_header['If-Match'] = '*';
            $entryResult = $this->gdata->updateEntry($xml, $editLink, null, $extra_header);

            echo 'Entry updated';

        } catch (Exception $e) {
            die('ERROR:' . $e->getMessage());
        }
    }


    //    DELETE Contact
    public function deleteContact($editUrl)
    {
        if(!isset($editUrl)) {
            die("Url is not set");
        }

        try {

            $this->protocolVersion = 1;
            $this->login();

            $entry = $this->gdata->getEntry($editUrl);
                     $this->gdata->delete($entry);

            echo '<h2>Delete Contact</h2>';
            echo 'Entry deleted';

        } catch (Exception $e) {
            die('ERROR:' . $e->getMessage());
        }
    }
 }
?>
\$\endgroup\$
0
3
\$\begingroup\$

A few things to point out:


        $feed = $this->gdata->getFeed($query);
        return $feed;

You can just return feed directly without initialising it.


public function determineSchemaType($value, $format = 'remove')
{
    if(!isset($value)) {
        die("Schema is not set.");
    }

    $standard = "http://schemas.google.com/g/2005#";

    if($format == 'remove') {
        $schema = str_replace($standard, '', $value);

    } else if ($format == 'add') {
        $schema = $standard . $value;
    }

    return $schema;
}
  • You should be keeping consistent spacing after your ifs
  • If the $format is not remove or add, $schema will return undefined/null

            $results[] = $obj;
        }


        return $results;

Why are there so many extraneous empty lines?


    $results = $this->gdata->insertEntry($xml, 'http://www.google.com/m8/feeds/contacts/default/full');
    echo $results->id;

What's wrong with combining them?

echo $this->gdata->insertEntry($xml, 'http://www.google.com/m8/feeds/contacts/default/full')->id;
\$\endgroup\$
2
  • \$\begingroup\$ Hey thanks for the feedback, appreciate the response! Been awhile the class has evolved a bit since then. But the general feedback is always good. \$\endgroup\$
    – Justin
    Sep 1 '15 at 17:56
  • \$\begingroup\$ @Justin You might want to consider posting a self-answer to your question, with information about what you improved with your original code and why/how. \$\endgroup\$ Sep 1 '15 at 21:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.