Coding Bits and Logic

Various logic and code bits to help you with various scripting tasks.

HowTo: Publish Exchange Public Calendar with PHP

My goal was to extract appointment info from an Exchange Public Calendar to be displayed on an intranet site. This can be accomplished using the Exchange Web Services. Microsoft has examples using C# and the EWS API to access the data. Also you can use Perl or PHP module code contributed by the communities to extract this. I chose to go the PHP route vs. trying to install all the wonderful perl modules/dependencies and/or learning C#.

Using the code found here:
http://code.google.com/p/php-ews/

Here is a really simple / stripped example of what I did to extract the data. I have used this to create an HTML page for an event list for the current day, a breakdown of events for X number of upcoming days, and even created a detailed day/time calendar grid extracting color categories from the calendar. Note times come back in UTC from Exchange. Also I dump the entire response into the HTML for debugging info.

Tested in Exchange 2007.


$today = Date("Y-m-d");
$host = 'mail.domain.com';
$username = 'restricted-user';
$password = 'password';
$localTZ = 'America/New_York';
$daysahead = '1'; // Today Only
$EWScalendar = 'SharedCalendar@domain.com';
$ews = new ExchangeWebServices ($host, $username, $password);
$request = new EWSType_FindItemType();
$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;
$request->CalendarView = new EWSType_CalendarViewType();
$request->CalendarView->StartDate = date ('c',strtotime("$today"));
$request->CalendarView->EndDate = date ('c',strtotime("$today + $daysahead days"));
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::CALENDAR;
$mailBox = new EWSType_EmailAddressType();
$mailBox->EmailAddress = "$EWScalendar";
$request->ParentFolderIds->DistinguishedFolderId->Mailbox = $mailBox;
$response = $ews->FindItem($request);
$TotalItemCount = $response->ResponseMessages->FindItemResponseMessage->RootFolder->TotalItemsInView;
// LOOP through the Event Data and Parse each item
for ( $ItemID = 0; $ItemID < $TotalItemCount; $ItemID++) {
--do something with item data--
$subject = $response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->CalendarItem[$ItemID]->Subject;
}
echo '<!--';
echo 'Raw Data Captured<br><pre>';
print_r($response);
echo '</pre> ';
echo '-->'

PHP - Input Variables from URL

I wanted to be able to generate a small little bit of content based on a variable the user sets. I could have created a small form, but in this case it was easier to pass the variable in a link based on a choice the user selected. Here is a really simple example of passing a variable via URL string to my php page.

if ($_GET["id"]) {
  $programID = $_GET["id"];
} else {
  $programID = "not specified";
}
echo "Program ID is $programID \n";

It's always important to have cases / defensive / debugging code. Keeps the logs cleaner, makes items easier to fix/debug, and it is just good clean living.

WARNING - I'm not an expert coder/developer, just posting little bits I learn as I go.

UPDATED - Thanks to @j_angliss for providing the more elegant solution. If 'id' in this case is legitimately "0" (zero), then the evaluation would not execute and be treated as false (aka "0"). Try this code instead...

if (array_key_exists('if',$_GET)) {

PHP - Read Data from a CSV file

I found myself needing to alter a PHP program I had that queried for data to one that read from a CSV file. After a little research, seems it is really straight forward. There is the fgetcsv function which makes it all a snap. Here is the example from PHP.net's website.

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

WARNING - I'm not an expert coder/developer, just posting little bits I learn as I go.

Perl Array Comparison

Here's a great example for an array comparison mechanism in perl to find out what is in common, what is different, etc.

 


$ cat ./compare_array.pl
#!/usr/bin/perl

use strict;
use warnings;

my @array1;
my @array2;
my @diff;
my @isect;
my $item;
my %count;

@array1 = (1, 2, 4, 6, 7, 8);
@array2 = (1, 2, 3, 5, 6, 7);

@isect = ( );
@diff = ( );
%count = ( );

foreach $item (@array1, @array2) { $count{$item}++;}

foreach $item (keys %count) {
if ($count{$item} == 2) {
push @isect, $item;
} else {
push @diff, $item;
}
}

print "\nA Array = @array1\n";

print "\nB Array = @array2\n";

print "\nIntersect Array = @isect\n";

print "\nDiff Array = @diff\n\n";

exit 0;

$ ./compare_array.pl

A Array = 1 2 4 6 7 8

B Array = 1 2 3 5 6 7

Intersect Array = 6 1 7 2

Diff Array = 8 4 3 5

 

Perl Split Function Example

The perl split function is handy for breaking up a string into several values.  For example if you are reading lines from a file and want to split that line into some different values, manipulate them, and spit them into a new file.  If you're lucky, the line is delimited by something like a ^ (carrot) charcater.

So, source line is something like: 

larry^moe^curly

You can use a one liner like this to break up the line into 3 values...

($value1,$value2,$value3)=split(/\^/,$line);

Note how we had to escaple the ^ with a backslash.  So now ...

print "$value1 --- $value2 --- $value3";

will print "larry --- moe --- curly".  If there were numbers, you can quickly read in a data file, calculate some values and spill out a new results file.  Or split a string into component values to be used later... be creative!