Nearby routes and routes by suburb
--- a/common-template.inc.php
+++ b/common-template.inc.php
@@ -122,7 +122,7 @@
or enter an address/co-ordinates in the box below.</div>';
}
echo '<div data-role="collapsible" data-collapsed="' . !$geoerror . '">
- <h3>Change Time/Place...</h3>
+ <h3>Change Time/Place (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' '.ucwords(service_period()).')...</h3>
<form action="" method="post">
<div class="ui-body">
<div data-role="fieldcontain">
--- a/common.inc.php
+++ b/common.inc.php
@@ -9,7 +9,8 @@
$debugOkay = Array(
"session",
"json",
- "phperror"
+ "phperror",
+ "other"
);
if (isDebug("phperror")) error_reporting(E_ALL ^ E_NOTICE);
include_once ("common-geo.inc.php");
@@ -25,13 +26,22 @@
$_SESSION['time'] = filter_var($_REQUEST['time'], FILTER_SANITIZE_STRING);
}
if (isset($_REQUEST['geolocate'])) {
+
$geocoded = false;
if (isset($_REQUEST['lat']) && isset($_REQUEST['lon'])) {
- $_SESSION['lat'] = filter_var($_REQUEST['lat'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
- $_SESSION['lon'] = filter_var($_REQUEST['lon'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
+ $_SESSION['lat'] = trim(filter_var($_REQUEST['lat'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
+ $_SESSION['lon'] = trim(filter_var($_REQUEST['lon'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
}
else {
- $contents = geocode(filter_var($_REQUEST['geolocate'], FILTER_SANITIZE_URL) , true);
+ $geolocate = filter_var($_REQUEST['geolocate'], FILTER_SANITIZE_URL);
+ echo $_REQUEST['geolocate'];
+ if (startsWith($geolocate, "-")) {
+ $locateparts = explode(",",$geolocate);
+ $_SESSION['lat'] = $locateparts[0];
+ $_SESSION['lon'] =$locateparts[1];
+ } else {
+ $contents = geocode($geolocate, true);
+ print_r($contents);
if (isset($contents[0]->centroid)) {
$geocoded = true;
$_SESSION['lat'] = $contents[0]->centroid->coordinates[0];
@@ -40,6 +50,7 @@
else {
$_SESSION['lat'] = "";
$_SESSION['lon'] = "";
+ }
}
}
if ($_SESSION['lat'] != "" && isMetricsOn()) {
@@ -139,5 +150,33 @@
{
return str_replace(")", "</small>", str_replace("(", "<br><small>", $input));
}
+
+function sksort(&$array, $subkey="id", $sort_ascending=false) {
+
+ if (count($array))
+ $temp_array[key($array)] = array_shift($array);
+
+ foreach($array as $key => $val){
+ $offset = 0;
+ $found = false;
+ foreach($temp_array as $tmp_key => $tmp_val)
+ {
+ if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
+ {
+ $temp_array = array_merge( (array)array_slice($temp_array,0,$offset),
+ array($key => $val),
+ array_slice($temp_array,$offset)
+ );
+ $found = true;
+ }
+ $offset++;
+ }
+ if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
+ }
+
+ if ($sort_ascending) $array = array_reverse($temp_array);
+
+ else $array = $temp_array;
+}
?>
--- a/layar_api.php
+++ b/layar_api.php
@@ -9,7 +9,6 @@
$page_end = $max_page + 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);
-if (isset($_REQUEST['radius'])) $radius = filter_var($_REQUEST['radius'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$url = $APIurl . "/json/neareststops?lat=$lat&lon=$lon&limit=50";
$contents = json_decode(getPage($url));
debug(print_r($contents, true));
@@ -24,24 +23,22 @@
$hotspot['lat'] = floor($row[2] * 1000000);
$hotspot['lon'] = floor($row[3] * 1000000);
$hotspot['distance'] = distance($row[2], $row[3], $_REQUEST['lat'], $_REQUEST['lon']);
- if (!isset($_REQUEST['radius']) || $hotspot['distance'] < $radius) {
- $hotspot['actions'] = Array(
- Array(
- "label" => 'View more trips/information',
- 'uri' => 'http://bus.lambdacomplex.org/' . 'stop.php?stopid=' . $row[0]
- )
- );
- $url = $APIurl . "/json/stoptrips?stop=" . $row[0] . "&time=" . midnight_seconds() . "&service_period=" . service_period() . "&limit=4&time_range=" . str(90 * 60);
- $trips = json_decode(getPage($url));
- debug(print_r($trips, true));
- foreach ($trips as $key => $row) {
- if ($key < 3) {
- $hotspot['line' . strval($key + 2) ] = $row[1][1] . ' @ ' . midnight_seconds_to_time($row[0]);
- }
+ $hotspot['actions'] = Array(
+ Array(
+ "label" => 'View more trips/information',
+ 'uri' => 'http://bus.lambdacomplex.org/' . 'stop.php?stopid=' . $row[0]
+ )
+ );
+ $url = $APIurl . "/json/stoptrips?stop=" . $row[0] . "&time=" . midnight_seconds() . "&service_period=" . service_period() . "&limit=4&time_range=" . strval(90 * 60);
+ $trips = json_decode(getPage($url));
+ debug(print_r($trips, true));
+ foreach ($trips as $key => $row) {
+ if ($key < 3) {
+ $hotspot['line' . strval($key + 2) ] = $row[1][1] . ' @ ' . midnight_seconds_to_time($row[0]);
}
- if (sizeof($trips) == 0) $hotspot['line2'] = 'No trips in the near future.';
- $output['hotspots'][] = $hotspot;
}
+ if (sizeof($trips) == 0) $hotspot['line2'] = 'No trips in the near future.';
+ $output['hotspots'][] = $hotspot;
}
}
if (sizeof($hotspot) > 0) {
--- /dev/null
+++ b/myway_api.json.php
@@ -1,1 +1,125 @@
+<?php
+function cleanString($subject)
+{
+ $subject = str_replace(" ", " ", $subject);
+ $subject = str_replace("&", "&", $subject);
+ $subject = preg_replace('/[^\r\n\t\x20-\x7E\xA0-\xFF]/', '', $subject);
+ $subject = str_replace(" ", " ", $subject);
+ return trim($subject);
+}
+$return = Array();
+/*if (file_exists("mywayresponse.txt")) {
+ @$fh = fopen("mywayresponse.txt", 'r');
+ if ($fh) {
+ $pageHTML = fread($fh, filesize("mywayresponse.txt"));
+ fclose($fh);
+ }
+}*/
+//set POST variables
+$url = 'https://www.action.act.gov.au/ARTS/use_Funcs.asp';
+$field_mapping = Array(
+ "card_number" => "SRNO",
+ "DOBmonth" => "month",
+ "DOBday" => "day",
+ "DOByear" => "year",
+ "secret_answer" => "pwrd",
+ "button" => "button"
+);
+foreach (Array(
+ "card_number",
+ "DOBday",
+ "DOBmonth",
+ "DOByear"
+) as $field_name) {
+ if (isset($_REQUEST[$field_name])) {
+ $fields[$field_name] = filter_var($_REQUEST[$field_name], FILTER_SANITIZE_NUMBER_INT);
+ }
+ else {
+ $return["error"][] = $field_name. " parameter invalid or unspecified";
+ }
+}
+if (isset($_REQUEST['secret_answer'])) {
+ $fields['secret_answer'] = filter_var($_REQUEST['secret_answer'], FILTER_SANITIZE_STRING, Array(
+ FILTER_FLAG_NO_ENCODE_QUOTES,
+ FILTER_FLAG_STRIP_HIGH,
+ FILTER_FLAG_STRIP_LOW
+ ));
+}
+else {
+ $return["error"][] = "secret_answer parameter invalid or unspecified";
+}
+$fields['button'] = 'Submit';
+$fields_string = "";
+//url-ify the data for the POST
+foreach ($fields as $key => $value) {
+ if (sizeof($value) === 0) $return['error'][] = $key . " parameter invalid or unspecified";
+ $fields_string.= $field_mapping[$key] . '=' . $value . '&';
+}
+$fields_string = rtrim($fields_string, '&');
+if (!isset($return['error'])) {
+ //open connection
+ $ch = curl_init();
+ //set the url, number of POST vars, POST data
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_POST, count($fields));
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($ch, CURLOPT_HEADER, 0);
+ curl_setopt($ch, CURLOPT_TIMEOUT, 30);
+ //execute post
+ $pageHTML = curl_exec($ch);
+ if (curl_errno($ch)) $return["error"][] = "Network error " . curl_errno($ch) . " " . curl_error($ch) . " " . $url . $fields_string;
+ //close connection
+ curl_close($ch);
+}
+if (!isset($return['error'])) {
+ include_once ('simple_html_dom.php');
+ $page = str_get_html($pageHTML);
+ $pageAlerts = $page->find(".smartCardAlert");
+ if (sizeof($pageAlerts) > 0) {
+ $return['error'][] = $pageAlerts[0]->plaintext;
+ }
+ if (!isset($return['error'])) {
+ $tableNum = 0;
+ $tableName = Array(
+ 1 => "myway_carddetails",
+ 2 => "myway_transactions"
+ );
+ foreach ($page->find("table") as $table) {
+ $tableNum++;
+ $tableColumns = Array();
+ $tableColumnNum = 0;
+ foreach ($table->find("th") as $th) {
+ $tableColumns[$tableColumnNum] = cleanString($th->plaintext);
+ $tableColumnNum++;
+ }
+ $tableRowNum = 0;
+ foreach ($table->find("tr") as $tr) {
+ $tableColumnNum = 0;
+ foreach ($tr->find("td") as $td) {
+ if ($tableNum == 1) $return[$tableName[$tableNum]][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext);
+ else $return[$tableName[$tableNum]][$tableRowNum][$tableColumns[$tableColumnNum]] = cleanString($td->plaintext);
+ $tableColumnNum++;
+ }
+ $tableRowNum++;
+ }
+ }
+ }
+}
+if (sizeof($return) == 0) {
+$return['error'][] = "No data extracted from MyWay website - API may be out of date";
+}
+
+header('Content-Type: text/javascript; charset=utf8');
+// header('Access-Control-Allow-Origin: http://bus.lambdacomplex.org/');
+header('Access-Control-Max-Age: 3628800');
+header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
+if (isset($_GET['callback'])) {
+ $json = '(' . json_encode($return) . ');'; //must wrap in parens and end with semicolon
+ print_r($_GET['callback'] . $json); //callback is prepended for json-p
+
+}
+else echo json_encode($return);
+?>
+
--- /dev/null
+++ b/mywaybalance.php
@@ -1,1 +1,63 @@
-
+<?php
+include ('common.inc.php');
+include_header("MyWay Balance", "mywayBalance");
+$return = Array();
+function printBalance($cardNumber, $date, $pwrd)
+{
+ global $return;
+ $return = json_decode(getPage(curPageURL() . "/myway_api.json.php?card_number=$cardNumber&DOBday={$date[0]}&DOBmonth={$date[1]}&DOByear={$date[2]}&secret_answer=$pwrd"), true);
+
+ if (isset($return['error'])) {
+ echo "<font color=red>" . var_dump($return['error']) . "</font>";
+ } else {
+ echo "<h2>Balance: " . $return['myway_carddetails']['Card Balance'] . "</h2>";
+ echo '<ul data-role="listview" data-inset="true"><li data-role="list-divider"> Recent Transactions </li>';
+ foreach ($return['myway_transactions'] as $transaction) {
+ echo "<li><b>" . $transaction["Date / Time"] . "</b>";
+ echo "<br><small>" . $transaction["TX Reference No / Type"]. "</small>";
+ echo '<p class="ui-li-aside">'.$transaction["TX Amount"].'</p>';
+ echo "</li>";
+ }
+ echo "</ul>";
+ }
+}
+if (isset($_REQUEST['card_number']) && isset($_REQUEST['date']) && isset($_REQUEST['secret_answer'])) {
+ $cardNumber = $_REQUEST['card_number'];
+ $date = explode("/", $_REQUEST['date']);
+ $pwrd = $_REQUEST['secret_answer'];
+ if ($_REQUEST['remember'] == true) {
+ $_COOKIE['card_number'] = $cardNumber;
+ $_COOKIE['date'] = $date;
+ $_COOKIE['secret_answer'] = $pwrd;
+ }
+ printBalance($cardNumber, $date, $pwrd);
+}
+else if (isset($_COOKIE['card_number']) && isset($_COOKIE['date']) && isset($_COOKIE['secret_answer'])) {
+ $cardNumber = $_COOKIE['card_number'];
+ $date = explode("/", $_COOKIE['date']);
+ $pwrd = $_COOKIE['secret_answer'];
+ printBalance($cardNumber, $date, $pwrd);
+}
+else {
+ $date = (isset($_REQUEST['date']) ? filter_var($_REQUEST['date'], FILTER_SANITIZE_STRING) : date("m/d/Y"));
+ echo '<form action="" method="post">
+ <div data-role="fieldcontain">
+ <label for="card_number">Card number</label>
+ <input type="text" name="card_number" id="card_number" value="' . $card_number . '" />
+ </div>
+ <div data-role="fieldcontain">
+ <label for="date"> Date of birth </label>
+ <input type="text" name="date" id="date" value="' . $date . '" />
+ </div>
+ <div data-role="fieldcontain">
+ <label for="secret_answer"> Secret question answer </label>
+ <input type="text" name="secret_answer" id="secret_answer" value="' . $secret_answer . '" />
+ </div>
+ <div data-role="fieldcontain">
+ <label for="remember"> Remember these details? </label>
+ <input type="checkbox" name="remember" id="remember" checked="yes" />
+ </div>
+ <input type="submit" value="Go!"></form>';
+}
+include_footer();
+?>
--- a/routeList.php
+++ b/routeList.php
@@ -1,7 +1,8 @@
<?php
include ('common.inc.php');
-include_header("Routes", "routeList");
-echo '
+function navbar()
+{
+ echo '
<div data-role="navbar">
<ul>
<li><a href="routeList.php">By Final Destination...</a></li>
@@ -11,16 +12,55 @@
</ul>
</div>
';
-echo ' <ul data-role="listview" data-inset="true">';
-$url = $APIurl . "/json/routes";
-$contents = json_decode(getPage($url));
-function printRoutes($routes)
-{
+}
+if ($_REQUEST['bysuburb']) {
+ include_header("Routes by Suburb", "routeList");
+ navbar();
+ echo ' <ul data-role="listview" data-filter="true" data-inset="true" >';
+ foreach ($suburbs as $suburb) {
+ if (!isset($_REQUEST['firstLetter'])) {
+ foreach (range('A', 'Z') as $letter) {
+ echo "<li><a href=\"routeList.php?firstLetter=$letter&bysuburb=yes\">$letter...</a></li>\n";
+ }
+ }
+ else if (startsWith($suburb, $_REQUEST['firstLetter'])) {
+ echo '<li><a href="routeList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>';
+ }
+ }
+ echo '</ul>';
+}
+else if ($_REQUEST['nearby'] || $_REQUEST['suburb']) {
+ if ($_REQUEST['suburb']) {
+ $suburb = filter_var($_REQUEST['suburb'], FILTER_SANITIZE_STRING);
+ $url = $APIurl . "/json/stopzonesearch?q=" . $suburb;
+ include_header("Routes by Suburb", "routeList");
+ }
+ if ($_REQUEST['nearby']) {
+ $url = $APIurl . "/json/neareststops?lat={$_SESSION['lat']}&lon={$_SESSION['lon']}&limit=15";
+ include_header("Routes Nearby", "routeList");
+ }
+ $stops = json_decode(getPage($url));
+ $routes = Array();
+ foreach ($stops as $stop) {
+ $url = $APIurl . "/json/stoproutes?stop=" . $stop[0];
+ $stoproutes = json_decode(getPage($url));
+ foreach ($stoproutes as $route) {
+ if (!isset($routes[$route[0]])) $routes[$route[0]] = $route;
+ }
+ }
+ navbar();
+ echo ' <ul data-role="listview" data-filter="true" data-inset="true" >';
+ sksort($routes, 1, true);
foreach ($routes as $row) {
- echo '<li>' . $row[1] . ' <a href="trip.php?routeid=' . $row[0] . '">' . $row[2] . " (" . ucwords($row[3]) . ")</a></li>\n";
+ echo '<li>' . $row[1] . ' <a href="trip.php?routeid=' . $row[0] . '">' . $row[2] . " (" . ucwords($row[4]) . ")</a></li>\n";
}
}
-if ($_REQUEST['bynumber']) {
+else if ($_REQUEST['bynumber']) {
+ include_header("Routes by Number", "routeList");
+ navbar();
+ echo ' <ul data-role="listview" data-inset="true">';
+ $url = $APIurl . "/json/routes";
+ $contents = json_decode(getPage($url));
$routeSeries = Array();
$seriesRange = Array();
foreach ($contents as $key => $row) {
@@ -54,11 +94,19 @@
echo '<a name="' . $series . '"></a>';
if ($series <= 9) echo '<li>' . $series . "<ul>\n";
else echo "<li>{$seriesRange[$series]['min']}-{$seriesRange[$series]['max']}<ul>\n";
- printRoutes($routes);
+ foreach ($routes as $row) {
+ echo '<li>' . $row[1] . ' <a href="trip.php?routeid=' . $row[0] . '">' . $row[2] . " (" . ucwords($row[3]) . ")</a></li>\n";
+ }
echo "</ul></li>\n";
}
}
else {
+ include_header("Routes by Destination", "routeList");
+ navbar();
+ echo ' <ul data-role="listview" data-inset="true">';
+ $url = $APIurl . "/json/routes";
+ $contents = json_decode(getPage($url));
+ // by destination!
foreach ($contents as $key => $row) {
$routeDestinations[$row[2]][] = $row;
}
@@ -73,7 +121,9 @@
foreach ($routeDestinations as $destination => $routes) {
echo '<a name="' . $destination . '"></a>';
echo '<li>' . $destination . "... <ul>\n";
- printRoutes($routes);
+ foreach ($routes as $row) {
+ echo '<li>' . $row[1] . ' <a href="trip.php?routeid=' . $row[0] . '">' . $row[2] . " (" . ucwords($row[3]) . ")</a></li>\n";
+ }
echo "</ul></li>\n";
}
}
--- a/schedule_viewer.py
+++ b/schedule_viewer.py
@@ -282,6 +282,23 @@
result.sort(key = lambda x: x[1:3])
return result
+ def handle_json_GET_routesearch(self, params):
+ """Return a list of routes with matching short name."""
+ schedule = self.server.schedule
+ routeshortname = params.get('routeshortname', None)
+ result = []
+ for r in schedule.GetRouteList():
+ if r.route_short_name == routeshortname:
+ servicep = None
+ for t in schedule.GetTripList():
+ if t.route_id == r.route_id:
+ servicep = t.service_period
+ break
+ result.append( (r.route_id, r.route_short_name, r.route_long_name, servicep.service_id) )
+ result.sort(key = lambda x: x[1:3])
+ return result
+
+
def handle_json_GET_routerow(self, params):
schedule = self.server.schedule
route = schedule.GetRoute(params.get('route', None))
@@ -349,14 +366,56 @@
points.append((stop.stop_lat, stop.stop_lon))
return points
+#
+# GeoPo Encode in Python
+# @author : Shintaro Inagaki
+# @param location (Dictionary) [lat (Float), lng (Float), scale(Int)]
+# @return geopo (String)
+#
+
def handle_json_GET_neareststops(self, params):
"""Return a list of the nearest 'limit' stops to 'lat', 'lon'"""
schedule = self.server.schedule
lat = float(params.get('lat'))
lon = float(params.get('lon'))
- limit = int(params.get('limit'))
- stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)
- return [StopToTuple(s) for s in stops]
+ limit = int(params.get('limit',5))
+ scale = int(params.get('scale',5)) # 5 = neighbourhood ~ 1km, 4= town 5 by 7km
+ stops = []
+
+ # 64characters (number + big and small letter + hyphen + underscore)
+ chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
+
+ geopo = ""
+
+ # Change a degree measure to a decimal number
+ lat = (lat + 90.0) / 180 * 8 ** 10 # 90.0 is forced FLOAT type when lat is INT
+ lon = (lon + 180.0) / 360 * 8 ** 10 # 180.0 is same
+
+ # Compute a GeoPo code from head and concatenate
+ for i in range(scale):
+ order = int(lat / (8 ** (9 - i)) % 8) + int(lon / (8 ** (9 - i)) % 8) * 8
+ geopo = geopo + chars[order]
+
+
+ for s in schedule.GetStopList():
+ if s.stop_code.find(geopo) != -1:
+ stops.append(s)
+
+ if scale == 5:
+ print stops
+ return [StopToTuple(s) for s in stops]
+ else:
+ dist_stop_list = []
+ for s in stops:
+ # TODO: Use util.ApproximateDistanceBetweenStops?
+ dist = (s.stop_lat - lat)**2 + (s.stop_lon - lon)**2
+ if len(dist_stop_list) < limit:
+ bisect.insort(dist_stop_list, (dist, s))
+ elif dist < dist_stop_list[-1][0]:
+ bisect.insort(dist_stop_list, (dist, s))
+ dist_stop_list.pop() # Remove stop with greatest distance
+ print dist_stop_list
+ return [StopToTuple(s) for dist, s in dist_stop_list]
def handle_json_GET_boundboxstops(self, params):
"""Return a list of up to 'limit' stops within bounding box with 'n','e'
@@ -435,8 +494,8 @@
result = {}
for trip in trips:
route = schedule.GetRoute(trip.route_id)
- if not trip.route_short_name+route.route_long_name in result:
- result[trip.route_short_name+route.route_long_name] = (route.route_id, route.route_short_name, route.route_long_name, trip.trip_id)
+ if not route.route_short_name+route.route_long_name+trip.service_id in result:
+ result[route.route_short_name+route.route_long_name+trip.service_id] = (route.route_id, route.route_short_name, route.route_long_name, trip.trip_id, trip.service_id)
return result
def handle_json_GET_stopalltrips(self, params):
@@ -467,6 +526,8 @@
if service_period == None or trip.service_id == service_period:
result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
return result
+
+
def handle_json_GET_stoptrips(self, params):
"""Given a stop_id and time in seconds since midnight return the next
@@ -476,7 +537,7 @@
requested_time = int(params.get('time', 0))
limit = int(params.get('limit', 15))
service_period = params.get('service_period', None)
- time_range = params.get('time_range', 24*60*60)
+ time_range = int(params.get('time_range', 24*60*60))
filtered_time_trips = []
--- /dev/null
+++ b/simple_html_dom.php
@@ -1,1 +1,975 @@
-
+<?php
+/*******************************************************************************
+Version: 1.11 ($Rev: 175 $)
+Website: http://sourceforge.net/projects/simplehtmldom/
+Author: S.C. Chen <me578022@gmail.com>
+Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
+Contributions by:
+ Yousuke Kumakura (Attribute filters)
+ Vadim Voituk (Negative indexes supports of "find" method)
+ Antcs (Constructor with automatically load contents either text or file/url)
+Licensed under The MIT License
+Redistributions of files must retain the above copyright notice.
+*******************************************************************************/
+
+define('HDOM_TYPE_ELEMENT', 1);
+define('HDOM_TYPE_COMMENT', 2);
+define('HDOM_TYPE_TEXT', 3);
+define('HDOM_TYPE_ENDTAG', 4);
+define('HDOM_TYPE_ROOT', 5);
+define('HDOM_TYPE_UNKNOWN', 6);
+define('HDOM_QUOTE_DOUBLE', 0);
+define('HDOM_QUOTE_SINGLE', 1);
+define('HDOM_QUOTE_NO', 3);
+define('HDOM_INFO_BEGIN', 0);
+define('HDOM_INFO_END', 1);
+define('HDOM_INFO_QUOTE', 2);
+define('HDOM_INFO_SPACE', 3);
+define('HDOM_INFO_TEXT', 4);
+define('HDOM_INFO_INNER', 5);
+define('HDOM_INFO_OUTER', 6);
+define('HDOM_INFO_ENDSPACE',7);
+
+// helper functions
+// -----------------------------------------------------------------------------
+// get html dom form file
+function file_get_html() {
+ $dom = new simple_html_dom;
+ $args = func_get_args();
+ $dom->load(call_user_func_array('file_get_contents', $args), true);
+ return $dom;
+}
+
+// get html dom form string
+function str_get_html($str, $lowercase=true) {
+ $dom = new simple_html_dom;
+ $dom->load($str, $lowercase);
+ return $dom;
+}
+
+// dump html dom tree
+function dump_html_tree($node, $show_attr=true, $deep=0) {
+ $lead = str_repeat(' ', $deep);
+ echo $lead.$node->tag;
+ if ($show_attr && count($node->attr)>0) {
+ echo '(';
+ foreach($node->attr as $k=>$v)
+ echo "[$k]=>\"".$node->$k.'", ';
+ echo ')';
+ }
+ echo "\n";
+
+ foreach($node->nodes as $c)
+ dump_html_tree($c, $show_attr, $deep+1);
+}
+
+// get dom form file (deprecated)
+function file_get_dom() {
+ $dom = new simple_html_dom;
+ $args = func_get_args();
+ $dom->load(call_user_func_array('file_get_contents', $args), true);
+ return $dom;
+}
+
+// get dom form string (deprecated)
+function str_get_dom($str, $lowercase=true) {
+ $dom = new simple_html_dom;
+ $dom->load($str, $lowercase);
+ return $dom;
+}
+
+// simple html dom node
+// -----------------------------------------------------------------------------
+class simple_html_dom_node {
+ public $nodetype = HDOM_TYPE_TEXT;
+ public $tag = 'text';
+ public $attr = array();
+ public $children = array();
+ public $nodes = array();
+ public $parent = null;
+ public $_ = array();
+ private $dom = null;
+
+ function __construct($dom) {
+ $this->dom = $dom;
+ $dom->nodes[] = $this;
+ }
+
+ function __destruct() {
+ $this->clear();
+ }
+
+ function __toString() {
+ return $this->outertext();
+ }
+
+ // clean up memory due to php5 circular references memory leak...
+ function clear() {
+ $this->dom = null;
+ $this->nodes = null;
+ $this->parent = null;
+ $this->children = null;
+ }
+
+ // dump node's tree
+ function dump($show_attr=true) {
+ dump_html_tree($this, $show_attr);
+ }
+
+ // returns the parent of node
+ function parent() {
+ return $this->parent;
+ }
+
+ // returns children of node
+ function children($idx=-1) {
+ if ($idx===-1) return $this->children;
+ if (isset($this->children[$idx])) return $this->children[$idx];
+ return null;
+ }
+
+ // returns the first child of node
+ function first_child() {
+ if (count($this->children)>0) return $this->children[0];
+ return null;
+ }
+
+ // returns the last child of node
+ function last_child() {
+ if (($count=count($this->children))>0) return $this->children[$count-1];
+ return null;
+ }
+
+ // returns the next sibling of node
+ function next_sibling() {
+ if ($this->parent===null) return null;
+ $idx = 0;
+ $count = count($this->parent->children);
+ while ($idx<$count && $this!==$this->parent->children[$idx])
+ ++$idx;
+ if (++$idx>=$count) return null;
+ return $this->parent->children[$idx];
+ }
+
+ // returns the previous sibling of node
+ function prev_sibling() {
+ if ($this->parent===null) return null;
+ $idx = 0;
+ $count = count($this->parent->children);
+ while ($idx<$count && $this!==$this->parent->children[$idx])
+ ++$idx;
+ if (--$idx<0) return null;
+ return $this->parent->children[$idx];
+ }
+
+ // get dom node's inner html
+ function innertext() {
+ if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
+ if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
+
+ $ret = '';
+ foreach($this->nodes as $n)
+ $ret .= $n->outertext();
+ return $ret;
+ }
+
+ // get dom node's outer text (with tag)
+ function outertext() {
+ if ($this->tag==='root') return $this->innertext();
+
+ // trigger callback
+ if ($this->dom->callback!==null)
+ call_user_func_array($this->dom->callback, array($this));
+
+ if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
+ if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
+
+ // render begin tag
+ $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
+
+ // render inner text
+ if (isset($this->_[HDOM_INFO_INNER]))
+ $ret .= $this->_[HDOM_INFO_INNER];
+ else {
+ foreach($this->nodes as $n)
+ $ret .= $n->outertext();
+ }
+
+ // render end tag
+ if(isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
+ $ret .= '</'.$this->tag.'>';
+ return $ret;
+ }
+
+ // get dom node's plain text
+ function text() {
+ if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
+ switch ($this->nodetype) {
+ case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
+ case HDOM_TYPE_COMMENT: return '';
+ case HDOM_TYPE_UNKNOWN: return '';
+ }
+ if (strcasecmp($this->tag, 'script')===0) return '';
+ if (strcasecmp($this->tag, 'style')===0) return '';
+
+ $ret = '';
+ foreach($this->nodes as $n)
+ $ret .= $n->text();
+ return $ret;
+ }
+
+ function xmltext() {
+ $ret = $this->innertext();
+ $ret = str_ireplace('<![CDATA[', '', $ret);
+ $ret = str_replace(']]>', '', $ret);
+ return $ret;
+ }
+
+ // build node's text with tag
+ function makeup() {
+ // text, comment, unknown
+ if (isset($thi