Fix SQL syntax in service alert check
Fix SQL syntax in service alert check

file:a/.gitignore -> file:b/.gitignore
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@
 /labs/tiles/16
 /labs/tiles/17
 /labs/tiles/19
+/nbproject/private/

--- a/aws/busuiphp.sh
+++ b/aws/busuiphp.sh
@@ -1,16 +1,12 @@
 cp /root/aws.php /tmp/
-mkdir /var/www/lib/staticmaplite/cache 
+chmod  777 /var/cache/lighttpd/compress/
+
 chcon -h system_u:object_r:httpd_sys_content_t /var/www
 chcon -R -h root:object_r:httpd_sys_content_t /var/www/*
-
-chcon -R -t httpd_sys_content_rw_t /var/www/lib/staticmaplite/cache
-chmod -R 777 /var/www/lib/staticmaplite/cache 
 
 chcon -R -t httpd_sys_content_rw_t /var/www/labs/tiles
 chmod -R 777 /var/www/labs/tiles
 
-chcon -R -t httpd_sys_content_rw_t /var/www/lib/openid-php/oid_store
-chmod -R 777 /var/www/lib/openid-php/oid_store
-
 wget http://s3-ap-southeast-1.amazonaws.com/busresources/cbrfeed.zip \
 -O /var/www/cbrfeed.zip
+

--- a/css/local.css.php
+++ b/css/local.css.php
@@ -1,13 +1,15 @@
 <?php
-  header('Content-type: text/css');
-  ob_start("compress");
-  function compress($buffer) {
+
+header('Content-type: text/css');
+ob_start("compress");
+
+function compress($buffer) {
     /* remove comments */
     $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
     /* remove tabs, spaces, newlines, etc. */
     $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
     return $buffer;
-  }
+}
 
 echo '
 .ui-li-thumb, .ui-li-icon { position: relative; }
@@ -86,7 +88,7 @@
 }';
 
 //if (false)
- echo '
+echo '
 // adaptive layout from jQuery Mobile docs site
 .type-interior .content-secondary {
 	border-right: 0;
@@ -113,7 +115,9 @@
 	padding:0;
 	margin: 0;
 }
+	/* hires ahoy */
 @media all and (min-width: 650px){
+
 .content-secondary {
 		text-align: left;
 		float: left;
@@ -210,7 +214,8 @@
 	.type-interior .content-primary {
 		width: 60%;
 	}
-}';
-  ob_end_flush();
+}
+';
+ob_end_flush();
 ?>
 

--- a/include/common-auth.inc.php
+++ b/include/common-auth.inc.php
@@ -1,101 +1,33 @@
 <?php
+require $basePath.'lib/openid.php';
+$openid = new LightOpenID($_SERVER['HTTP_HOST']);
+ 
+function login()
+{
+ global $openid;
+ if(!$openid->mode) {
+    $openid->required = array('contact/email');
+            $openid->identity = 'https://www.google.com/accounts/o8/id';
+            header('Location: ' . $openid->authUrl());
+ }
+    } 
 
