Adding items to a Sharepoint list using PHP

July 5, 2011 2 comments

At work I was asked to populate a sharepoint list from a database report. I did a lot of searching on the web for how to’s, they all seemed a little old, but they did head me in the right direction. This is my adventure.

First thing is to get the log into the sharepoint using soap, I used my own class which extends the Zend_Soap_Client class. The most important thing to remember is that after successfully logging in you have to save the cookie to send on subsequent requests. Also remember to set the WSDL to the sharepoint list URL. Below is the code:

/**
 * Log into the sharepoint site
 * @param int $count How many times the function has been called
 * @return Cisc\Web\Soapclient
 */
function webserviceLogin($count=0)
{
    // Create soap client
    $wsdl = 'https://path/to/sharepoint/list/_vti_bin/Authentication.asmx?WSDL';
    $ws = new Cisc\Web\Soapclient($wsdl);
    $login = array('username'=>'user',
                   'password'=>'pass');
    try {
        $rs = $ws->Login($login);
        if($rs->LoginResult->ErrorCode != 'NoError'){
            throw new Exception($rs->LoginResult->ErrorCode);
        }
        $ws->setSoapCookieInfo($rs->LoginResult->CookieName, getCookieValue($ws->getLastResponseHeaders()));
        return $ws;
    } catch (SoapFault $ex) {
        $log = Zend_Registry::get('log');
        $log->err($ex->getMessage());
        sleep(20); // Sleep for 10 seconds and try again
        $count++;
        if ($count < 10) {
            return webserviceLogin($count);
        }
        scriptExit('Unable to process soap call!');
    }
}

Notice the getCookieValue function, this is used to extract the cookie value since sharepoint sends the name on success but not the value. The function parses the HTTP header and extracts the cookie value. The code is below:

/**
 * Get the cookie value from the http header
 *
 * @param string $header
 * @return string
 */
function getCookieValue($header)
{
    $header_array = explode("\r\n",$header);
    foreach($header_array as $header) {
        $loop = explode(":",$header);
        if($loop[0] == 'Set-Cookie') {
            $value = explode(".ASPXAUTH=",$loop[1]);
        }
    }
    return $value[1];
}

The next bit of oddity is creating the XML file to upload. The variable used to hold the new items is called any. Gotta love Microsoft.

/**
 * Generate the xml to populate the lists
 *
 * @param array $data
 * @return string
 */
function generateXml($data)
{
    $id = 1;
    foreach($data as $rowData) {
        $xml_batch .= "<Method Cmd='New' ID='$id'>
                        <Field Name='Title'>{$row['title']}</Field>
                     </Method>";
        $id++;// Increase id number
    }

    $listname = 'list';
    $xml_add = "<Batch ListVersion='1' OnError='Continue'>$xml_batch</Batch>";
    $xml = array(
            'listName' => $listname,
            'updates' => array('any' => $xml_add)
          );
    return $xml;
}

The next thing to do is update the list with the new items.

/**
 * Update the list with the data
 *
 * @param object $ws
 * @param array $params
 */
function updateList($ws,$params)
{
    $wsdl_list = 'https://paht/to/sharepoint/list/_vti_bin/Lists.asmx?WSDL';
    // Change wsdl file
    $ws->setWsdl($wsdl_list);
    try {
        // Need to send cookie for each request
        $ws->sendCookie();
        $rs = $ws->UpdateListItems($params);
    } catch (Exception $ex) {
        $log = Zend_Registry::get('log');
        $log->err($ex->getMessage());
        scriptExit('Unable to update the list: ' . $ex->getMessage());
    }
    return $rs->UpdateListItemsResult->any;
}

And that’s pretty much it. It’s simple once you figure out the oddities but maddening until you do.

Please leave any questions, comments or criticisms.

Categories: PHP, Zend Framework

Favorite Safari 5 Extension

July 30, 2010 Leave a comment

Just installed the Google Reader for Snow Leopard extension and I have to say I like it. Give it a try here. An I really like being able to install and remove extensions with a browser restart.

Categories: Fun Stuff, Mac, Software

Netbeans 6.9

July 20, 2010 Leave a comment

My new favorite PHP IDE is Netbeans 6.9 . Netbeans is great for what I do, but your mileage may vary. First of all it uses a loss less ram then Eclipse which is great because I don’t have a lot. At work I have to use a very old Windows XP desktop, with only 1.5 gigs of ram so anytime I use Eclipse it really slows down the machine.

Netbeans has great Zend Framework integration and making it extremely easy to use Zend Tool. The only feature it lacks for me is jQuery integration. A nice add-on I found is called Path Tools, it makes it easy to copy a project path, open a window with the project directory selected or open a terminal window in the project. The requirements do not state 6.9 compatibility but I have not had any problems. BTW, there is a version of Path Tools for Eclipse.

Categories: PHP, Zend Framework

Using jQuery data function for local storage

July 17, 2010 Leave a comment

I needed to create a decision tree on a web page without refreshing or leaving the page. And, I needed a way to keep the data for the options selected so at the end I could send the data to a database. Since I have to write for IE 6 & 7, no html 5 local storage, I found jQuery data to be the thing I needed. With using jQuery data I was able to create a javascript object, update the information in the object, and then save the object to a hidden div on the page. Another reason to love jQuery!

