diff options
Diffstat (limited to 'includes')
-rw-r--r-- | includes/datas.php | 1 | ||||
-rw-r--r-- | includes/db.inc.php | 11 | ||||
-rw-r--r-- | includes/header.php | 67 | ||||
-rw-r--r-- | includes/mapoftheday.php | 1 | ||||
-rw-r--r-- | includes/maps.php | 743 | ||||
-rw-r--r-- | includes/openid.php | 740 | ||||
-rw-r--r-- | includes/pathing.php | 108 |
7 files changed, 1671 insertions, 0 deletions
diff --git a/includes/datas.php b/includes/datas.php new file mode 100644 index 0000000..0d3d0c5 --- /dev/null +++ b/includes/datas.php @@ -0,0 +1 @@ +<?PHP
// For interaction with the SQL database.
//
include_once('db.inc.php');
//Select Stats/Scores.
function topScores($mapid, $top = 5) {
$sql = "
SELECT
timediff(solutions.dateModified, TIMESTAMP(CURDATE())) as diff,
users.displayName as display,
solutions.moves as m,
users.ID as ID
FROM
`users`
JOIN `solutions`
ON users.ID = solutions.userID
WHERE solutions.mapID = '$mapid'
ORDER BY solutions.moves DESC, solutions.dateModified ASC
LIMIT $top
";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
$output .= "<table style='border:1px solid #FFF'>";
$output .= "<tr>";
$output .= "<th style='border:1px solid #ccc'>Rank</th>";
$output .= "<th style='border:1px solid #ccc'>Name</th>";
$output .= "<th style='border:1px solid #ccc'>Moves</th>";
$output .= "<th style='border:1px solid #ccc'>Time taken</th>";
$output .= "</tr>";
while (list($diff, $display, $moves, $userID) = mysql_fetch_row($result)) {
$i++;
if ($_SESSION['userID'] == $userID)
$output .= "<tr style='background-color: #338899;'>";
else
$output .= "<tr>";
$output .= "<td>$i</td>";
$output .= "<td><span title='UserID: $userID'>$display</span></td>";
$output .= "<td>$moves</td>";
$output .= "<td>$diff</td>";
//$output .= "<b>$i. <span title='UserID: $userID'>$display</span> with $moves moves. In $diff<br /></b>";
$output .= "</tr>";
}
$output .= "</table>";
}
return $output;
}
?>
\ No newline at end of file diff --git a/includes/db.inc.php b/includes/db.inc.php new file mode 100644 index 0000000..8e9bdfb --- /dev/null +++ b/includes/db.inc.php @@ -0,0 +1,11 @@ +<?php
+
+global $mysqlid;
+$db_host = "db2838.perfora.net";
+$db_user = "dbo358894438";
+$db_name = "db358894438";
+$db_pass = "MAZE4US";
+$mysqlid = @mysql_connect($db_host,$db_user, $db_pass) or die("Cannot connect to database.");
+@mysql_select_db($db_name, $mysqlid) or die("Invalid database.");
+
+?>
\ No newline at end of file diff --git a/includes/header.php b/includes/header.php new file mode 100644 index 0000000..53c1a82 --- /dev/null +++ b/includes/header.php @@ -0,0 +1,67 @@ +<?PHP
+
+function htmlHeader() {
+?>
+<!DOCTYPE html>
+<html xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
+ <link href="css/mapstyle.css" rel="stylesheet" type="text/css" />
+ <link href="css/pagestyle.css" rel="stylesheet" type="text/css" />
+ <link href="css/statsstyle.css" rel="stylesheet" type="text/css" />
+ <title>Snapems.com Mazegame</title>
+
+ <script src="js/ajax.js" type="text/javascript"></script>
+ <script src="js/mapspecs.js" type="text/javascript"></script>
+
+<script type="text/javascript">
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-371072-3']);
+ _gaq.push(['_trackPageview']);
+
+ (function() {
+ var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+ })();
+</script>
+</head>
+<?
+}
+
+function htmlfooter() {
+
+}
+
+function topbar($links) {
+ echo '<div class="topbar">';
+
+ $page = $_GET[page];
+ if ($page == '')
+ $page = 'home';
+ $first = true;
+ foreach ($links as $key => $value) {
+ if ($first)
+ $first = false;
+ else
+ echo ' | ';
+ if ($page == $key)
+ echo "<b><a href='?page=$key'>$value</a></b>";
+ else
+ echo "<a href='?page=$key'>$value</a>";
+ }
+
+ echo "\t<div class='lfloat'>";
+ if ($_SESSION['accepted'] == 1) {
+ echo "Logged in as <a href='?page=cp' title='change name'>$_SESSION[displayName]</a>.\n";
+ echo "<a href='?page=logout'>Logout</a>";
+ if ($_SESSION['displayName'] == 'noname')
+ echo "<a href='?page=cp' title='change name'>Update your name</a>";
+ } else
+ echo "<a href='?page=login'>Sign in using Google</a>";
+
+ echo "\t</div>";
+ echo "</div>";
+}
+
+?>
diff --git a/includes/mapoftheday.php b/includes/mapoftheday.php new file mode 100644 index 0000000..cd646cb --- /dev/null +++ b/includes/mapoftheday.php @@ -0,0 +1 @@ +<?PHP
include_once('maps.php');
include_once('db.inc.php');
//Select from current day.
function getMapOfTheDay() {
$sql = "
select `ID`, `code` from `maps`
WHERE (
DAY(dateCreated) = DAY(NOW())
AND
MONTH(dateCreated) = MONTH(NOW())
AND
YEAR(dateCreated) = YEAR(NOW())
)
";
$result = mysql_query($sql);
//No map for today?
if (mysql_num_rows($result) == 0) {
// If you want to modify the maps created! This is the line
$map = GenerateMap(rand(13, 18), rand(10, 14), rand(6, 9));
$code = GenerateMapCode($map);
$sql = "INSERT INTO `maps` (`code`)
VALUES ('$code')";
mysql_query($sql);
$r['code'] = $code;
$r['map'] = $map;
$r['id'] = mysql_insert_id();
return $r;
}
$r['code'] = mysql_result($result, 0, 'code');
$r['map'] = GenerateMapByCode($r['code']);
$r['id'] = mysql_result($result, 0, 'ID');
return $r;
}
function mapOfTheDay($type = 1) {
$sql = "
select maps.ID, maps.code
FROM `mapOfTheDay`, `maps`
WHERE `mapDate` = CURDATE() AND
`mapType` = $type AND
mapID = maps.ID
";
$result = mysql_query($sql);
//No map for today?
if (mysql_num_rows($result) == 0) {
// If you want to modify the maps created! This is the line
//GenerateMap($rows, $cols, $rockchance, $numBlocks = -1, $cp = -1, $tp = -1) {
switch ($type) {
case 1: //Easy
$map = GenerateMap(13, 7, 12, rand(7,10), rand(0, 2), 0);
break;
case 2: //Normal
$map = GenerateMap(15, 9, 7, rand(11,13), rand(1,2) + rand(0,1), rand(0,1));
break;
case 3: //Hard
$map = GenerateMap(19, 9, rand(7, 9), rand(13,16), rand(2,5), rand(1,2));
break;
case 4: //Full random map
//Get the current day as int.
$numday = date('w');
$numday = intval($numday);
switch ($numday) {
case 0: //Sunday
//Thirty
$map = GenerateMap(
18, 14, 20 , //width, height, rocks
weight(30) , //Walls
weight(1) , //Checkpoints
weight(1) //Teleports
);
break;
case 1: //Monday
//Simple
$map = GenerateMap(
18, 9, 7 , //width, height, rocks
weight(15,16,17) , //Walls
weight(0) , //Checkpoints
weight(0) //Teleports
);
break;
case 2: //Tuesday
//ABC's
$map = GenerateMap(
19, 11, 12 , //width, height, rocks
weight(20,21,22,22,23) , //Walls
weight(3) , //Checkpoints
weight(0) //Teleports
);
break;
case 3: //Wednesday
//Tele Madness
$map = GenerateMap(
17, 12, 10 , //width, height, rocks
weight(17,18) , //Walls
weight(1) , //Checkpoints
weight(5) //Teleports
);
break;
case 4: //Thursday
//Rocky Maze
$map = GenerateMap(
19, 15, 5 , //width, height, rocks
weight(16,17,18) , //Walls
weight(1,2,2,2,3,3) , //Checkpoints
weight(0) //Teleports
);
break;
case 5: //Friday
//Side to Side
$map = GenerateMap(
26, 6, 12 , //width, height, rocks
weight(17,18,19) , //Walls
weight(2,2,2,3,3) , //Checkpoints
weight(3,3,3,4) //Teleports
);
break;
case 6: //Saturday
//ABC's
$map = GenerateMap(
19, 11, 12 , //width, height, rocks
weight(20,21,22,22,23) , //Walls
weight(3) , //Checkpoints
weight(0) //Teleports
);
break;
}
break;
default:
$map = GenerateMap(rand(13, 18), rand(10, 14), rand(6, 9));
break;
}
$code = GenerateMapCode($map);
$sql = "INSERT INTO `maps` (`code`)
VALUES ('$code')";
mysql_query($sql);
$mapID = mysql_insert_id();
$r['code'] = $code;
$r['map'] = $map;
$r['id'] = $mapID;
$sql = "INSERT INTO `mapOfTheDay` (`mapID`, `mapType`, `mapDate`)
VALUES ('$mapID', '$type', CURDATE()) ";
mysql_query($sql);
return $r;
}
$r['code'] = mysql_result($result, 0, 'code');
$r['map'] = GenerateMapByCode($r['code']);
$r['id'] = mysql_result($result, 0, 'ID');
return $r;
}
// RMA # CT1160811
// 97686
//Select from yesterday
function getYesterdaysMap() {
$sql = "
select `ID`, `code` from `maps`
WHERE (
DAY(dateCreated) = DAY(NOW()) - 1
AND
MONTH(dateCreated) = MONTH(NOW())
AND
YEAR(dateCreated) = YEAR(NOW())
)
";
$result = mysql_query($sql);
//No map for today?
if (mysql_num_rows($result) == 0) {
return -1;
}
$r['code'] = mysql_result($result, 0, 'code');
$r['id'] = mysql_result($result, 0, 'ID');
return $r;
}
?>
\ No newline at end of file diff --git a/includes/maps.php b/includes/maps.php new file mode 100644 index 0000000..acb4c6c --- /dev/null +++ b/includes/maps.php @@ -0,0 +1,743 @@ +<?PHP
+function DisplayMap($mapMatrix, $idprefix = 1, $example = false, $speed = NULL) {
+ //Iterate through $mapMatrix and generate the html
+ $maptable = ""; //The string to return to the database.
+ $index = 0; //The current number of tiles from the last tile saved.
+
+
+ if ($speed == NULL) {
+ if ($example) {
+ $speed = 1;
+ } else {
+ $speed = 2;
+ }
+ }
+
+ for($i = 1; $i < count($mapMatrix); $i++)
+ {
+ $maptable .= "<tr>";
+ for($j = 0; $j < count($mapMatrix[$i]); $j++)
+ {
+ //==
+ $index++;
+
+ $handle = "$idprefix,$i,$j";
+ switch($mapMatrix[$i][$j])
+ {
+ case 's': $maptable .= "<td class='grid_td_start' id='$handle' ></td>"; break;
+ case 'f': $maptable .= "<td class='grid_td_finish' id='$handle' ></td>"; break;
+
+ //TP1
+ case 't': $maptable .= "<td title='Teleport 1 in' class='grid_td_tp1_in' id='$handle' ></td>"; break;
+ case 'u': $maptable .= "<td title='Teleport 1 out' class='grid_td_tp1_out' id='$handle' ></td>"; break;
+ //TP2
+ case 'm': $maptable .= "<td title='Teleport 2 in' class='grid_td_tp2_in' id='$handle' ></td>"; break;
+ case 'n': $maptable .= "<td title='Teleport 2 out'class='grid_td_tp2_out' id='$handle' ></td>"; break;
+ //TP3
+ case 'g': $maptable .= "<td title='Teleport 3 in' class='grid_td_tp3_in' id='$handle' ></td>"; break;
+ case 'h': $maptable .= "<td title='Teleport 3 out'class='grid_td_tp3_out' id='$handle' ></td>"; break;
+ //TP4
+ case 'i': $maptable .= "<td title='Teleport 4 in' class='grid_td_tp4_in' id='$handle' ></td>"; break;
+ case 'j': $maptable .= "<td title='Teleport 4 out'class='grid_td_tp4_out' id='$handle' ></td>"; break;
+ //TP5
+ case 'k': $maptable .= "<td title='Teleport 5 in' class='grid_td_tp5_in' id='$handle' ></td>"; break;
+ case 'l': $maptable .= "<td title='Teleport 5 out'class='grid_td_tp5_out' id='$handle' ></td>"; break;
+
+ case 'a': $maptable .= "<td class='grid_td_cpa' id='$handle' ></td>"; break;
+ case 'b': $maptable .= "<td class='grid_td_cpb' id='$handle' ></td>"; break;
+ case 'c': $maptable .= "<td class='grid_td_cpc' id='$handle' ></td>"; break;
+ case 'd': $maptable .= "<td class='grid_td_cpd' id='$handle' ></td>"; break;
+ case 'e': $maptable .= "<td class='grid_td_cpe' id='$handle' ></td>"; break;
+
+ case 'r': $maptable .= "<td class='grid_td_rocks' id='$handle' ></td>"; break; //rock
+ case 'w': $maptable .= "<td class='grid_td_walls' id='$handle' name='true' onClick='grid_click(this)' ></td>"; break; //wall
+ //default: $maptable .= "<td class='grid_td' id='$handle' onClick='grid_click(this)' >".$index."</td>";
+ default: $maptable .= "<td title='Position: $i,$j' class='grid_td' id='$handle' onClick='grid_click(this)' ></td>";
+ //default: $maptable .= "<td class='grid_td' id='$handle' onClick='grid_click(this)' >".$mapMatrix[$i][$j]."</td>";
+ }
+ }
+ $maptable .= "</tr>";
+ }
+ //Prepare mapdata.
+ $mapdata['height'] = $mapMatrix[0][0];
+ $mapdata['width'] = $mapMatrix[0][1];
+ $mapdata['points'] = $mapMatrix[0][2];
+ $mapdata['rocks'] = $mapMatrix[0][3];
+ $mapdata['walls'] = $mapMatrix[0][4];
+ $mapdata['teleports'] = $mapMatrix[0][5];
+ $mapdata['example'] = $example;
+ $mapdata['mapid'] = $idprefix;
+
+ $path = routePath($mapMatrix, '');
+ $mapdata['code'] = GenerateMapCode($mapMatrix);
+
+ $width = (($j * 35) + 2).'px';
+ //$width = (($j * 23) + 2).'px';
+ $i -= 1;
+ $height = (($i * 35)).'px';
+ //$height = (($i * 22) + 2).'px';
+
+ $jsonmap = json_encode($mapdata);
+ $mapdatadiv .= "<div id='$idprefix,mapdata' style='visibility:hidden;display:none'>";
+ $mapdatadiv .= $jsonmap;
+ $mapdatadiv .= '</div>';
+
+ $maptable = "<table style='width:$width;height:$height;' class='grid_table'>
+ $maptable
+ </table>";
+
+
+ $prefSpeed = $_COOKIE['pref_speed'];
+ $speedOption['Slow'] = 1;
+ $speedOption['Med'] = 2;
+ $speedOption['Fast'] = 3;
+ $speedOption['Ultra'] = 4;
+ if (!in_array($prefSpeed, $speedOption))
+ $prefSpeed = '2';
+
+ foreach ($speedOption as $key => $value) {
+ $rOption .= "<option value='$value'";
+ if ($prefSpeed == $value)
+ $rOption .= " selected='selected'";
+ $rOption .= ">$key</option>\n";
+ }
+
+ if ($_COOKIE['pref_mute'] == "true") {
+ $mutebutton = "<label><input onclick='savePref(\"mute\", this.checked)' type='checkbox' id='$idprefix,mute' checked='checked' />Mute</label>";
+ } else {
+ $mutebutton = "<label><input onclick='savePref(\"mute\", this.checked)' type='checkbox' id='$idprefix,mute' />Mute</label>";
+ }
+
+
+ if ($example) {
+ $output = $maptable;
+ $output .= "<input id='$idprefix,btn' type='button' onclick='doSend($idprefix)' value='Test' />";
+ $output .= "
+ <div style='display:none;'>
+ <input type='checkbox' id='$idprefix,mute' checked=true />
+ <select id='$idprefix,speed'>
+ $rOption
+ </select>
+ </div>
+ ";
+ $output .= $mapdatadiv;
+ $output = "<div style='width:$width;height:$height;'>
+ $output
+ </div>";
+ return $output;
+ }
+ //$date = date("m-d-y");
+
+ $output = "
+ <div id='$idprefix,outer' class='grid_outer' style='width:".($width+2)."px;height:".($height+50)."px;'>
+
+ <div class='grid_dsp_left dsp_49'>
+ <div id='$idprefix,dspID' title='MapID: $idprefix'>
+ MapID: $idprefix
+ </div>
+ </div>
+
+
+ <div id='$idprefix,dsptr' class='grid_dsp_right dsp_33'>
+ <span id='$idprefix,dspWalls' class='grid_dsp_data'>
+ ".$mapdata['walls']." walls
+ </span>
+ <span>
+ ( <a href='javascript:resetwalls($idprefix)'>Reset</a> )
+ </span>
+ </div>
+
+
+ $maptable
+
+ <div id='$idprefix,dspbl' class='grid_dsp_left dsp_49'>
+ <input id='$idprefix,btn' type='button' onclick='doSend($idprefix)' value='Go!' />
+ Speed:
+ <select onChange='savePref(\"speed\", this.value)' id='$idprefix,speed'>
+ $rOption
+ </select>
+ </div>
+
+ <div class='grid_dsp_mid dsp_16'>
+ $mutebutton
+ </div>
+
+ <div id='$idprefix,dspbr' class='grid_dsp_right dsp_33'>
+ <div id='$idprefix,dspCount' class='grid_dsp_data'>
+ ".$path['moves']." moves
+ </div>
+ </div>
+
+ $mapdatadiv
+ </div>
+ ";
+
+ return $output;
+}
+//Generates map
+function GenerateMap($rows, $cols, $rockchance, $numBlocks = -1, $cp = -1, $tp = -1) {
+
+ //!! Possibility of inf loop here.
+ do {
+ $randvalue = rand(1, ($rows * $cols));
+ //As long as it isn't the first, or last column.
+ //if ((($randvalue +1) % ($rows)) > 1) {
+ //As long as it isn't in the first, 2nd, last and 2nd to last column.
+ if ((($randvalue +2) % ($rows)) > 3) {
+ $unique[] = $randvalue;
+ $unique = array_unique($unique);
+ $unique = array_values($unique);
+ }
+ } while (count($unique) < 15);
+
+ if ($numBlocks == -1)
+ $numBlocks = Rand(7, (int)($rows * $cols) * .12);
+
+ if ($cp == -1)
+ $cp = rand(0, 5);
+ if ($tp == -1)
+ $tp = rand(0, 2);
+ $tp = $tp * 2; //Requires an out-teleport.
+
+ $cpnames = Array("a", "b", "c", "d", "e");
+ $tpnames = Array("t", "u", "m", "n", 'g', 'h', 'i', 'j', 'k', 'l');
+
+ $teleport = Array();
+ $checkpoint = Array();
+
+ $i = 0;
+ for($p = 0; $p < $cp; $p++) {
+ $checkpoint[$cpnames[$p]] = $unique[$i];
+ $i++;
+ }
+ for($p = 0; $p < $tp; $p++) {
+ $teleport[$tpnames[$p]] = $unique[$i];
+ $i++;
+ }
+
+ $rocks = 0; //Number of rocks in the maze.
+
+ // We need to make sure the map we construct is valid.
+ // so we throw this in a do-while.
+ do {
+ $p = -1;
+ //Begin loop to populate grid.
+ for( $y = 1; $y <= $cols; $y++) { //Number of Columns
+ for( $x = 0; $x < $rows; $x++) { //Number of Rows
+ $p++;
+ //Start and Finish squares.
+ if ($x == 0) {
+ $grid[$y][$x] = "s";
+ } elseif ($x == $rows - 1) {
+ $grid[$y][$x] = "f";
+ //Randomly Placed Rocks
+ } elseif (rand(1, $rockchance) == 2) {
+ $grid[$y][$x] = "r";
+ $rocks++;
+ //!! rock count could be off if covered by checkpoint.
+ //Just a normal square.
+ } else {
+ $grid[$y][$x] = "o";
+ }
+ //Absolutely placed points; Checkpoints.
+ foreach ($checkpoint as $key => $v) {
+ if ($v == $p) {
+ $grid[$y][$x] = $key;
+ }
+ } //Teleports too
+ foreach ($teleport as $key => $v) {
+ if ($v == $p) {
+ $grid[$y][$x] = $key;
+ }
+ }
+
+ } //Rows
+ } //Cols
+ //Fill $grid[0] with header information
+ $grid[0][0] = $rows;
+ $grid[0][1] = $cols;
+ $grid[0][2] = count($checkpoint);
+ $grid[0][3] = $rocks;
+ $grid[0][4] = $numBlocks;
+ $grid[0][5] = count($teleport);
+
+ //Confirm the map isn't broken to start-out.
+ $path = routePath($grid);
+ //Only repeat if it's blocked.
+ } while ($path['blocked'] == true);
+
+ return $grid;
+}
+
+
+//Turns a mapMatrix into a code - see GenerateMapByCode
+function GenerateMapCode($mapMatrix) {
+ //Iterate through $mapMatrix and generate the code used to save and
+ // load the map through the database.
+
+ // 0.1 Snap. (added mapsize header data)
+ // 0.2 Rex - Added #checkpoints, #rocks, #walls to header data; adjusted loops.
+
+ $code = ""; //The string to return to the database.
+ $index = 0; //The current number of tiles from the last tile saved.
+
+ // $mapMatrix[0] stores header data--dimensions, #checkpoints, #rocks, #walls
+ // $mapMatrix[1] count will always be the width.
+ $mapsize = $mapMatrix[0][0].'x'.$mapMatrix[0][1]; //Width x Height
+
+ $code = $mapsize.
+ '.c'.$mapMatrix[0][2].
+ '.r'.$mapMatrix[0][3].
+ '.w'.$mapMatrix[0][4].
+ '.t'.$mapMatrix[0][5];
+ // dimensions + # checkpoints + # rocks + # placeable walls
+
+ //echo $code."<br />";
+
+ $code .= ".:";
+
+ for( $i = 1; $i < count($mapMatrix); $i++)
+ {
+ for( $j = 0; $j < count($mapMatrix[$i]); $j++)
+ {
+ if($mapMatrix[$i][$j] != 'o')
+ {
+ //As long as the tile is NOT open, embed it in the code.
+ $code .= $index.$mapMatrix[$i][$j].'.';
+ $index = -1;
+ //==echo "<br /><b>".$index.$mapMatrix[$i][$j]."</b><br />";
+ }
+ $index += 1;
+ }
+ }
+
+ return $code;
+}
+
+//Turns a mapcode into a mapMatrix, - see GenerateMapCode
+function GenerateMapByCode($code) {
+ //Create $mapMatrix by iterating through $code (a string value).
+ //==$mapMatrix = array();
+
+
+ $tmp = explode( ":", $code);
+
+ $headers = explode( '.', $tmp[0]);
+ $splitCode = explode( '.', $tmp[1]);
+
+ //Extract header information.
+ //==$mapMatrix[0] = array();
+ $dimensions = explode( 'x', $headers[0]);
+ $mapMatrix[0][0] = $dimensions[0]; //Width
+ $mapMatrix[0][1] = $dimensions[1]; //Height
+
+ //Select the next parameters by ignoring the character label.
+ $mapMatrix[0][2] = (int)substr($headers[1], 1); //Number of Checkpoints
+ $mapMatrix[0][3] = (int)substr($headers[2], 1); //Number of Rocks
+ $mapMatrix[0][4] = (int)substr($headers[3], 1); //Number of Wall Blocks
+ $mapMatrix[0][5] = (int)substr($headers[4], 1); //Number of Teleports
+
+ //Printing out parameters for debug purposes...
+ /*
+ echo "<br />Map Parameters:<br />";
+ echo "mapMatrix[0][0]: ".$mapMatrix[0][0]."<br />";
+ echo "mapMatrix[0][1]: ".$mapMatrix[0][1]."<br />";
+ echo "mapMatrix[0][2]: ".$mapMatrix[0][2]."<br />";
+ echo "mapMatrix[0][3]: ".$mapMatrix[0][3]."<br />";
+ echo "mapMatrix[0][4]: ".$mapMatrix[0][4]."<br />";
+ echo "mapMatrix[0][5]: ".$mapMatrix[0][5]."<br />";
+ */
+ //Begin creating our mapMatrix
+ $t = -1;
+ $index = 0;
+ for( $i = 1; $i <= $mapMatrix[0][1]; $i++) { //Number of Rows
+ for( $j = 0; $j < $mapMatrix[0][0]; $j++) { //Number of Columns
+ $t++;
+ $next = substr($splitCode[$index], 0, strlen($splitCode[$index]) - 1);
+
+ if ($next == $t) {
+ $type = substr($splitCode[$index], -1, 1);
+ $mapMatrix[$i][$j] = $type;
+ $index++;
+ $t = -1;
+
+ //echo "type:".$type."<br />";
+ //echo "number:".$next."<br />";
+ //echo "original:".$splitCode[$index]."<br />";
+ } else {
+ $mapMatrix[$i][$j] = 'o'; //Empty Tile
+ }
+ //echo "Value:".$mapMatrix[$i][$j]."<br />";
+ }
+ }
+
+ //echo "mapMatrix[1][0]: ".$mapMatrix[1][0]."<br />";
+ //echo "mapMatrix[1][1]: ".$mapMatrix[1][1]."<br />";
+
+ return $mapMatrix;
+ //Snap Stops
+
+ //Iterate through the code and adjust spaces as directed.
+ /* UNREACHABLE CODE
+ $index = 0;
+ for ( $i = 4; $i < count($splitCode); $i++)
+ {
+ echo "<br />";
+
+ $index += (int)$splitCode[$i];
+ $type = $splitCode[$i][strlen($splitCode[$i])-1];
+
+ //$tile = GetTile($mapMatrix, $index);
+ echo "$x = (int)($index / ".$mapMatrix[0][0].");<br />";
+ $x = (int)($index / $mapMatrix[0][0]);
+ $y = $id % $mapMatrix[0][0];
+
+
+ echo "splitCode: ".$splitCode[$i]."<br />";
+ echo "Index: ".$index." -- ".$x.",".$y." to ".$type;
+ echo "<br />";
+
+ $mapMatrix[$x][$y] = $type;
+ }
+
+ return $mapMatrix; */
+}
+
+//Returns a mapMatrix merged with a solution/maze.
+function MergeMapSolution($mapMatrix, $solution) {
+ //echo $solution;
+ $sa = explode( '.', $solution);
+ foreach($sa as $v) {
+ if ($v == '') continue;
+ $v= explode(",", $v);
+ $i = $v[0];
+ $j = $v[1];
+
+ //Trying to place a wall - where?
+ if ($mapMatrix[$i][$j] <> 'o') return -1;
+ $mapMatrix[$i][$j] = 'w';
+
+ //Are we out of blocks?
+ //if ($mapMatrix[0][2] < 1) return -2;
+ $mapMatrix[0][4]--;
+ }
+ return $mapMatrix;
+}
+
+function seperateMapSolution($mapMatrix) {
+ for( $i = 1; $i <= $mapMatrix[0][1]; $i++) //Number of Rows
+ for( $j = 0; $j < $mapMatrix[0][0]; $j++) //Number of Columns
+ if ($mapMatrix[$i][$j] == 'w')
+ $solution .= "$i,$j.";
+ $solution = ".".$solution;
+ return $solution;
+}
+
+//This is required to identify identical solutions, or even 'close' ones.
+function formSolution($solution) {
+ $tmp = explode(".", $solution);
+ $tmp = array_filter($tmp);
+ sort($tmp);
+ $tmp = '.'.implode(".", $tmp).'.';
+ return $tmp;
+}
+
+//Returns the best solution.
+function getSolution($userID, $mapID) {
+ include_once('db.inc.php');
+ $sql = "SELECT `solution`
+ FROM `solutions`
+ WHERE `userID` = '$userID' AND
+ `mapID` = '$mapID'
+ ";
+ $result = mysql_query($sql);
+ if (mysql_num_rows($result) > 0) {
+ list($solution) = mysql_fetch_row($result);
+ return $solution;
+ }
+}
+
+function getMapCode($mapID) {
+ include_once('db.inc.php');
+ $sql = "SELECT `code`
+ FROM `maps`
+ WHERE `ID` = '$mapID'
+ ";
+ $result = mysql_query($sql);
+ if (mysql_num_rows($result) > 0) {
+ list($map) = mysql_fetch_row($result);
+ return $map;
+ }
+}
+
+function pastMap($maptype, $daysago) {
+ $sql = "
+ SELECT `mapID`
+ FROM `mapOfTheDay`
+ WHERE DATE_ADD(CURDATE(), INTERVAL -$daysago DAY) =
+ DATE_FORMAT(mapDate,'%Y-%m-%d') AND
+ `mapType` = '$maptype'
+ ";
+ //echo "<br />$sql<br />";
+ $result = mysql_query($sql) or die(mysql_error());
+ //No map for today?
+ if (mysql_num_rows($result) == 0)
+ return -1;
+
+ $r = mysql_result($result, 0, 'mapID');
+ //echo "result: $r";
+ return $r;
+}
+
+
+
+
+
+// Returns: ARRAY( blocked, path, start, end )
+function findPath($mapMatrix, $start = '0,1.', $target = 'f') {
+ $seed = explode(".", $start);
+ foreach ($seed as &$v) {
+ $v = explode(",", $v);
+ $v[2] = $v[0].','.$v[1];
+ }
+ //print_r ($seed);
+
+ $index = count($seed);
+
+ do {
+ foreach ($seed as $key => $v) {
+ //Search the squares around, to spread the seeds
+ for($i = 1; $i <= 4; $i++) {
+ $x = $v[0];
+ $y = $v[1];
+ //Create a handle on the squares around it.
+ switch($i){
+ case 1: $y--; break; //up
+ case 2: $x++; break; //right
+ case 3: $y++; break; //down
+ case 4: $x--; break; //left
+ }
+ if ($y < 1 OR $x < 0) continue 1;
+ //What's there?
+ switch($mapMatrix[$y][$x]) {
+ case $target: //Finishline!
+ //Our search is over.
+ $r['blocked'] = false;
+ $r['path'] = $seed[$key][3].$i;
+ $r['start'] = $v[2];
+ $r['end'] = "$x,$y";
+ return $r;
+ break;
+ // Teleports m t g i k
+ case "m": case "t": case "g": case "i": case "k":
+ $path = $mapMatrix[$y][$x];
+
+ case "o": //Available squares
+ //!!
+ case "s": case "f": //Start and end tiles
+
+ case "a": case "b": case "c": case "d": case "e": //Checkpoints too
+ case "u": case "n": case "h": case "j": case "l": //Teleport-out towers included!
+ //Plant Seed here
+ $seed[$index][0] = $x;
+ $seed[$index][1] = $y;
+ //Save our starting position.
+ $seed[$index][2] = $v[2];
+ //Save 'PATH'
+ $path = $i.$path;
+ $seed[$index][3] = $v[3].$path;
+ $path = '';
+ //Been there, done that.
+ $mapMatrix[$y][$x] = null;
+ //Move index
+ $index++;
+
+ break;
+ }
+ }
+ //Running out of seeds?
+ if (count($seed) < 2) {
+ $r['blocked'] = true;
+ $r['path'] = $seed[$key][3].$i;
+ $r['end'] = "$x,$y";
+ return $r;
+ }
+ //Lets not try this again.
+ unset($seed[$key]);
+ }
+ } while ( 1);
+ echo "Ran outa seeds.<br />";
+ print_r($seed);
+ return $mapMatrix;
+}
+
+
+/* UNUSED FUNCTION
+function GetTile($mapMatrix, $id)
+{
+ //Returns the location in $mapMatrix indicated by $id
+ $toReturn = &$mapMatrix [ (int)($id / $mapMatrix[0][0]) ]
+ [ $id % $mapMatrix[0][0] ];
+
+ return $toReturn;
+}
+ */
+
+//Routes a path through all checkpoints and teleports, returning an array.
+// [path] path-string. [blocked] boolean, [moves] int.
+function routePath($mygrid, $start = '') {
+
+ //== This should grab the start positions by scaning the map.
+ if ($start == '') {
+ for ($i = 1; $i <= $mygrid[0][1]; $i++) {
+ $start .= "0,$i.";
+ }
+ }
+
+ //Checkpoint names
+ $cpnames = Array("a", "b", "c", "d", "e");
+ //Get the amount of checkpoints on this map.
+ $cpcount = $mygrid[0][2];
+
+ //Add the existing checkpoints to targets.
+ for($p = 0; $p < $cpcount; $p++) {
+ $target[] = $cpnames[$p];
+ }
+ //Always need the finish line.
+ $target[] = 'f';
+
+ //Assume that we're not blocked, and raise a red flag later.
+ $blocked = false;
+
+
+ //All possible teleports in play.
+ $tpnames = Array('t', 'm', 'g', 'i', 'k');
+
+ $tpcount = intval($mygrid[0][5] * .5);
+ //Add the existing checkpoints to targets.
+ for($p = 0; $p < $tpcount; $p++) {
+ $teleport[] = $tpnames[$p];
+ }
+
+ $teleout['t'] = 'u';
+ $teleout['m'] = 'n';
+ $teleout['g'] = 'h';
+ $teleout['i'] = 'j';
+ $teleout['k'] = 'l';
+
+ //$r['tparray'] = $teleport;
+ //$r['cparray'] = $target;
+
+ //Loop through all the targets.
+ foreach($target as $t) {
+ //Path from where we are, to the target.
+ $p = Findpath ($mygrid, $start, $t);
+ //It's possible to start from multiple places;
+ //so mark where we ended up starting from.
+ if ($r['start'] == '')
+ $r['start'] = $p['start'];
+
+ //$f = 0;
+ //1449
+ //2263
+ do {
+ //Make sure there is a teleport to search.
+ if (! is_array($teleport))
+ break 1;
+ //Search through the path to find first teleport hit, if any.
+
+ $pathary = str_split($p['path']);
+
+ //As per usual, it's best to assume that you've failed.
+ $foundtele = false;
+ //Search through pathary and compare all existing teleports.
+ foreach ($pathary as $position => $char) {
+ foreach ($teleport as $ktel => $port) {
+ //$r['z'] .= ';'.$f++;
+ if ($port == $char) {
+ //Disable teleport
+ //$teleport[$ktel] = '';
+ unset($teleport[$ktel]);
+ //$teleport = array_values($teleport);
+ //We found it
+ $foundtele = true;
+ break 2;
+ }
+ }
+ }
+ if ($foundtele == false) {
+ break 1;
+ }
+
+
+ $outchar = $teleout[$port];
+ if ($position === false) continue;
+ //if ($teleactive[$port] === false) continue;
+ //Where is the tele $out location.
+ $x = Findpath($mygrid, $start, $outchar);
+ $out = $x['end'];
+ if ($x['blocked']) $blocked = true; //Optional?
+
+ //New path starting from our out-location.
+ $z = Findpath($mygrid, $out, $t);
+ if ($z['blocked']) $blocked = true; //Optional?
+
+ //Deactivate teleport
+ $teleactive[$port] = false;
+ //$r['debug'] = "TPD: $port";
+
+ //Apply modified path, and warp-cordinates.
+ //123 _Tele_ 222
+ //123
+ $p['path'] = substr($p['path'], 0, $position + 1);
+ //123
+ //123 U CORDS U
+ $p['path'] .= $outchar.$out.$outchar;
+ //123 U CORDS U
+ //123 U CORDS U 2322
+ $p['path'] .= $z['path'];
+
+ $movesoffset -= countmoves($out);
+ //}
+ } while ($foundtele);
+
+ //$start = explode(",", $p['end']);
+ $start = $p['end'];
+ if ($p['blocked']) $blocked = true;
+ $tpath .= $t.$p['path'].'r';
+ }
+ $r['blocked'] = $blocked;
+ $r['path'] = $tpath;
+ //$moves = count_chars($tpath, 0);
+ $moves = countmoves($tpath);
+ $moves += $movesoffset;
+ $r['moves'] = $moves;
+ //$r['moves'] = print_r($moves);
+ return $r;
+}
+//For use with routepath;
+function cmp($a, $b) {
+ if ($a === false) $a = 10000;
+ if ($b === false) $b = 10000;
+ if ($a == $b) {
+ return 0;
+ }
+ return ($a < $b) ? -1 : 1;
+}
+//For use with routepath;
+function countmoves($path) {
+ $moves = substr_count($path, '1');
+ $moves += substr_count($path, '2');
+ $moves += substr_count($path, '3');
+ $moves += substr_count($path, '4');
+ return $moves;
+}
+
+//Returns a random selection of one of the arguements.
+function weight() {
+ $weights = func_get_args();
+ return $weights[rand(0, (count($weights) -1))];
+}
+
+
+?>
diff --git a/includes/openid.php b/includes/openid.php new file mode 100644 index 0000000..85af9a8 --- /dev/null +++ b/includes/openid.php @@ -0,0 +1,740 @@ +<?php +/** + * This class provides a simple interface for OpenID (1.1 and 2.0) authentication. + * Supports Yadis discovery. + * The authentication process is stateless/dumb. + * + * Usage: + * Sign-on with OpenID is a two step process: + * Step one is authentication with the provider: + * <code> + * $openid = new LightOpenID; + * $openid->identity = 'ID supplied by user'; + * header('Location: ' . $openid->authUrl()); + * </code> + * The provider then sends various parameters via GET, one of them is openid_mode. + * Step two is verification: + * <code> + * if ($this->data['openid_mode']) { + * $openid = new LightOpenID; + * echo $openid->validate() ? 'Logged in.' : 'Failed'; + * } + * </code> + * + * Optionally, you can set $returnUrl and $realm (or $trustRoot, which is an alias). + * The default values for those are: + * $openid->realm = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; + * $openid->returnUrl = $openid->realm . $_SERVER['REQUEST_URI']; + * If you don't know their meaning, refer to any openid tutorial, or specification. Or just guess. + * + * AX and SREG extensions are supported. + * To use them, specify $openid->required and/or $openid->optional before calling $openid->authUrl(). + * These are arrays, with values being AX schema paths (the 'path' part of the URL). + * For example: + * $openid->required = array('namePerson/friendly', 'contact/email'); + * $openid->optional = array('namePerson/first'); + * If the server supports only SREG or OpenID 1.1, these are automaticaly + * mapped to SREG names, so that user doesn't have to know anything about the server. + * + * To get the values, use $openid->getAttributes(). + * + * + * The library requires PHP >= 5.1.2 with curl or http/https stream wrappers enabled. + * @author Mewp + * @copyright Copyright (c) 2010, Mewp + * @license http://www.opensource.org/licenses/mit-license.php MIT + */ +class LightOpenID +{ + public $returnUrl + , $required = array() + , $optional = array() + , $verify_peer = null + , $capath = null + , $cainfo = null; + private $identity, $claimed_id; + protected $server, $version, $trustRoot, $aliases, $identifier_select = false + , $ax = false, $sreg = false, $data; + static protected $ax_to_sreg = array( + 'namePerson/friendly' => 'nickname', + 'contact/email' => 'email', + 'namePerson' => 'fullname', + 'birthDate' => 'dob', + 'person/gender' => 'gender', + 'contact/postalCode/home' => 'postcode', + 'contact/country/home' => 'country', + 'pref/language' => 'language', + 'pref/timezone' => 'timezone', + ); + + function __construct() + { + $this->trustRoot = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; + $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?'); + $this->returnUrl = $this->trustRoot . $uri; + + $this->data = $_POST + $_GET; # OPs may send data as POST or GET. + } + + function __set($name, $value) + { + switch ($name) { + case 'identity': + if (strlen($value = trim((String) $value))) { + if (preg_match('#^xri:/*#i', $value, $m)) { + $value = substr($value, strlen($m[0])); + } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) { + $value = "http://$value"; + } + if (preg_match('#^https?://[^/]+$#i', $value, $m)) { + $value .= '/'; + } + } + $this->$name = $this->claimed_id = $value; + break; + case 'trustRoot': + case 'realm': + $this->trustRoot = trim($value); + } + } + + function __get($name) + { + switch ($name) { + case 'identity': + # We return claimed_id instead of identity, + # because the developer should see the claimed identifier, + # i.e. what he set as identity, not the op-local identifier (which is what we verify) + return $this->claimed_id; + case 'trustRoot': + case 'realm': + return $this->trustRoot; + case 'mode': + return empty($this->data['openid_mode']) ? null : $this->data['openid_mode']; + } + } + + /** + * Checks if the server specified in the url exists. + * + * @param $url url to check + * @return true, if the server exists; false otherwise + */ + function hostExists($url) + { + if (strpos($url, '/') === false) { + $server = $url; + } else { + $server = @parse_url($url, PHP_URL_HOST); + } + + if (!$server) { + return false; + } + + return !!gethostbynamel($server); + } + + protected function request_curl($url, $method='GET', $params=array()) + { + $params = http_build_query($params, '', '&'); + $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_HEADER, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); + + if($this->verify_peer !== null) { + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer); + if($this->capath) { + curl_setopt($curl, CURLOPT_CAPATH, $this->capath); + } + + if($this->cainfo) { + curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo); + } + } + + if ($method == 'POST') { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $params); + } elseif ($method == 'HEAD') { + curl_setopt($curl, CURLOPT_HEADER, true); + curl_setopt($curl, CURLOPT_NOBODY, true); + } else { + curl_setopt($curl, CURLOPT_HTTPGET, true); + } + $response = curl_exec($curl); + + if($method == 'HEAD') { + $headers = array(); + foreach(explode("\n", $response) as $header) { + $pos = strpos($header,':'); + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + } + + # Updating claimed_id in case of redirections. + $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); + if($effective_url != $url) { + $this->identity = $this->claimed_id = $effective_url; + } + + return $headers; + } + + if (curl_errno($curl)) { + throw new ErrorException(curl_error($curl), curl_errno($curl)); + } + + return $response; + } + + protected function request_streams($url, $method='GET', $params=array()) + { + if(!$this->hostExists($url)) { + throw new ErrorException('Invalid request.'); + } + + $params = http_build_query($params, '', '&'); + switch($method) { + case 'GET': + $opts = array( + 'http' => array( + 'method' => 'GET', + 'header' => 'Accept: application/xrds+xml, */*', + 'ignore_errors' => true, + ) + ); + $url = $url . ($params ? '?' . $params : ''); + break; + case 'POST': + $opts = array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $params, + 'ignore_errors' => true, + ) + ); + break; + case 'HEAD': + # We want to send a HEAD request, + # but since get_headers doesn't accept $context parameter, + # we have to change the defaults. + $default = stream_context_get_options(stream_context_get_default()); + stream_context_get_default( + array('http' => array( + 'method' => 'HEAD', + 'header' => 'Accept: application/xrds+xml, */*', + 'ignore_errors' => true, + )) + ); + + $url = $url . ($params ? '?' . $params : ''); + $headers_tmp = get_headers ($url); + if(!$headers_tmp) { + return array(); + } + + # Parsing headers. + $headers = array(); + foreach($headers_tmp as $header) { + $pos = strpos($header,':'); + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + + # Following possible redirections. The point is just to have + # claimed_id change with them, because get_headers() will + # follow redirections automatically. + # We ignore redirections with relative paths. + # If any known provider uses them, file a bug report. + if($name == 'location') { + if(strpos($headers[$name], 'http') === 0) { + $this->identity = $this->claimed_id = $headers[$name]; + } elseif($headers[$name][0] == '/') { + $parsed_url = parse_url($this->claimed_id); + $this->identity = + $this->claimed_id = $parsed_url['scheme'] . '://' + . $parsed_url['host'] + . $headers[$name]; + } + } + } + + # And restore them. + stream_context_get_default($default); + return $headers; + } + + if($this->verify_peer) { + $opts += array('ssl' => array( + 'verify_peer' => true, + 'capath' => $this->capath, + 'cafile' => $this->cainfo, + )); + } + + $context = stream_context_create ($opts); + + return file_get_contents($url, false, $context); + } + + protected function request($url, $method='GET', $params=array()) + { + if(function_exists('curl_init') && !ini_get('safe_mode')) { + return $this->request_curl($url, $method, $params); + } + return $this->request_streams($url, $method, $params); + } + + protected function build_url($url, $parts) + { + if (isset($url['query'], $parts['query'])) { + $parts['query'] = $url['query'] . '&' . $parts['query']; + } + + $url = $parts + $url; + $url = $url['scheme'] . '://' + . (empty($url['username'])?'' + :(empty($url['password'])? "{$url['username']}@" + :"{$url['username']}:{$url['password']}@")) + . $url['host'] + . (empty($url['port'])?'':":{$url['port']}") + . (empty($url['path'])?'':$url['path']) + . (empty($url['query'])?'':"?{$url['query']}") + . (empty($url['fragment'])?'':"#{$url['fragment']}"); + return $url; + } + + /** + * Helper function used to scan for <meta>/<link> tags and extract information + * from them + */ + protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName) + { + preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1); + preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2); + + $result = array_merge($matches1[1], $matches2[1]); + return empty($result)?false:$result[0]; + } + + /** + * Performs Yadis and HTML discovery. Normally not used. + * @param $url Identity URL. + * @return String OP Endpoint (i.e. OpenID provider address). + * @throws ErrorException + */ + function discover($url) + { + if (!$url) throw new ErrorException('No identity supplied.'); + # Use xri.net proxy to resolve i-name identities + if (!preg_match('#^https?:#', $url)) { + $url = "https://xri.net/$url"; + } + + # We save the original url in case of Yadis discovery failure. + # It can happen when we'll be lead to an XRDS document + # which does not have any OpenID2 services. + $originalUrl = $url; + + # A flag to disable yadis discovery in case of failure in headers. + $yadis = true; + + # We'll jump a maximum of 5 times, to avoid endless redirections. + for ($i = 0; $i < 5; $i ++) { + if ($yadis) { + $headers = $this->request($url, 'HEAD'); + + $next = false; + if (isset($headers['x-xrds-location'])) { + $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location']))); + $next = true; + } + + if (isset($headers['content-type']) + && (strpos($headers['content-type'], 'application/xrds+xml') !== false + || strpos($headers['content-type'], 'text/xml') !== false) + ) { + # Apparently, some providers return XRDS documents as text/html. + # While it is against the spec, allowing this here shouldn't break + # compatibility with anything. + # --- + # Found an XRDS document, now let's find the server, and optionally delegate. + $content = $this->request($url, 'GET'); + + preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m); + foreach($m[1] as $content) { + $content = ' ' . $content; # The space is added, so that strpos doesn't return 0. + + # OpenID 2 + $ns = preg_quote('http://specs.openid.net/auth/2.0/'); + if(preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) { + if ($type[1] == 'server') $this->identifier_select = true; + + preg_match('#<URI.*?>(.*)</URI>#', $content, $server); + preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate); + if (empty($server)) { + return false; + } + # Does the server advertise support for either AX or SREG? + $this->ax = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>'); + $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>') + || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>'); + + $server = $server[1]; + if (isset($delegate[2])) $this->identity = trim($delegate[2]); + $this->version = 2; + + $this->server = $server; + return $server; + } + + # OpenID 1.1 + $ns = preg_quote('http://openid.net/signon/1.1'); + if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) { + + preg_match('#<URI.*?>(.*)</URI>#', $content, $server); + preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate); + if (empty($server)) { + return false; + } + # AX can be used only with OpenID 2.0, so checking only SREG + $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>') + || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>'); + + $server = $server[1]; + if (isset($delegate[1])) $this->identity = $delegate[1]; + $this->version = 1; + + $this->server = $server; + return $server; + } + } + + $next = true; + $yadis = false; + $url = $originalUrl; + $content = null; + break; + } + if ($next) continue; + + # There are no relevant information in headers, so we search the body. + $content = $this->request($url, 'GET'); + $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content'); + if ($location) { + $url = $this->build_url(parse_url($url), parse_url($location)); + continue; + } + } + + if (!$content) $content = $this->request($url, 'GET'); + + # At this point, the YADIS Discovery has failed, so we'll switch + # to openid2 HTML discovery, then fallback to openid 1.1 discovery. + $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href'); + $this->version = 2; + + if (!$server) { + # The same with openid 1.1 + $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href'); + $this->version = 1; + } + + if ($server) { + # We found an OpenID2 OP Endpoint + if ($delegate) { + # We have also found an OP-Local ID. + $this->identity = $delegate; + } + $this->server = $server; + return $server; + } + + throw new ErrorException('No servers found!'); + } + throw new ErrorException('Endless redirection!'); + } + + protected function sregParams() + { + $params = array(); + # We always use SREG 1.1, even if the server is advertising only support for 1.0. + # That's because it's fully backwards compatibile with 1.0, and some providers + # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com + $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1'; + if ($this->required) { + $params['openid.sreg.required'] = array(); + foreach ($this->required as $required) { + if (!isset(self::$ax_to_sreg[$required])) continue; + $params['openid.sreg.required'][] = self::$ax_to_sreg[$required]; + } + $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']); + } + + if ($this->optional) { + $params['openid.sreg.optional'] = array(); + foreach ($this->optional as $optional) { + if (!isset(self::$ax_to_sreg[$optional])) continue; + $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional]; + } + $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']); + } + return $params; + } + + protected function axParams() + { + $params = array(); + if ($this->required || $this->optional) { + $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0'; + $params['openid.ax.mode'] = 'fetch_request'; + $this->aliases = array(); + $counts = array(); + $required = array(); + $optional = array(); + foreach (array('required','optional') as $type) { + foreach ($this->$type as $alias => $field) { + if (is_int($alias)) $alias = strtr($field, '/', '_'); + $this->aliases[$alias] = 'http://axschema.org/' . $field; + if (empty($counts[$alias])) $counts[$alias] = 0; + $counts[$alias] += 1; + ${$type}[] = $alias; + } + } + foreach ($this->aliases as $alias => $ns) { + $params['openid.ax.type.' . $alias] = $ns; + } + foreach ($counts as $alias => $count) { + if ($count == 1) continue; + $params['openid.ax.count.' . $alias] = $count; + } + + # Don't send empty ax.requied and ax.if_available. + # Google and possibly other providers refuse to support ax when one of these is empty. + if($required) { + $params['openid.ax.required'] = implode(',', $required); + } + if($optional) { + $params['openid.ax.if_available'] = implode(',', $optional); + } + } + return $params; + } + + protected function authUrl_v1() + { + $returnUrl = $this->returnUrl; + # If we have an openid.delegate that is different from our claimed id, + # we need to somehow preserve the claimed id between requests. + # The simplest way is to just send it along with the return_to url. + if($this->identity != $this->claimed_id) { + $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id; + } + + $params = array( + 'openid.return_to' => $returnUrl, + 'openid.mode' => 'checkid_setup', + 'openid.identity' => $this->identity, + 'openid.trust_root' => $this->trustRoot, + ) + $this->sregParams(); + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + protected function authUrl_v2($identifier_select) + { + $params = array( + 'openid.ns' => 'http://specs.openid.net/auth/2.0', + 'openid.mode' => 'checkid_setup', + 'openid.return_to' => $this->returnUrl, + 'openid.realm' => $this->trustRoot, + ); + if ($this->ax) { + $params += $this->axParams(); + } + if ($this->sreg) { + $params += $this->sregParams(); + } + if (!$this->ax && !$this->sreg) { + # If OP doesn't advertise either SREG, nor AX, let's send them both + # in worst case we don't get anything in return. + $params += $this->axParams() + $this->sregParams(); + } + + if ($identifier_select) { + $params['openid.identity'] = $params['openid.claimed_id'] + = 'http://specs.openid.net/auth/2.0/identifier_select'; + } else { + $params['openid.identity'] = $this->identity; + $params['openid.claimed_id'] = $this->claimed_id; + } + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + /** + * Returns authentication url. Usually, you want to redirect your user to it. + * @return String The authentication url. + * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1. + * @throws ErrorException + */ + function authUrl($identifier_select = null) + { + if (!$this->server) $this->discover($this->identity); + + if ($this->version == 2) { + if ($identifier_select === null) { + return $this->authUrl_v2($this->identifier_select); + } + return $this->authUrl_v2($identifier_select); + } + return $this->authUrl_v1(); + } + + /** + * Performs OpenID verification with the OP. + * @return Bool Whether the verification was successful. + * @throws ErrorException + */ + function validate() + { + $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity']; + $params = array( + 'openid.assoc_handle' => $this->data['openid_assoc_handle'], + 'openid.signed' => $this->data['openid_signed'], + 'openid.sig' => $this->data['openid_sig'], + ); + + if (isset($this->data['openid_ns'])) { + # We're dealing with an OpenID 2.0 server, so let's set an ns + # Even though we should know location of the endpoint, + # we still need to verify it by discovery, so $server is not set here + $params['openid.ns'] = 'http://specs.openid.net/auth/2.0'; + } elseif (isset($this->data['openid_claimed_id']) + && $this->data['openid_claimed_id'] != $this->data['openid_identity'] + ) { + # If it's an OpenID 1 provider, and we've got claimed_id, + # we have to append it to the returnUrl, like authUrl_v1 does. + $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') + . 'openid.claimed_id=' . $this->claimed_id; + } + + if ($this->data['openid_return_to'] != $this->returnUrl) { + # The return_to url must match the url of current request. + # I'm assuing that noone will set the returnUrl to something that doesn't make sense. + return false; + } + + $server = $this->discover($this->claimed_id); + + foreach (explode(',', $this->data['openid_signed']) as $item) { + # Checking whether magic_quotes_gpc is turned on, because + # the function may fail if it is. For example, when fetching + # AX namePerson, it might containg an apostrophe, which will be escaped. + # In such case, validation would fail, since we'd send different data than OP + # wants to verify. stripslashes() should solve that problem, but we can't + # use it when magic_quotes is off. + $value = $this->data['openid_' . str_replace('.','_',$item)]; + $params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($value) : $value; + + } + + $params['openid.mode'] = 'check_authentication'; + + $response = $this->request($server, 'POST', $params); + + return preg_match('/is_valid\s*:\s*true/i', $response); + } + + protected function getAxAttributes() + { + $alias = null; + if (isset($this->data['openid_ns_ax']) + && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0' + ) { # It's the most likely case, so we'll check it before + $alias = 'ax'; + } else { + # 'ax' prefix is either undefined, or points to another extension, + # so we search for another prefix + foreach ($this->data as $key => $val) { + if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_' + && $val == 'http://openid.net/srv/ax/1.0' + ) { + $alias = substr($key, strlen('openid_ns_')); + break; + } + } + } + if (!$alias) { + # An alias for AX schema has not been found, + # so there is no AX data in the OP's response + return array(); + } + + $attributes = array(); + foreach ($this->data as $key => $value) { + $keyMatch = 'openid_' . $alias . '_value_'; + if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { + continue; + } + $key = substr($key, strlen($keyMatch)); + if (!isset($this->data['openid_' . $alias . '_type_' . $key])) { + # OP is breaking the spec by returning a field without + # associated ns. This shouldn't happen, but it's better + # to check, than cause an E_NOTICE. + continue; + } + $key = substr($this->data['openid_' . $alias . '_type_' . $key], + strlen('http://axschema.org/')); + $attributes[$key] = $value; + } + return $attributes; + } + + protected function getSregAttributes() + { + $attributes = array(); + $sreg_to_ax = array_flip(self::$ax_to_sreg); + foreach ($this->data as $key => $value) { + $keyMatch = 'openid_sreg_'; + if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { + continue; + } + $key = substr($key, strlen($keyMatch)); + if (!isset($sreg_to_ax[$key])) { + # The field name isn't part of the SREG spec, so we ignore it. + continue; + } + $attributes[$sreg_to_ax[$key]] = $value; + } + return $attributes; + } + + /** + * Gets AX/SREG attributes provided by OP. should be used only after successful validaton. + * Note that it does not guarantee that any of the required/optional parameters will be present, + * or that there will be no other attributes besides those specified. + * In other words. OP may provide whatever information it wants to. + * * SREG names will be mapped to AX names. + * * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email' + * @see http://www.axschema.org/types/ + */ + function getAttributes() + { + if (isset($this->data['openid_ns']) + && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0' + ) { # OpenID 2.0 + # We search for both AX and SREG attributes, with AX taking precedence. + return $this->getAxAttributes() + $this->getSregAttributes(); + } + return $this->getSregAttributes(); + } +} diff --git a/includes/pathing.php b/includes/pathing.php new file mode 100644 index 0000000..fc07f0b --- /dev/null +++ b/includes/pathing.php @@ -0,0 +1,108 @@ +<?PHP
+//
+function FindPath($mapMatrix)
+{
+ //FindPath will generate a string consisting of the moves made by the
+ // puppy to reach each checkpoint and then the finish.
+
+ $status = array(); //This stores the search status of each tile
+ // in the grid.
+ //-2 - Unprocessed; -1 - Queued; [x] - Processed/Previous tile
+
+ $queue = array(); //This is the order to check tiles in, to
+ // prevent overcommitting. Stores TileID.
+
+ $targets = array(); //This is the queue of targets the path must connect. Flags.
+
+ $finish = array(); //This is the set of finish tiles. Stores TileID.
+
+ $path = ""; //This is a string of the moves taken by the
+ // puppy!
+ //1 - Up; 2 - Right; 3 - Down; 4 - Left
+
+ //Initialize $status
+ for( $i = 0; $i < count($mapMatrix); $i++)
+ {
+ $status[i] = array();
+ for( $j = 0; $j < count($mapMatrix[$i]); $j++)
+ {
+ $status[i][j] = -1;
+ }
+ }
+
+ //Initialize $queue with tiles adjacent to Starts
+ //Assuming the LEFT column is entirely composed of Start tiles...
+ // NOTE: This is what we would change should the Start tiles become different.
+ for( $i = 1; $i <= $mapMatrix[0][1]; $i++)
+ {
+ $status[1][$i] = 0;
+ $nextTile = GetTileID($mapMatrix, 2, $i);
+ $queue[($i-1)] = $nextTile;
+ }
+
+ //Initialize $finish queue with Finish tiles.
+ //Assuming the RIGHT column is entirely composed of Finish tiles...
+ // NOTE: This is what we would change should the Finish tiles become different.
+ for( $i = 1; $i <= $mapMatrix[0][1]; $i++)
+ {
+ echo "Tile #".GetTileID($mapMatrix, $mapMatrix[0][0] - 1, $i)." has been marked as a Finish tile.<br />";
+ $nextTile = GetTileID($mapMatrix, $mapMatrix[0][0] - 1, $i);
+ $finish[($i-1)] = $nextTile;
+ }
+
+ //Initialize $targets with Checkpoints and Finish.
+ switch($mapMatrix[0][2])
+ {
+ case 3: array_push($targets, 'C');
+ case 2: array_push($targets, 'B');
+ case 1: array_push($targets, 'A');
+ }
+ array_reverse($targets);
+ array_push($targets, 'Finish');
+
+ print_r($queue);
+ echo "<br />";
+
+ while(count($queue) > 0)
+ {
+ $nextSearch = array_shift($queue);
+ $idFinish = array_shift($targets);
+ }
+
+ /*
+ echo "Pre-PrintArray. <br />";
+ print_r($queue);
+ echo "Post-PrintArray. <br />";
+ */
+
+ //Search($mapMatrix, $loc, $path);
+
+ return $path;
+}
+
+function Search($mapMatrix, $idStart, $idFinish, $path)
+{
+
+}
+
+function GetTileID($mapMatrix, $x, $y)
+{
+ //echo "Request for TileID of (".$x.",".$y."): ";
+ if($mapMatrix[0][0] >= $x && $mapMatrix[0][1] >= $y)
+ return $mapMatrix[0][0] * ($y-1) + $x;
+ else return -1;
+}
+
+//WOULD be a function if not for overhead of calling a function and
+// inconvenience of returning an array. Here to display formula.
+
+function GetTileCoordinates($mapMatrix, $tileID)
+{
+ $x = $tileID % $mapMatrix[0][0];
+ $y = (int)($tileID / $mapMatrix[0][0]) + 1;
+
+ echo "(".$x.",".$y.")";
+ echo "<br />";
+}
+
+?>
\ No newline at end of file |