-/*
- *    Copyright 2010,2011 Alexander Sadleir 
 
-  Licensed under the Apache License, Version 2.0 (the "License");
-  you may not use this file except in compliance with the License.
-  You may obtain a copy of the License at
+function auth()
 
-  http://www.apache.org/licenses/LICENSE-2.0
-
-  Unless required by applicable law or agreed to in writing, software
-  distributed under the License is distributed on an "AS IS" BASIS,
-  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  See the License for the specific language governing permissions and
-  limitations under the License.
- */
-
-function getScheme() {
-    $scheme = 'http';
-    if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
-        $scheme .= 's';
-    }
-    return $scheme;
-}
-
-function getTrustRoot() {
-    return sprintf("%s://%s:%s%s/", getScheme(), $_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT'], dirname($_SERVER['PHP_SELF']));
-}
-
-// Includes required files
-set_include_path(get_include_path() . PATH_SEPARATOR . $basePath . "lib/openid-php/");
-require_once "Auth/OpenID/Consumer.php";
-require_once "Auth/OpenID/FileStore.php";
-require_once "Auth/OpenID/AX.php";
-
-function login() {
-    global $basePath;
-    // Just tested this with/for Google, needs trying with others ...
-    $oid_identifier = 'https://www.google.com/accounts/o8/id';
-    // Create file storage area for OpenID data
-    $store = new Auth_OpenID_FileStore(realpath($basePath) . '/lib/openid-php/oid_store');
-    // Create OpenID consumer
-    $consumer = new Auth_OpenID_Consumer($store);
-    // Create an authentication request to the OpenID provider
-    $auth = $consumer->begin($oid_identifier);
-
-    // Create attribute request object
-    // See http://code.google.com/apis/accounts/docs/OpenID.html#Parameters for parameters
-    // Usage: make($type_uri, $count=1, $required=false, $alias=null)
-    $attribute[] = Auth_OpenID_AX_AttrInfo :: make('http://axschema.org/contact/email', 2, 1, 'email');
-    $attribute[] = Auth_OpenID_AX_AttrInfo :: make('http://axschema.org/namePerson/first', 1, 1, 'firstname');
-    $attribute[] = Auth_OpenID_AX_AttrInfo :: make('http://axschema.org/namePerson/last', 1, 1, 'lastname');
-
-    // Create AX fetch request
-    $ax = new Auth_OpenID_AX_FetchRequest;
-
-    // Add attributes to AX fetch request
-    foreach ($attribute as $attr) {
-        $ax->add($attr);
-    }
-
-    // Add AX fetch request to authentication request
-    $auth->addExtension($ax);
-    $_SESSION['returnURL'] = curPageURL();
-    // Redirect to OpenID provider for authentication
-    $url = $auth->redirectURL(getTrustRoot(), $_SESSION['returnURL']);
-    header('Location: ' . $url);
-}
-
-function auth() {
-      global $basePath;
-    if ($_SESSION['authed'] == true)
-        return true;
-
-    // Create file storage area for OpenID data
-    $store = new Auth_OpenID_FileStore(realpath($basePath) . '/lib/openid-php/oid_store');
-    // Create OpenID consumer
-    $consumer = new Auth_OpenID_Consumer($store);
-    // Create an authentication request to the OpenID provider
-    $response = $consumer->complete($_SESSION['returnURL']);
-
-    if ($response->status == Auth_OpenID_SUCCESS) {
-        // Get registration informations
-        $ax = new Auth_OpenID_AX_FetchResponse();
-        $obj = $ax->fromSuccessResponse($response);
-        $email = $obj->data['http://axschema.org/contact/email'][0];
-        var_dump($email);
-        if ($email != "maxious@gmail.com") {
+{
+  if ($_SESSION['authed'] == true) return true;
+ global $openid;
+  
+  if($openid->mode) {
+      $attr = $openid->getAttributes();
+        if ($attr["contact/email"] != "maxious@gmail.com") {
             die("Access Denied");
+             } else {
+               $_SESSION['authed'] = true;
+             }
         } else {
-            $_SESSION['authed'] = true;
-        }
-    } else {
         login();
-    }
-}
-
-if ($_REQUEST['janrain_nonce'])
-    auth();
+         } 
+    } 
 ?>

--- a/include/common-geo.inc.php
+++ b/include/common-geo.inc.php
@@ -18,58 +18,49 @@
 // SELECT array_to_string(array(SELECT REPLACE(name_2006, ',', '\,') as name FROM suburbs order by name), ',')
 $suburbs = explode(",", "Acton,Ainslie,Amaroo,Aranda,Banks,Barton,Belconnen,Bonner,Bonython,Braddon,Bruce,Calwell,Campbell,Chapman,Charnwood,Chifley,Chisholm,City,Conder,Cook,Curtin,Deakin,Dickson,Downer,Duffy,Dunlop,Evatt,Fadden,Farrer,Fisher,Florey,Flynn,Forrest,Franklin,Fraser,Fyshwick,Garran,Gilmore,Giralang,Gordon,Gowrie,Greenway,Griffith,Gungahlin,Hackett,Hall,Harrison,Hawker,Higgins,Holder,Holt,Hughes,Hume,Isaacs,Isabella Plains,Kaleen,Kambah,Kingston,Latham,Lawson,Lyneham,Lyons,Macarthur,Macgregor,Macquarie,Mawson,McKellar,Melba,Mitchell,Monash,Narrabundah,Ngunnawal,Nicholls,Oaks Estate,O'Connor,O'Malley,Oxley,Page,Palmerston,Parkes,Pearce,Phillip,Pialligo,Red Hill,Reid,Richardson,Rivett,Russell,Scullin,Spence,Stirling,Symonston,Tharwa,Theodore,Torrens,Turner,Wanniassa,Waramanga,Watson,Weetangera,Weston,Yarralumla");
 
-function staticmap($mapPoints, $zoom = 0, $markerImage = "iconb", $collapsible = true, $twotone = false) {
-    global $basePath;
-    $width = 300;
+function staticmap($mapPoints, $collapsible = true, $twotone = false, $path = false, $numbered = false) {
+
+    $markers = "";
     $height = 300;
-    $metersperpixel[9] = 305.492 * $width;
-    $metersperpixel[10] = 152.746 * $width;
-    $metersperpixel[11] = 76.373 * $width;
-    $metersperpixel[12] = 38.187 * $width;
-    $metersperpixel[13] = 19.093 * $width;
-    $metersperpixel[14] = 9.547 * $width;
-    $metersperpixel[15] = 4.773 * $width;
-    //$metersperpixel[16] = 2.387 * $width;
-    // $metersperpixel[17]=1.193*$width;
-    $center = "";
-    $markers = "";
-    $mapwidthinmeters = 50;
+    $width = $height;
+    $index = 0;
     if (sizeof($mapPoints) < 1)
         return "map error";
     if (sizeof($mapPoints) === 1) {
-        if ($zoom == 0)
-            $zoom = 14;
-        $markers.= "{$mapPoints[0][0]},{$mapPoints[0][1]},$markerimage";
-        $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}";
-    }
-    else {
+        $markers = "markers={$mapPoints[0][0]},{$mapPoints[0][1]}";
+    } else {
+        if (!$numbered) {
+            $markers = "markers=";
+        }
+        if ($path) {
+            $markers.= "markers={$mapPoints[0][0]},{$mapPoints[0][1]}&amp;path=";
+        }
         foreach ($mapPoints as $index => $mapPoint) {
             if ($twotone && $index == 0) {
-                $markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . "iconr" . ($index + 1);
-                $center = "{$mapPoints[0][0]},{$mapPoints[0][1]}";
+                $markers = "markerd=color:red|".$mapPoint[0] . "," . $mapPoint[1]."&amp;markers=";
             } else {
-                $markers.= $mapPoint[0] . "," . $mapPoint[1] . "," . $markerImage . ($index + 1);
-            }
-            if ($index + 1 != sizeof($mapPoints))
-                $markers.= "|";
-            $dist = distance($mapPoints[0][0], $mapPoint[0][1], $mapPoint[0], $mapPoint[1]);
-            $mapwidthinmeters = ($dist > $mapwidthinmeters ? $dist : $mapwidthinmeters);
-            $totalLat+= $mapPoint[0];
-            $totalLon+= $mapPoint[1];
-        }
-        if ($zoom == 0) {
-            $mapwidthinmeters = distance($minlat, $minlon, $minlat, $maxlon);
-            foreach (array_reverse($metersperpixel, true) as $zoomLevel => $maxdistance) {
-                if ($zoom == 0 && $mapwidthinmeters * 1.5 < ($maxdistance))
-                    $zoom = $zoomLevel;
+                if ($numbered) {
+                    $label = ($index > 9 ? 9 : $index);
+                    $markers.= "markers=label:$label|" . $mapPoint[0] . "," . $mapPoint[1];
+                    if ($index + 1 != sizeof($mapPoints)) {
+                        $markers.= "&amp;";
+                    }
+                } else {
+                    $markers.= $mapPoint[0] . "," . $mapPoint[1];
+                    if ($index + 1 != sizeof($mapPoints)) {
+                        $markers.= "|";
+                    }
+                }
+                $index++;
             }
         }
-        $center = $totalLat / sizeof($mapPoints) . "," . $totalLon / sizeof($mapPoints);
     }
     $output = "";
     if ($collapsible)
         $output.= '<div class="map" data-role="collapsible" data-collapsed="true"><h3>Open Map...</h3>';
-    $output.= '<img class="map" src="' . curPageURL() . '/' . $basePath . '/lib/staticmaplite/staticmap.php?center=' . $center . '&amp;zoom=' . $zoom . '&amp;size=' . $width . 'x' . $height . '&amp;markers=' . $markers . '" width=' . $width . ' height=' . $height . '>';
+   if (isIOSDevice()) $output.= '<img class="hiresmap" src="http://maps.googleapis.com/maps/api/staticmap?size=' . $width . 'x' . $height . '&amp;' . $markers . '&amp;scale=2&amp;sensor=true" width=' . $width . ' height=' . $height . '>';
+ else $output.= '<img class="lowresmap" src="http://maps.googleapis.com/maps/api/staticmap?size=' . $width . 'x' . $height . '&amp;' . $markers . '&amp;scale=1&amp;format=jpg&amp;sensor=true" width=' . $width . ' height=' . $height . '>';
+   
     if ($collapsible)
         $output.= '</div>';
     return $output;

--- a/include/common-request.inc.php
+++ b/include/common-request.inc.php
@@ -33,10 +33,18 @@
 if (isset($_REQUEST['suburb'])) {
     $suburb = $_REQUEST['suburb'];
 }
-$pageKey = filter_var($_REQUEST['pageKey'], FILTER_SANITIZE_NUMBER_INT);
-$lat = filter_var($_REQUEST['lat'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
-$lon = filter_var($_REQUEST['lon'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
-$max_distance = filter_var($_REQUEST['radius'], FILTER_SANITIZE_NUMBER_INT);
+if (isset($_REQUEST['pageKey'])) {
+    $pageKey = filter_var($_REQUEST['pageKey'], FILTER_SANITIZE_NUMBER_INT);
+}
+if (isset($_REQUEST['lat'])) {
+    $lat = filter_var($_REQUEST['lat'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
+}
+if (isset($_REQUEST['lon'])) {
+    $lon = filter_var($_REQUEST['lon'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
+}
+if (isset($_REQUEST['radius'])) {
+    $max_distance = filter_var($_REQUEST['radius'], FILTER_SANITIZE_NUMBER_INT);
+}
 if (isset($_REQUEST['numberSeries'])) {
     $numberSeries = filter_var($_REQUEST['numberSeries'], FILTER_SANITIZE_NUMBER_INT);
 }

--- a/include/common-template.inc.php
+++ b/include/common-template.inc.php
@@ -42,7 +42,7 @@
 }
 
 function include_header($pageTitle, $pageType, $opendiv = true, $geolocate = false, $datepicker = false) {
-    global $basePath, $serviceAlertsEnabled;
+    global $basePath, $GTFSREnabled;
     echo '
 <!DOCTYPE html> 
 <html lang="en">
@@ -103,7 +103,7 @@
 }';
     echo '</style>';
     echo '<link rel="stylesheet"  href="' . $basePath . 'css/local.css.php" />';
-    if (strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
+    if (isIOSDevice()){
         echo '<meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <link rel="apple-touch-startup-image" href="startup.png" />
@@ -179,9 +179,11 @@
         }
         if ($GTFSREnabled) {
             $serviceAlerts = getServiceAlertsAsArray("agency", "0");
-            foreach ($serviceAlerts['entity'] as $entity) {
-                echo "<div id='servicewarning'>" . date("F j, g:i a", strtotime($entity['alert']['active_period'][0]['start'])) . " to " . date("F j, g:i a", strtotime($entity['alert']['active_period'][0]['end'])) . "{$entity['alert']['header_text']['translation'][0]['text']}<br>Warning: {$entity['alert']['description_text']['translation'][0]['text']} 
-			<br><a href='{$entity['alert']['url']['translation'][0]['text']}'>Source</a>  </div>";
+            if (isset($serviceAlerts['entity']) && sizeof($serviceAlerts['entity']) > 0) {
+                foreach ($serviceAlerts['entity'] as $entity) {
+                    echo "<div id='servicewarning'>" . date("F j, g:i a", strtotime($entity['alert']['active_period'][0]['start'])) . " to " . date("F j, g:i a", strtotime($entity['alert']['active_period'][0]['end'])) . "{$entity['alert']['header_text']['translation'][0]['text']}<br>Warning: {$entity['alert']['description_text']['translation'][0]['text']} 
+                            <br><a href='{$entity['alert']['url']['translation'][0]['text']}'>Source</a>  </div>";
+                }
             }
         }
     }

--- a/include/common.inc.php
+++ b/include/common.inc.php
@@ -48,6 +48,8 @@
 $basePath = "";
 if (strstr($_SERVER['PHP_SELF'], "labs/")
         || strstr($_SERVER['PHP_SELF'], "myway/")
+        || strstr($_SERVER['PHP_SELF'], "lib/")
+        || strstr($_SERVER['PHP_SELF'], "include/")
         || strstr($_SERVER['PHP_SELF'], "servicealerts/"))
     $basePath = "../";
 
@@ -81,31 +83,15 @@
     if (isDebug($debugReason))
         echo "\n<!-- " . date(DATE_RFC822) . "\n $msg -->\n";
 }
-
+function isIOSDevice() {
+   return strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPod') || strstr($_SERVER['HTTP_USER_AGENT'], 'iPad');
+}
 function isJQueryMobileDevice() {
     // http://forum.jquery.com/topic/what-is-the-best-way-to-detect-all-useragents-which-can-handle-jquery-mobile#14737000002087897
     $user_agent = $_SERVER['HTTP_USER_AGENT'];
     return preg_match('/iphone/i', $user_agent) || preg_match('/android/i', $user_agent) || preg_match('/webos/i', $user_agent) || preg_match('/ios/i', $user_agent) || preg_match('/bada/i', $user_agent) || preg_match('/maemo/i', $user_agent) || preg_match('/meego/i', $user_agent) || preg_match('/fennec/i', $user_agent) || (preg_match('/symbian/i', $user_agent) && preg_match('/s60/i', $user_agent) && $browser['majorver'] >= 5) || (preg_match('/symbian/i', $user_agent) && preg_match('/platform/i', $user_agent) && $browser['majorver'] >= 3) || (preg_match('/blackberry/i', $user_agent) && $browser['majorver'] >= 5) || (preg_match('/opera mobile/i', $user_agent) && $browser['majorver'] >= 10) || (preg_match('/opera mini/i', $user_agent) && $browser['majorver'] >= 5);
 }
 
-function isFastDevice() {
-    $ua = $_SERVER['HTTP_USER_AGENT'];
-    $fastDevices = Array(
-        "Mozilla/5.0 (X11;",
-        "Mozilla/5.0 (Windows;",
-        "Mozilla/5.0 (iP",
-        "Mozilla/5.0 (Linux; U; Android",
-        "Mozilla/4.0 (compatible; MSIE"
-    );
-    $slowDevices = Array(
-        "J2ME",
-        "MIDP",
-        "Opera/",
-        "Mozilla/2.0 (compatible;",
-        "Mozilla/3.0 (compatible;"
-    );
-    return true;
-}
 
 function array_flatten($a, $f = array()) {
     if (!$a || !is_array($a))

--- a/include/db/servicealert-dao.inc.php
+++ b/include/db/servicealert-dao.inc.php
@@ -32,7 +32,7 @@
 
 function getServiceAlert($alertID) {
     global $conn;
-    $query = "SELECT id,extract('epoch', start) as start, extract('epoch', end) as end,cause,effect,header,description,url from servicealerts_alerts where id = :servicealert_id";
+    $query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from end) as end,cause,effect,header,description,url from servicealerts_alerts where id = :servicealert_id";
     debug($query, "database");
     $query = $conn->prepare($query);
     $query->bindParam(":servicealert_id", $alertID);
@@ -87,7 +87,7 @@
 
 function getCurrentAlerts() {
     global $conn;
-    $query = "SELECT id,extract('epoch', start) as start, extract('epoch', end) as end,cause,effect,header,description,url from servicealerts_alerts where NOW() > start and NOW() < \"end\"";
+    $query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from end) as end,cause,effect,header,description,url from servicealerts_alerts where NOW() > start and NOW() < \"end\"";
     // debug($query, "database");
     $query = $conn->prepare($query);
     $query->execute();
@@ -100,7 +100,7 @@
 
 function getFutureAlerts() {
     global $conn;
-    $query = "SELECT id,extract('epoch', start) as start, extract('epoch', end) as end,cause,effect,header,description,url from servicealerts_alerts where NOW() > start or NOW() < \"end\"";
+    $query = "SELECT id,extract('epoch' from start) as start, extract('epoch' from end) as end,cause,effect,header,description,url from servicealerts_alerts where NOW() > start or NOW() < \"end\"";
     // debug($query, "database");
     $query = $conn->prepare($query);
     $query->execute();

--- a/labs/stop.pdf.php
+++ b/labs/stop.pdf.php
@@ -34,7 +34,7 @@
                 $stop[2],
                 $stop[3]
             )
-                ), 0, "iconb", false) . "</td></tr>";
+                ), 0, false) . "</td></tr>";
 $url = $APIurl . "/json/stoptrips?stop=" . $stopid . "&time=" . midnight_seconds() . "&service_period=" . service_period();
 $trips = json_decode(getPage($url));
 $html.= "</table><br><br><table>";

--- a/lib/autocomplete.php
+++ b/lib/autocomplete.php
@@ -3,7 +3,7 @@
 $result = Array();
 if (isset($_REQUEST['term'])) {
 	$term = filter_var($_REQUEST['term'], FILTER_SANITIZE_STRING);
-	$query = "Select stop_name,min(stop_lat) as stop_lat,min(stop_lon) as stop_lon from stops where stop_name LIKE :term group by stop_name";
+	$query = "Select stop_name,min(stop_lat) as stop_lat,min(stop_lon) as stop_lon from stops where stop_name ILIKE :term group by stop_name";
 	$query = $conn->prepare($query);
 	$term = "$term%";
 	$query->bindParam(":term", $term);

--- a/lib/openid-php/Auth/OpenID.php
+++ /dev/null
@@ -1,564 +1,1 @@
-<?php
 
-/**
- * This is the PHP OpenID library by JanRain, Inc.
- *
- * This module contains core utility functionality used by the
- * library.  See Consumer.php and Server.php for the consumer and
- * server implementations.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: See the COPYING file included in this distribution.
- *
- * @package OpenID
- * @author JanRain, Inc. <openid@janrain.com>
- * @copyright 2005-2008 Janrain, Inc.
- * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
- */
-
-/**
- * The library version string
- */
-define('Auth_OpenID_VERSION', '2.2.2');
-
-/**
- * Require the fetcher code.
- */
-require_once "Auth/Yadis/PlainHTTPFetcher.php";
-require_once "Auth/Yadis/ParanoidHTTPFetcher.php";
-require_once "Auth/OpenID/BigMath.php";
-require_once "Auth/OpenID/URINorm.php";
-
-/**
- * Status code returned by the server when the only option is to show
- * an error page, since we do not have enough information to redirect
- * back to the consumer. The associated value is an error message that
- * should be displayed on an HTML error page.
- *
- * @see Auth_OpenID_Server
- */
-define('Auth_OpenID_LOCAL_ERROR', 'local_error');
-
-/**
- * Status code returned when there is an error to return in key-value
- * form to the consumer. The caller should return a 400 Bad Request
- * response with content-type text/plain and the value as the body.
- *
- * @see Auth_OpenID_Server
- */
-define('Auth_OpenID_REMOTE_ERROR', 'remote_error');
-
-/**
- * Status code returned when there is a key-value form OK response to
- * the consumer. The value associated with this code is the
- * response. The caller should return a 200 OK response with
- * content-type text/plain and the value as the body.
- *
- * @see Auth_OpenID_Server
- */
-define('Auth_OpenID_REMOTE_OK', 'remote_ok');
-
-/**
- * Status code returned when there is a redirect back to the
- * consumer. The value is the URL to redirect back to. The caller
- * should return a 302 Found redirect with a Location: header
- * containing the URL.
- *
- * @see Auth_OpenID_Server
- */
-define('Auth_OpenID_REDIRECT', 'redirect');
-
-/**
- * Status code returned when the caller needs to authenticate the
- * user. The associated value is a {@link Auth_OpenID_ServerRequest}
- * object that can be used to complete the authentication. If the user
- * has taken some authentication action, use the retry() method of the
- * {@link Auth_OpenID_ServerRequest} object to complete the request.
- *
- * @see Auth_OpenID_Server
- */
-define('Auth_OpenID_DO_AUTH', 'do_auth');
-
-/**
- * Status code returned when there were no OpenID arguments
- * passed. This code indicates that the caller should return a 200 OK
- * response and display an HTML page that says that this is an OpenID
- * server endpoint.
- *
- * @see Auth_OpenID_Server
- */
-define('Auth_OpenID_DO_ABOUT', 'do_about');
-
-/**
- * Defines for regexes and format checking.
- */
-define('Auth_OpenID_letters',
-       "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
-
-define('Auth_OpenID_digits',
-       "0123456789");
-
-define('Auth_OpenID_punct',
-       "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
-
-Auth_OpenID_include_init();
-
-/**
- * The OpenID utility function class.
- *
- * @package OpenID
- * @access private
- */
-class Auth_OpenID {
-
-    /**
-     * Return true if $thing is an Auth_OpenID_FailureResponse object;
-     * false if not.
-     *
-     * @access private
-     */
-    static function isFailure($thing)
-    {
-        return is_a($thing, 'Auth_OpenID_FailureResponse');
-    }
-
-    /**
-     * Gets the query data from the server environment based on the
-     * request method used.  If GET was used, this looks at
-     * $_SERVER['QUERY_STRING'] directly.  If POST was used, this
-     * fetches data from the special php://input file stream.
-     *
-     * Returns an associative array of the query arguments.
-     *
-     * Skips invalid key/value pairs (i.e. keys with no '=value'
-     * portion).
-     *
-     * Returns an empty array if neither GET nor POST was used, or if
-     * POST was used but php://input cannot be opened.
-     *
-     * See background:
-     * http://lists.openidenabled.com/pipermail/dev/2007-March/000395.html
-     *
-     * @access private
-     */
-    static function getQuery($query_str=null)
-    {
-        $data = array();
-
-        if ($query_str !== null) {
-            $data = Auth_OpenID::params_from_string($query_str);
-        } else if (!array_key_exists('REQUEST_METHOD', $_SERVER)) {
-            // Do nothing.
-        } else {
-          // XXX HACK FIXME HORRIBLE.
-          //
-          // POSTing to a URL with query parameters is acceptable, but
-          // we don't have a clean way to distinguish those parameters
-          // when we need to do things like return_to verification
-          // which only want to look at one kind of parameter.  We're
-          // going to emulate the behavior of some other environments
-          // by defaulting to GET and overwriting with POST if POST
-          // data is available.
-          $data = Auth_OpenID::params_from_string($_SERVER['QUERY_STRING']);
-
-          if ($_SERVER['REQUEST_METHOD'] == 'POST') {
-            $str = file_get_contents('php://input');
-
-            if ($str === false) {
-              $post = array();
-            } else {
-              $post = Auth_OpenID::params_from_string($str);
-            }
-
-            $data = array_merge($data, $post);
-          }
-        }
-
-        return $data;
-    }
-
-    static function params_from_string($str)
-    {
-        $chunks = explode("&", $str);
-
-        $data = array();
-        foreach ($chunks as $chunk) {
-            $parts = explode("=", $chunk, 2);
-
-            if (count($parts) != 2) {
-                continue;
-            }
-
-            list($k, $v) = $parts;
-            $data[urldecode($k)] = urldecode($v);
-        }
-
-        return $data;
-    }
-
-    /**
-     * Create dir_name as a directory if it does not exist. If it
-     * exists, make sure that it is, in fact, a directory.  Returns
-     * true if the operation succeeded; false if not.
-     *
-     * @access private
-     */
-    static function ensureDir($dir_name)
-    {
-        if (is_dir($dir_name) || @mkdir($dir_name)) {
-            return true;
-        } else {
-            $parent_dir = dirname($dir_name);
-
-            // Terminal case; there is no parent directory to create.
-            if ($parent_dir == $dir_name) {
-                return true;
-            }
-
-            return (Auth_OpenID::ensureDir($parent_dir) && @mkdir($dir_name));
-        }
-    }
-
-    /**
-     * Adds a string prefix to all values of an array.  Returns a new
-     * array containing the prefixed values.
-     *
-     * @access private
-     */
-    static function addPrefix($values, $prefix)
-    {
-        $new_values = array();
-        foreach ($values as $s) {
-            $new_values[] = $prefix . $s;
-        }
-        return $new_values;
-    }
-
-    /**
-     * Convenience function for getting array values.  Given an array
-     * $arr and a key $key, get the corresponding value from the array
-     * or return $default if the key is absent.
-     *
-     * @access private
-     */
-    static function arrayGet($arr, $key, $fallback = null)
-    {
-        if (is_array($arr)) {
-            if (array_key_exists($key, $arr)) {
-                return $arr[$key];
-            } else {
-                return $fallback;
-            }
-        } else {
-            trigger_error("Auth_OpenID::arrayGet (key = ".$key.") expected " .
-                          "array as first parameter, got " .
-                          gettype($arr), E_USER_WARNING);
-
-            return false;
-        }
-    }
-
-    /**
-     * Replacement for PHP's broken parse_str.
-     */
-    static function parse_str($query)
-    {
-        if ($query === null) {
-            return null;
-        }
-
-        $parts =