Categories: jquery

Smarty templating issue

March 24, 2010 Leave a comment

At work I use Smarty for PHP templating, I would prefer to use Zend MVC but our Sever 2003 boxes don’t have url rewriting. End of rant. But I had an issue that was odd and just wanted to post the solution I found, I hope it helps someone. The issue was I was trying to fill a form in using data from a database so the user could edit the information. I was passing a database value and directly assigning it to a Smarty variable. Well the data would render as 0 (zero) when the page was output. There were no errors, just zeros. Well apparently Smarty did not like the hyphen in the word being returned from the database. So I changed the hyphens to underscores and all was well. Let me know if you run into this odd error.

Categories: Uncategorized

Remove all the items in a drop down list except the first using Jquery

November 6, 2009 2 comments

I needed a drop down list to be populated from a selection in another drop down list. Each select should change the options listed in the second list. Using Jquery it was easy to remove all the options and rebuild the list, but I wanted to keep the first option. I finally found the solution searching the Jquery site and it’s quite simple.

selection.children('option:not(:first)').remove();

Where selection is the id of the drop down list. I hope this helps somebody not spend the hour it took me to figure it out.

Categories: jquery

Hide borders for an input box

November 6, 2009 Leave a comment

I wanted to have a form with read only input boxes that were populated by Ajax calls. The problem is there was a border around the box in IE7 and FF 3.5. In IE6 border=0 solved the issue but not in the other browsers. Thanks to this site for the inspiration I was able to remove the borders using this css style:

.hiddenlabel[type="text"] 
{
border:none;
display:inline;
vertical-align:middle;
}

The key is the [type="text"], this applies the style to the input box. Just in case your wondering why I need to do this it is because I need the information in the form to be submitted and need to update the information using Ajax. This was easier than using hidden fields.

Categories: CSS Tags:

Snow Leopard Install

September 13, 2009 Leave a comment

I updated my MacBook Pro to Apple’s latest operating system Snow Leopard 10.6. This is how I did it and my install went fine.
First, check to make sure any programs that you need are compatible or have been updated to work with 10.6. The best place I have found was this wiki http://snowleopard.wikidot.com/. I had some software that was not compatible but for me, but the software was not that big of a deal and I could wait for updates.
The next thing I did was run a full maintenance on my computer using Maintenance. This clean a lot of stuff out and repaired any permissions.
After that I just rebooted to the install disk and followed the onscreen instructions. Everything was fine. I got back about 6GB of space.
I did have to uninstall the software for my HP AIO 2570 printer and add it using the Printers & Faxes, but everything works including scanning. Scanning directly from Preview is nice.
Well that’s how I did it and it worked for me.

Categories: Mac, Software

Save an email attachment using Zend Mail

June 10, 2009 7 comments

To do some automated billing I needed to grab an email attachment off the exchange server. The Zend framework made it very easy to connect to the mail server and navigate files, and that part of the code came directly from the Zend Framework documentation. The issue that took the longest was saving the attachment. I could not figure out how to decode the attachment using the Zend framework. Let me know if you have a better way or if it helps you out.
NOTE: If you getting the mail from the INBOX you do not have to use the getFolders() function.

// Connecting with Imap
$mail = new Zend_Mail_Storage_Imap(
        array('host'     => 'SERVER',
              'user'     => 'USERNAME',
              'password' => 'PASSWORD'));

// Navigate to desired folder
$folder = $mail->getFolders()->INBOX->Info;

// Change to folder
$mail->selectFolder($folder);

// Loop through messages
foreach ($mail as $message)
{
 // Find desired message subject
 if($message->subject == 'SUBJECT')
 {
 // Check for attachment
 if($message->isMultipart())
 {
    $part = $message->getPart(2);
 }

 // Get the attacment file name
 $fileName = $part->getHeader('content-description');

 // Get the attachement and decode
 $attachment = base64_decode($part->getContent());

 // Save the attachment
 $fh = fopen($fileName, 'w');

 fwrite($fh, $attachment);

 fclose($fh);
 }
}

Categories: PHP, Zend Framework

Getting the root node from an XML string

June 3, 2009 Leave a comment

PHPs SimpleXML is great for parsing xml files. The downside is that it does not return the root node name. I wrote this function that gets the name.


/**
 * function getXMLRootNode
 * @param string An xml string
 * @return string Return XML root node name
 */

function getXMLRootNode($xmlstr)
{
 // Create DOM model
 $doc = new DOMDocument();

 // Load the XML string
 if(!$doc->loadXML($xmlstr))
 {
 throw new Exception('Unable to parse XML string');
 }

 // Find the root tag name
 $root = $doc->documentElement;

 if(!isset($root))
 {
 throw new Exception('Unable to find XML root node');
 }

 if(!isset($root->nodeName))
 {
 throw new Exception('Unable to find XML root node name');
 }

 return $root->nodeName;
}

Categories: PHP, Programming
Follow

Get every new post delivered to your Inbox.